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

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.39    ! anton    1020: @cindex --appl-image, command-line option
        !          1021: @item --appl-image @i{file}
        !          1022: Loads the image @i{file} and leaves all further command-line arguments
        !          1023: to the image (instead of processing them as options).  This is useful
        !          1024: for building executable application images on Unix, built with
        !          1025: @code{gforthmi --application ...}.
        !          1026: 
1.29      crook    1027: @cindex --path, command-line option
                   1028: @cindex -p, command-line option
                   1029: @item --path @i{path}
                   1030: @itemx -p @i{path}
                   1031: Uses @i{path} for searching the image file and Forth source code files
                   1032: instead of the default in the environment variable @code{GFORTHPATH} or
                   1033: the path specified at installation time (e.g.,
                   1034: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                   1035: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook    1036: 
1.29      crook    1037: @cindex --dictionary-size, command-line option
                   1038: @cindex -m, command-line option
                   1039: @cindex @i{size} parameters for command-line options
                   1040: @cindex size of the dictionary and the stacks
                   1041: @item --dictionary-size @i{size}
                   1042: @itemx -m @i{size}
                   1043: Allocate @i{size} space for the Forth dictionary space instead of
                   1044: using the default specified in the image (typically 256K). The
                   1045: @i{size} specification for this and subsequent options consists of
                   1046: an integer and a unit (e.g.,
                   1047: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                   1048: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                   1049: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                   1050: @code{e} is used.
1.21      crook    1051: 
1.29      crook    1052: @cindex --data-stack-size, command-line option
                   1053: @cindex -d, command-line option
                   1054: @item --data-stack-size @i{size}
                   1055: @itemx -d @i{size}
                   1056: Allocate @i{size} space for the data stack instead of using the
                   1057: default specified in the image (typically 16K).
1.21      crook    1058: 
1.29      crook    1059: @cindex --return-stack-size, command-line option
                   1060: @cindex -r, command-line option
                   1061: @item --return-stack-size @i{size}
                   1062: @itemx -r @i{size}
                   1063: Allocate @i{size} space for the return stack instead of using the
                   1064: default specified in the image (typically 15K).
1.21      crook    1065: 
1.29      crook    1066: @cindex --fp-stack-size, command-line option
                   1067: @cindex -f, command-line option
                   1068: @item --fp-stack-size @i{size}
                   1069: @itemx -f @i{size}
                   1070: Allocate @i{size} space for the floating point stack instead of
                   1071: using the default specified in the image (typically 15.5K). In this case
                   1072: the unit specifier @code{e} refers to floating point numbers.
1.21      crook    1073: 
1.29      crook    1074: @cindex --locals-stack-size, command-line option
                   1075: @cindex -l, command-line option
                   1076: @item --locals-stack-size @i{size}
                   1077: @itemx -l @i{size}
                   1078: Allocate @i{size} space for the locals stack instead of using the
                   1079: default specified in the image (typically 14.5K).
1.21      crook    1080: 
1.29      crook    1081: @cindex -h, command-line option
                   1082: @cindex --help, command-line option
                   1083: @item --help
                   1084: @itemx -h
                   1085: Print a message about the command-line options
1.21      crook    1086: 
1.29      crook    1087: @cindex -v, command-line option
                   1088: @cindex --version, command-line option
                   1089: @item --version
                   1090: @itemx -v
                   1091: Print version and exit
1.21      crook    1092: 
1.29      crook    1093: @cindex --debug, command-line option
                   1094: @item --debug
                   1095: Print some information useful for debugging on startup.
1.21      crook    1096: 
1.29      crook    1097: @cindex --offset-image, command-line option
                   1098: @item --offset-image
                   1099: Start the dictionary at a slightly different position than would be used
                   1100: otherwise (useful for creating data-relocatable images,
                   1101: @pxref{Data-Relocatable Image Files}).
1.21      crook    1102: 
1.29      crook    1103: @cindex --no-offset-im, command-line option
                   1104: @item --no-offset-im
                   1105: Start the dictionary at the normal position.
1.21      crook    1106: 
1.29      crook    1107: @cindex --clear-dictionary, command-line option
                   1108: @item --clear-dictionary
                   1109: Initialize all bytes in the dictionary to 0 before loading the image
                   1110: (@pxref{Data-Relocatable Image Files}).
                   1111: 
                   1112: @cindex --die-on-signal, command-line-option
                   1113: @item --die-on-signal
                   1114: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                   1115: or the segmentation violation SIGSEGV) by translating it into a Forth
                   1116: @code{THROW}. With this option, Gforth exits if it receives such a
                   1117: signal. This option is useful when the engine and/or the image might be
                   1118: severely broken (such that it causes another signal before recovering
                   1119: from the first); this option avoids endless loops in such cases.
                   1120: @end table
                   1121: 
                   1122: @cindex loading files at startup
                   1123: @cindex executing code on startup
                   1124: @cindex batch processing with Gforth
                   1125: As explained above, the image-specific command-line arguments for the
                   1126: default image @file{gforth.fi} consist of a sequence of filenames and
                   1127: @code{-e @var{forth-code}} options that are interpreted in the sequence
                   1128: in which they are given. The @code{-e @var{forth-code}} or
                   1129: @code{--evaluate @var{forth-code}} option evaluates the Forth
                   1130: code. This option takes only one argument; if you want to evaluate more
                   1131: Forth words, you have to quote them or use @code{-e} several times. To exit
                   1132: after processing the command line (instead of entering interactive mode)
                   1133: append @code{-e bye} to the command line.
                   1134: 
                   1135: @cindex versions, invoking other versions of Gforth
                   1136: If you have several versions of Gforth installed, @code{gforth} will
                   1137: invoke the version that was installed last. @code{gforth-@i{version}}
                   1138: invokes a specific version. You may want to use the option
                   1139: @code{--path}, if your environment contains the variable
                   1140: @code{GFORTHPATH}.
                   1141: 
                   1142: Not yet implemented:
                   1143: On startup the system first executes the system initialization file
                   1144: (unless the option @code{--no-init-file} is given; note that the system
                   1145: resulting from using this option may not be ANS Forth conformant). Then
                   1146: the user initialization file @file{.gforth.fs} is executed, unless the
                   1147: option @code{--no-rc} is given; this file is first searched in @file{.},
                   1148: then in @file{~}, then in the normal path (see above).
1.21      crook    1149: 
                   1150: 
                   1151: 
1.29      crook    1152: @comment ----------------------------------------------
                   1153: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                   1154: @section Leaving Gforth
                   1155: @cindex Gforth - leaving
                   1156: @cindex leaving Gforth
1.21      crook    1157: 
1.30      anton    1158: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                   1159: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                   1160: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
                   1161: data are discarded. @xref{Image Files} for ways of saving the state of
                   1162: the system before leaving Gforth.
1.21      crook    1163: 
1.29      crook    1164: doc-bye
1.21      crook    1165: 
1.29      crook    1166: @comment ----------------------------------------------
                   1167: @node Command-line editing, Upper and lower case,Leaving Gforth,Gforth Environment
                   1168: @section Command-line editing
                   1169: @cindex command-line editing
1.21      crook    1170: 
1.29      crook    1171: Gforth maintains a history file that records every line that you type to
                   1172: the text interpreter. This file is preserved between sessions, and is
                   1173: used to provide a command-line recall facility; if you type ctrl-P
                   1174: repeatedly you can recall successively older commands from this (or
                   1175: previous) session(s). The full list of command-line editing facilities is:
1.21      crook    1176: 
1.30      anton    1177: @comment use @table? - anton
1.21      crook    1178: @itemize @bullet
                   1179: @item
1.30      anton    1180: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
1.29      crook    1181: commands from the history buffer.
                   1182: @item
1.30      anton    1183: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
1.29      crook    1184: from the history buffer.
                   1185: @item
1.30      anton    1186: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
1.29      crook    1187: @item
1.30      anton    1188: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
1.29      crook    1189: @item
1.30      anton    1190: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
1.29      crook    1191: closing up the line.
                   1192: @item
1.30      anton    1193: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
1.29      crook    1194: @item
1.30      anton    1195: @kbd{Ctrl-a} to move the cursor to the start of the line.
1.21      crook    1196: @item
1.30      anton    1197: @kbd{Ctrl-e} to move the cursor to the end of the line.
1.21      crook    1198: @item
1.30      anton    1199: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
1.29      crook    1200: line.
1.21      crook    1201: @item
1.30      anton    1202: @key{TAB} to step through all possible full-word completions of the word
1.29      crook    1203: currently being typed.
1.21      crook    1204: @item
1.30      anton    1205: @kbd{Ctrl-d} at the start of the line to terminate Gforth (gracefully,
                   1206: using @code{bye}).
1.21      crook    1207: @end itemize
                   1208: 
1.29      crook    1209: When editing, displayable characters are inserted to the left of the
                   1210: cursor position; the line is always in ``insert'' (as opposed to
                   1211: ``overstrike'') mode.
                   1212: 
                   1213: @cindex history file
                   1214: @cindex @file{.gforth-history}
                   1215: On Unix systems, the history file is @file{~/.gforth-history} by
                   1216: default@footnote{i.e. it is stored in the user's home directory.}. You
                   1217: can find out the name and location of your history file using:
                   1218: 
                   1219: @example 
                   1220: history-file type \ Unix-class systems
1.21      crook    1221: 
1.29      crook    1222: history-file type \ Other systems
                   1223: history-dir  type
1.21      crook    1224: @end example
                   1225: 
1.29      crook    1226: If you enter long definitions by hand, you can use a text editor to
                   1227: paste them out of the history file into a Forth source file for reuse at
                   1228: a later time.
                   1229: 
                   1230: Gforth never trims the size of the history file, so you should do this
                   1231: periodically, if necessary.
                   1232: 
                   1233: @comment this is all defined in history.fs
                   1234: 
                   1235: 
                   1236: 
                   1237: @comment ----------------------------------------------
                   1238: @node Upper and lower case, Environment variables,Command-line editing,Gforth Environment
                   1239: @section Upper and lower case
                   1240: @cindex case-sensitivity
                   1241: @cindex upper and lower case
                   1242: 
                   1243: Gforth is case-insensitive, so you can enter definitions and invoke
                   1244: Standard words using upper, lower or mixed case (however,
                   1245: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   1246: options}).
                   1247: 
1.30      anton    1248: ANS Forth only @i{requires} implementations to recognise Standard words
                   1249: when they are typed entirely in upper case. Therefore, a Standard
                   1250: program must use upper case for all Standard words. You can use whatever
                   1251: case you like for words that you define, but in a standard program you
                   1252: have to use the words in the same case that you defined them.
                   1253: 
                   1254: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   1255: wordlists, @pxref{Word Lists}).
                   1256: 
                   1257: Two people have asked how to convert Gforth to case sensitivity; while
                   1258: we think this is a bad idea, you can change all wordlists into tables
                   1259: like this:
1.29      crook    1260: 
1.30      anton    1261: @example
                   1262: ' table-find forth-wordlist wordlist-map @ !
                   1263: @end example
                   1264: 
                   1265: Note that you now have to type the predefined words in the same case
                   1266: that we defined them, which are varying.  You may want to convert them
                   1267: to your favourite case before doing this operation (I won't explain how,
                   1268: because if you are even contemplating to do this, you'd better have
                   1269: enough knowledge of Forth systems to know this already).
1.29      crook    1270: 
                   1271: @comment ----------------------------------------------
                   1272: @node Environment variables, Gforth Files, Upper and lower case,Gforth Environment
                   1273: @section Environment variables
                   1274: @cindex environment variables
1.21      crook    1275: 
1.29      crook    1276: Gforth uses these environment variables:
1.21      crook    1277: 
1.29      crook    1278: @itemize @bullet
                   1279: @item
                   1280: @cindex GFORTHHIST - environment variable
                   1281: GFORTHHIST - (Unix systems only) specifies the directory in which to
                   1282: open/create the history file, @file{.gforth-history}. Default:
                   1283: @code{$HOME}.
1.21      crook    1284: 
1.29      crook    1285: @item
                   1286: @cindex GFORTHPATH - environment variable
                   1287: GFORTHPATH - specifies the path used when searching for the gforth image file and
                   1288: for Forth source-code files.
1.21      crook    1289: 
1.29      crook    1290: @item
                   1291: @cindex GFORTH - environment variable
                   1292: GFORTH - used by @file{gforthmi} @xref{gforthmi}.
1.26      crook    1293: 
1.29      crook    1294: @item
                   1295: @cindex GFORTHD - environment variable
                   1296: GFORTHD - used by @file{gforthmi} @xref{gforthmi}.
1.21      crook    1297: 
1.29      crook    1298: @item
                   1299: @cindex TMP, TEMP - environment variable
                   1300: TMP, TEMP - (non-Unix systems only) used as a potential location for the
                   1301: history file.
                   1302: @end itemize
1.21      crook    1303: 
1.29      crook    1304: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1305: @comment mentioning these.
1.21      crook    1306: 
1.29      crook    1307: All the Gforth environment variables default to sensible values if they
                   1308: are not set.
1.21      crook    1309: 
                   1310: 
1.29      crook    1311: @comment ----------------------------------------------
                   1312: @node Gforth Files, ,Environment variables,Gforth Environment
                   1313: @section Gforth files
                   1314: @cindex Gforth files
1.21      crook    1315: 
1.30      anton    1316: When you Gforth on a Unix system in the default places, it installs
                   1317: files in these locations:
1.21      crook    1318: 
1.26      crook    1319: @itemize @bullet
                   1320: @item
1.29      crook    1321: @file{/usr/local/bin/gforth}
                   1322: @item
                   1323: @file{/usr/local/bin/gforthmi}
                   1324: @item
                   1325: @file{/usr/local/man/man1/gforth.1} - man page.
                   1326: @item
                   1327: @file{/usr/local/info} - the Info version of this manual.
                   1328: @item
1.30      anton    1329: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1.29      crook    1330: @item
                   1331: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1.26      crook    1332: @item
1.30      anton    1333: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1.26      crook    1334: @item
1.30      anton    1335: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1.26      crook    1336: @end itemize
1.21      crook    1337: 
1.30      anton    1338: You can select different places for installation by using
                   1339: @code{configure} options (listed with @code{configure --help}).
1.21      crook    1340: 
1.29      crook    1341: @c ******************************************************************
                   1342: @node Introduction, Words, Gforth Environment, Top
                   1343: @comment node-name,     next,           previous, up
                   1344: @chapter An Introduction to ANS Forth
                   1345: @cindex Forth - an introduction
1.21      crook    1346: 
1.29      crook    1347: The primary purpose of this manual is to document Gforth. However, since
                   1348: Forth is not a widely-known language and there is a lack of up-to-date
                   1349: teaching material, it seems worthwhile to provide some introductory
                   1350: material. @xref{Forth-related information} for other sources of Forth-related
                   1351: information.
1.21      crook    1352: 
1.29      crook    1353: The examples in this section should work on any ANS Forth; the
                   1354: output shown was produced using Gforth. Each example attempts to
                   1355: reproduce the exact output that Gforth produces. If you try out the
                   1356: examples (and you should), what you should type is shown @kbd{like this}
                   1357: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    1358: that, where the example shows @key{RET} it means that you should
1.29      crook    1359: press the ``carriage return'' key. Unfortunately, some output formats for
                   1360: this manual cannot show the difference between @kbd{this} and
                   1361: @code{this} which will make trying out the examples harder (but not
                   1362: impossible).
1.21      crook    1363: 
1.29      crook    1364: Forth is an unusual language. It provides an interactive development
                   1365: environment which includes both an interpreter and compiler. Forth
                   1366: programming style encourages you to break a problem down into many
                   1367: @cindex factoring
                   1368: small fragments (@dfn{factoring}), and then to develop and test each
                   1369: fragment interactively. Forth advocates assert that breaking the
                   1370: edit-compile-test cycle used by conventional programming languages can
                   1371: lead to great productivity improvements.
1.21      crook    1372: 
1.29      crook    1373: @menu
                   1374: * Introducing the Text Interpreter::
                   1375: * Stacks and Postfix notation::
                   1376: * Your first definition::
                   1377: * How does that work?::
                   1378: * Forth is written in Forth::
                   1379: * Review - elements of a Forth system::
                   1380: * Where to go next::
                   1381: * Exercises::
                   1382: @end menu
1.21      crook    1383: 
1.29      crook    1384: @comment ----------------------------------------------
                   1385: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   1386: @section Introducing the Text Interpreter
                   1387: @cindex text interpreter
                   1388: @cindex outer interpreter
1.21      crook    1389: 
1.30      anton    1390: @c IMO this is too detailed and the pace is too slow for
                   1391: @c an introduction.  If you know German, take a look at
                   1392: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   1393: @c to see how I do it - anton 
                   1394: 
1.29      crook    1395: When you invoke the Forth image, you will see a startup banner printed
                   1396: and nothing else (if you have Gforth installed on your system, try
1.30      anton    1397: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    1398: its command line interpreter, which is called the @dfn{Text Interpreter}
                   1399: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.30      anton    1400: about the text interpreter as you read through this chapter, but
                   1401: @pxref{The Text Interpreter} for more detail).
1.21      crook    1402: 
1.29      crook    1403: Although it's not obvious, Forth is actually waiting for your
1.30      anton    1404: input. Type a number and press the @key{RET} key:
1.21      crook    1405: 
1.26      crook    1406: @example
1.30      anton    1407: @kbd{45@key{RET}}  ok
1.26      crook    1408: @end example
1.21      crook    1409: 
1.29      crook    1410: Rather than give you a prompt to invite you to input something, the text
                   1411: interpreter prints a status message @i{after} it has processed a line
                   1412: of input. The status message in this case (``@code{ ok}'' followed by
                   1413: carriage-return) indicates that the text interpreter was able to process
                   1414: all of your input successfully. Now type something illegal:
                   1415: 
                   1416: @example
1.30      anton    1417: @kbd{qwer341@key{RET}}
1.29      crook    1418: :1: Undefined word
                   1419: qwer341
                   1420: ^^^^^^^
                   1421: $400D2BA8 Bounce
                   1422: $400DBDA8 no.extensions
                   1423: @end example
1.23      crook    1424: 
1.29      crook    1425: The exact text, other than the ``Undefined word'' may differ slightly on
                   1426: your system, but the effect is the same; when the text interpreter
                   1427: detects an error, it discards any remaining text on a line, resets
1.30      anton    1428: certain internal state and prints an error message. @xref{Error
                   1429: messages} for a detailed description of error messages.
1.23      crook    1430: 
1.29      crook    1431: The text interpreter waits for you to press carriage-return, and then
                   1432: processes your input line. Starting at the beginning of the line, it
                   1433: breaks the line into groups of characters separated by spaces. For each
                   1434: group of characters in turn, it makes two attempts to do something:
1.23      crook    1435: 
1.29      crook    1436: @itemize @bullet
                   1437: @item
                   1438: It tries to treat it as a command. It does this by searching a @dfn{name
                   1439: dictionary}. If the group of characters matches an entry in the name
                   1440: dictionary, the name dictionary provides the text interpreter with
                   1441: information that allows the text interpreter perform some actions. In
                   1442: Forth jargon, we say that the group
                   1443: @cindex word
                   1444: @cindex definition
                   1445: @cindex execution token
                   1446: @cindex xt
                   1447: of characters names a @dfn{word}, that the dictionary search returns an
                   1448: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   1449: word, and that the text interpreter executes the xt. Often, the terms
                   1450: @dfn{word} and @dfn{definition} are used interchangeably.
                   1451: @item
                   1452: If the text interpreter fails to find a match in the name dictionary, it
                   1453: tries to treat the group of characters as a number in the current number
                   1454: base (when you start up Forth, the current number base is base 10). If
                   1455: the group of characters legitimately represents a number, the text
                   1456: interpreter pushes the number onto a stack (we'll learn more about that
                   1457: in the next section).
                   1458: @end itemize
1.23      crook    1459: 
1.29      crook    1460: If the text interpreter is unable to do either of these things with any
                   1461: group of characters, it discards the group of characters and the rest of
                   1462: the line, then prints an error message. If the text interpreter reaches
                   1463: the end of the line without error, it prints the status message ``@code{ ok}''
                   1464: followed by carriage-return.
1.21      crook    1465: 
1.29      crook    1466: This is the simplest command we can give to the text interpreter:
1.23      crook    1467: 
                   1468: @example
1.30      anton    1469: @key{RET}  ok
1.23      crook    1470: @end example
1.21      crook    1471: 
1.29      crook    1472: The text interpreter did everything we asked it to do (nothing) without
                   1473: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   1474: command:
1.21      crook    1475: 
1.23      crook    1476: @example
1.30      anton    1477: @kbd{12 dup fred dup@key{RET}}
1.29      crook    1478: :1: Undefined word
                   1479: 12 dup fred dup
                   1480:        ^^^^
                   1481: $400D2BA8 Bounce
                   1482: $400DBDA8 no.extensions
1.23      crook    1483: @end example
1.21      crook    1484: 
1.29      crook    1485: When you press the carriage-return key, the text interpreter starts to
                   1486: work its way along the line:
1.21      crook    1487: 
1.29      crook    1488: @itemize @bullet
                   1489: @item
                   1490: When it gets to the space after the @code{2}, it takes the group of
                   1491: characters @code{12} and looks them up in the name
                   1492: dictionary@footnote{We can't tell if it found them or not, but assume
                   1493: for now that it did not}. There is no match for this group of characters
                   1494: in the name dictionary, so it tries to treat them as a number. It is
                   1495: able to do this successfully, so it puts the number, 12, ``on the stack''
                   1496: (whatever that means).
                   1497: @item
                   1498: The text interpreter resumes scanning the line and gets the next group
                   1499: of characters, @code{dup}. It looks it up in the name dictionary and
                   1500: (you'll have to take my word for this) finds it, and executes the word
                   1501: @code{dup} (whatever that means).
                   1502: @item
                   1503: Once again, the text interpreter resumes scanning the line and gets the
                   1504: group of characters @code{fred}. It looks them up in the name
                   1505: dictionary, but can't find them. It tries to treat them as a number, but
                   1506: they don't represent any legal number.
                   1507: @end itemize
1.21      crook    1508: 
1.29      crook    1509: At this point, the text interpreter gives up and prints an error
                   1510: message. The error message shows exactly how far the text interpreter
                   1511: got in processing the line. In particular, it shows that the text
                   1512: interpreter made no attempt to do anything with the final character
                   1513: group, @code{dup}, even though we have good reason to believe that the
                   1514: text interpreter would have no problem looking that word up and
                   1515: executing it a second time.
1.21      crook    1516: 
                   1517: 
1.29      crook    1518: @comment ----------------------------------------------
                   1519: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   1520: @section Stacks, postfix notation and parameter passing
                   1521: @cindex text interpreter
                   1522: @cindex outer interpreter
1.21      crook    1523: 
1.29      crook    1524: In procedural programming languages (like C and Pascal), the
                   1525: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   1526: functions or procedures are called with @dfn{explicit parameters}. For
                   1527: example, in C we might write:
1.21      crook    1528: 
1.23      crook    1529: @example
1.29      crook    1530: total = total + new_volume(length,height,depth);
1.23      crook    1531: @end example
1.21      crook    1532: 
1.23      crook    1533: @noindent
1.29      crook    1534: where new_volume is a function-call to another piece of code, and total,
                   1535: length, height and depth are all variables. length, height and depth are
                   1536: parameters to the function-call.
1.21      crook    1537: 
1.29      crook    1538: In Forth, the equivalent of the function or procedure is the
                   1539: @dfn{definition} and parameters are implicitly passed between
                   1540: definitions using a shared stack that is visible to the
                   1541: programmer. Although Forth does support variables, the existence of the
                   1542: stack means that they are used far less often than in most other
                   1543: programming languages. When the text interpreter encounters a number, it
                   1544: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    1545: actual number is implementation-dependent ...) and the particular stack
1.29      crook    1546: used for any operation is implied unambiguously by the operation being
                   1547: performed. The stack used for all integer operations is called the @dfn{data
                   1548: stack} and, since this is the stack used most commonly, references to
                   1549: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    1550: 
1.29      crook    1551: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    1552: 
1.23      crook    1553: @example
1.30      anton    1554: @kbd{1 2 3@key{RET}}  ok
1.23      crook    1555: @end example
1.21      crook    1556: 
1.29      crook    1557: Then this instructs the text interpreter to placed three numbers on the
                   1558: (data) stack. An analogy for the behaviour of the stack is to take a
                   1559: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   1560: the table. The 3 was the last card onto the pile (``last-in'') and if
                   1561: you take a card off the pile then, unless you're prepared to fiddle a
                   1562: bit, the card that you take off will be the 3 (``first-out''). The
                   1563: number that will be first-out of the stack is called the @dfn{top of
                   1564: stack}, which
                   1565: @cindex TOS definition
                   1566: is often abbreviated to @dfn{TOS}.
1.21      crook    1567: 
1.29      crook    1568: To understand how parameters are passed in Forth, consider the
                   1569: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   1570: be surprised to learn that this definition performs addition. More
                   1571: precisely, it adds two number together and produces a result. Where does
                   1572: it get the two numbers from? It takes the top two numbers off the
                   1573: stack. Where does it place the result? On the stack. You can act-out the
                   1574: behaviour of @code{+} with your playing cards like this:
1.21      crook    1575: 
                   1576: @itemize @bullet
                   1577: @item
1.29      crook    1578: Pick up two cards from the stack on the table
1.21      crook    1579: @item
1.29      crook    1580: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   1581: numbers''
1.21      crook    1582: @item
1.29      crook    1583: Decide that the answer is 5
1.21      crook    1584: @item
1.29      crook    1585: Shuffle the two cards back into the pack and find a 5
1.21      crook    1586: @item
1.29      crook    1587: Put a 5 on the remaining ace that's on the table.
1.21      crook    1588: @end itemize
                   1589: 
1.29      crook    1590: If you don't have a pack of cards handy but you do have Forth running,
                   1591: you can use the definition @code{.s} to show the current state of the stack,
                   1592: without affecting the stack. Type:
1.21      crook    1593: 
                   1594: @example
1.30      anton    1595: @kbd{clearstack 1 2 3@key{RET}} ok
                   1596: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    1597: @end example
                   1598: 
1.29      crook    1599: The text interpreter looks up the word @code{clearstack} and executes
                   1600: it; it tidies up the stack and removes any entries that may have been
                   1601: left on it by earlier examples. The text interpreter pushes each of the
                   1602: three numbers in turn onto the stack. Finally, the text interpreter
                   1603: looks up the word @code{.s} and executes it. The effect of executing
                   1604: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   1605: followed by a list of all the items on the stack; the item on the far
                   1606: right-hand side is the TOS.
1.21      crook    1607: 
1.29      crook    1608: You can now type:
1.21      crook    1609: 
1.29      crook    1610: @example
1.30      anton    1611: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    1612: @end example
1.21      crook    1613: 
1.29      crook    1614: @noindent
                   1615: which is correct; there are now 2 items on the stack and the result of
                   1616: the addition is 5.
1.23      crook    1617: 
1.29      crook    1618: If you're playing with cards, try doing a second addition: pick up the
                   1619: two cards, work out that their sum is 6, shuffle them into the pack,
                   1620: look for a 6 and place that on the table. You now have just one item on
                   1621: the stack. What happens if you try to do a third addition? Pick up the
                   1622: first card, pick up the second card -- ah! There is no second card. This
                   1623: is called a @dfn{stack underflow} and consitutes an error. If you try to
                   1624: do the same thing with Forth it will report an error (probably a Stack
                   1625: Underflow or an Invalid Memory Address error).
1.23      crook    1626: 
1.29      crook    1627: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   1628: which simply accepts that there is a finite amount of storage space
                   1629: reserved for the stack. To stretch the playing card analogy, if you had
                   1630: enough packs of cards and you piled the cards up on the table, you would
                   1631: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   1632: allows you to set the maximum size of the stacks. In general, the only
                   1633: time that you will get a stack overflow is because a definition has a
                   1634: bug in it and is generating data on the stack uncontrollably.
1.23      crook    1635: 
1.29      crook    1636: There's one final use for the playing card analogy. If you model your
                   1637: stack using a pack of playing cards, the maximum number of items on
                   1638: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   1639: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   1640: possible numbers are positive integer numbers 1 through 13; you can't
                   1641: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   1642: think about some of the cards, you can accommodate different
                   1643: numbers. For example, you could think of the Jack as representing 0,
                   1644: the Queen as representing -1 and the King as representing -2. Your
                   1645: *range* remains unchanged (you can still only represent a total of 13
                   1646: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    1647: 
1.29      crook    1648: In that analogy, the limit was the amount of information that a single
                   1649: stack entry could hold, and Forth has a similar limit. In Forth, the
                   1650: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   1651: implementation dependent and affects the maximum value that a stack
                   1652: entry can hold. A Standard Forth provides a cell size of at least
                   1653: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    1654: 
1.29      crook    1655: Forth does not do any type checking for you, so you are free to
                   1656: manipulate and combine stack items in any way you wish. A convenient way
                   1657: of treating stack items is as 2's complement signed integers, and that
                   1658: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    1659: 
1.29      crook    1660: @example
1.30      anton    1661: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    1662: @end example
1.21      crook    1663: 
1.29      crook    1664: If you use numbers and definitions like @code{+} in order to turn Forth
                   1665: into a great big pocket calculator, you will realise that it's rather
                   1666: different from a normal calculator. Rather than typing 2 + 3 = you had
                   1667: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   1668: result). The terminology used to describe this difference is to say that
                   1669: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   1670: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   1671: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    1672: 
1.29      crook    1673: Whilst postfix notation might look confusing to begin with, it has
                   1674: several important advantages:
1.21      crook    1675: 
1.23      crook    1676: @itemize @bullet
                   1677: @item
1.29      crook    1678: it is unambiguous
1.23      crook    1679: @item
1.29      crook    1680: it is more concise
1.23      crook    1681: @item
1.29      crook    1682: it fits naturally with a stack-based system
1.23      crook    1683: @end itemize
1.21      crook    1684: 
1.29      crook    1685: To examine these claims in more detail, consider these sums:
1.21      crook    1686: 
1.29      crook    1687: @example
                   1688: 6 + 5 * 4 =
                   1689: 4 * 5 + 6 =
                   1690: @end example
1.21      crook    1691: 
1.29      crook    1692: If you're just learning maths or your maths is very rusty, you will
                   1693: probably come up with the answer 44 for the first and 26 for the
                   1694: second. If you are a bit of a whizz at maths you will remember the
                   1695: @i{convention} that multiplication takes precendence over addition, and
                   1696: you'd come up with the answer 26 both times. To explain the answer 26
                   1697: to someone who got the answer 44, you'd probably rewrite the first sum
                   1698: like this:
1.21      crook    1699: 
1.29      crook    1700: @example
                   1701: 6 + (5 * 4) =
                   1702: @end example
1.21      crook    1703: 
1.29      crook    1704: If what you really wanted was to perform the addition before the
                   1705: multiplication, you would have to use parentheses to force it.
1.21      crook    1706: 
1.29      crook    1707: If you did the first two sums on a pocket calculator you would probably
                   1708: get the right answers, unless you were very cautious and entered them using
                   1709: these keystroke sequences:
1.21      crook    1710: 
1.29      crook    1711: 6 + 5 = * 4 =
                   1712: 4 * 5 = + 6 =
1.21      crook    1713: 
1.29      crook    1714: Postfix notation is unambiguous because the order that the operators
                   1715: are applied is always explicit; that also means that parentheses are
                   1716: never required. The operators are @i{active} (the act of quoting the
                   1717: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    1718: 
1.29      crook    1719: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   1720: equivalent ways:
1.26      crook    1721: 
                   1722: @example
1.29      crook    1723: 6 5 4 * +      or:
                   1724: 5 4 * 6 +
1.26      crook    1725: @end example
1.23      crook    1726: 
1.29      crook    1727: An important thing that you should notice about this notation is that
                   1728: the @i{order} of the numbers does not change; if you want to subtract
                   1729: 2 from 10 you type @code{10 2 -}.
1.1       anton    1730: 
1.29      crook    1731: The reason that Forth uses postfix notation is very simple to explain: it
                   1732: makes the implementation extremely simple, and it follows naturally from
                   1733: using the stack as a mechanism for passing parameters. Another way of
                   1734: thinking about this is to realise that all Forth definitions are
                   1735: @i{active}; they execute as they are encountered by the text
                   1736: interpreter. The result of this is that the syntax of Forth is trivially
                   1737: simple.
1.1       anton    1738: 
                   1739: 
                   1740: 
1.29      crook    1741: @comment ----------------------------------------------
                   1742: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   1743: @section Your first Forth definition
                   1744: @cindex first definition
1.1       anton    1745: 
1.29      crook    1746: Until now, the examples we've seen have been trivial; we've just been
                   1747: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   1748: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   1749: again@footnote{That's not quite true. If you press the up-arrow key on
                   1750: your keyboard you should be able to scroll back to any earlier command,
                   1751: edit it and re-enter it.} In this section we'll see how to add new
                   1752: words to Forth's vocabulary.
1.1       anton    1753: 
1.29      crook    1754: The easiest way to create a new word is to use a @dfn{colon
                   1755: definition}. We'll define a few and try them out before worrying too
                   1756: much about how they work. Try typing in these examples; be careful to
                   1757: copy the spaces accurately:
1.1       anton    1758: 
1.29      crook    1759: @example
                   1760: : add-two 2 + . ;
                   1761: : greet ." Hello and welcome" ;
                   1762: : demo 5 add-two ;
                   1763: @end example
1.1       anton    1764: 
1.29      crook    1765: @noindent
                   1766: Now try them out:
1.1       anton    1767: 
1.29      crook    1768: @example
1.30      anton    1769: @kbd{greet@key{RET}} Hello and welcome  ok
                   1770: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   1771: @kbd{4 add-two@key{RET}} 6  ok
                   1772: @kbd{demo@key{RET}} 7  ok
                   1773: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    1774: @end example
1.1       anton    1775: 
1.29      crook    1776: The first new thing that we've introduced here is the pair of words
                   1777: @code{:} and @code{;}. These are used to start and terminate a new
                   1778: definition, respectively. The first word after the @code{:} is the name
                   1779: for the new definition.
1.1       anton    1780: 
1.29      crook    1781: As you can see from the examples, a definition is built up of words that
                   1782: have already been defined; Forth makes no distinction between
                   1783: definitions that existed when you started the system up, and those that
                   1784: you define yourself.
1.1       anton    1785: 
1.29      crook    1786: The examples also introduce the words @code{.} (dot), @code{."}
                   1787: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   1788: the stack and displays it. It's like @code{.s} except that it only
                   1789: displays the top item of the stack and it is destructive; after it has
                   1790: executed, the number is no longer on the stack. There is always one
                   1791: space printed after the number, and no spaces before it. Dot-quote
                   1792: defines a string (a sequence of characters) that will be printed when
                   1793: the word is executed. The string can contain any printable characters
                   1794: except @code{"}. A @code{"} has a special function; it is not a Forth
                   1795: word but it acts as a delimiter (the way that delimiters work is
                   1796: described in the next section). Finally, @code{dup} duplicates the value
                   1797: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    1798: 
1.29      crook    1799: We already know that the text interpreter searches through the
                   1800: dictionary to locate names. If you've followed the examples earlier, you
                   1801: will already have a definition called @code{add-two}. Lets try modifying
                   1802: it by typing in a new definition:
1.1       anton    1803: 
1.29      crook    1804: @example
1.30      anton    1805: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    1806: @end example
1.5       anton    1807: 
1.29      crook    1808: Forth recognised that we were defining a word that already exists, and
                   1809: printed a message to warn us of that fact. Let's try out the new
                   1810: definition:
1.5       anton    1811: 
1.29      crook    1812: @example
1.30      anton    1813: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    1814: @end example
1.1       anton    1815: 
1.29      crook    1816: @noindent
                   1817: All that we've actually done here, though, is to create a new
                   1818: definition, with a particular name. The fact that there was already a
                   1819: definition with the same name did not make any difference to the way
                   1820: that the new definition was created (except that Forth printed a warning
                   1821: message). The old definition of add-two still exists (try @code{demo}
                   1822: again to see that this is true). Any new definition will use the new
                   1823: definition of @code{add-two}, but old definitions continue to use the
                   1824: version that already existed at the time that they were @code{compiled}.
1.1       anton    1825: 
1.29      crook    1826: Before you go on to the next section, try defining and redefining some
                   1827: words of your own.
1.1       anton    1828: 
1.29      crook    1829: @comment ----------------------------------------------
                   1830: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   1831: @section How does that work?
                   1832: @cindex parsing words
1.1       anton    1833: 
1.30      anton    1834: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   1835: 
                   1836: @c Is it a good idea to talk about the interpretation semantics of a
                   1837: @c number? We don't have an xt to go along with it. - anton
                   1838: 
                   1839: @c Now that I have eliminated execution semantics, I wonder if it would not
                   1840: @c be better to keep them (or add run-time semantics), to make it easier to
                   1841: @c explain what compilation semantics usually does. - anton
                   1842: 
1.29      crook    1843: Now we're going to take another look at the definition of @code{add-two}
                   1844: from the previous section. From our knowledge of the way that the text
                   1845: interpreter works, we would have expected this result when we tried to
                   1846: define @code{add-two}:
1.21      crook    1847: 
1.29      crook    1848: @example
1.30      anton    1849: @kbd{: add-two 2 + . " ;@key{RET}}
1.29      crook    1850:   ^^^^^^^
                   1851: Error: Undefined word
                   1852: @end example
1.28      crook    1853: 
1.29      crook    1854: The reason that this didn't happen is bound up in the way that @code{:}
                   1855: works. The word @code{:} does two special things. The first special
                   1856: thing that it does prevents the text interpreter from ever seeing the
                   1857: characters @code{add-two}. The text interpreter uses a variable called
                   1858: @cindex modifying >IN
                   1859: @code{>IN} (pronounced ''to-in'') to keep track of where it is in the
                   1860: input line. When it encounters the word @code{:} it behaves in exactly
                   1861: the same way as it does for any other word; it looks it up in the name
                   1862: dictionary, finds its xt and executes it. When @code{:} executes, it
                   1863: looks at the input buffer, finds the word @code{add-two} and advances the
                   1864: value of @code{>IN} to point past it. It then does some other stuff
                   1865: associated with creating the new definition (including creating an entry
                   1866: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   1867: completes, control returns to the text interpreter, which is oblivious
                   1868: to the fact that it has been tricked into ignoring part of the input
                   1869: line.
1.21      crook    1870: 
1.29      crook    1871: @cindex parsing words
                   1872: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   1873: prevent the text interpreter from acting on the whole of the input line
                   1874: -- are called @dfn{parsing words}.
1.21      crook    1875: 
1.29      crook    1876: @cindex @code{state} - effect on the text interpreter
                   1877: @cindex text interpreter - effect of state
                   1878: The second special thing that @code{:} does is change the value of a
                   1879: variable called @code{state}, which affects the way that the text
                   1880: interpreter behaves. When Gforth starts up, @code{state} has the value
                   1881: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   1882: colon definition (started with @code{:}), @code{state} is set to -1 and
                   1883: the text interpreter is said to be @dfn{compiling}. The word @code{;}
                   1884: ends the definition -- one of the things that it does is to change the
                   1885: value of @code{state} back to 0.
1.21      crook    1886: 
1.29      crook    1887: We have already seen how the text interpreter behaves when it is
                   1888: interpreting; it looks for each character sequence in the dictionary,
                   1889: finds its xt and executes it, or it converts it to a number and pushes
                   1890: it onto the stack, or it fails to do either and generates an error.
1.21      crook    1891: 
1.29      crook    1892: When the text interpreter is compiling, its behaviour is slightly
                   1893: different; it still looks for each character sequence in the dictionary
1.30      anton    1894: and finds it, or converts it to a number, or fails to do either and
                   1895: generates an error.  But instead of the execution token of a word it
                   1896: finds and executes the compilation token.  For most words executing the
                   1897: compilation token results in laying down (@dfn{compiling}) the execution
                   1898: token, i.e., some magic to make that xt or number get executed or pushed
                   1899: at a later time; at the time that @code{add-two} is
                   1900: @dfn{executed}. Therefore, when you execute @code{add-two} its
                   1901: @dfn{run-time effect} is exactly the same as if you had typed @code{2 +
                   1902: .} outside of a definition, and pressed carriage-return.
1.28      crook    1903: 
1.30      anton    1904: In Forth, every word or number can be described in terms of two
1.29      crook    1905: properties:
1.28      crook    1906: 
                   1907: @itemize @bullet
                   1908: @item
1.30      anton    1909: Its @dfn{interpretation semantics}, represented by the execution token.
1.28      crook    1910: @item
1.30      anton    1911: Its @dfn{compilation semantics}, represented by the compilation token.
1.29      crook    1912: @end itemize
                   1913: 
1.30      anton    1914: The value of @code{state} determines whether the text interpreter will
                   1915: use the compilation or interpretation semantics of a word or number that
                   1916: it encounters.
1.29      crook    1917: 
                   1918: @itemize @bullet
1.28      crook    1919: @item
1.29      crook    1920: @cindex interpretation semantics
                   1921: When the text interpreter encounters a word or number in @dfn{interpret}
                   1922: state, it performs the @dfn{interpretation semantics} of the word or
                   1923: number.
1.28      crook    1924: @item
1.29      crook    1925: @cindex compilation semantics
                   1926: When the text interpreter encounters a word or number in @dfn{compile}
                   1927: state, it performs the @dfn{compilation semantics} of the word or
                   1928: number.
                   1929: @end itemize
                   1930: 
                   1931: @noindent
                   1932: Numbers are always treated in a fixed way:
                   1933: 
                   1934: @itemize @bullet
1.28      crook    1935: @item
1.30      anton    1936: When the number is @dfn{interpreted}, its behaviour is to push the number onto the stack.
1.28      crook    1937: @item
1.30      anton    1938: When the number is @dfn{compiled}, a piece of code is appended to the
                   1939: current definition that pushes the number when it runs. (In other words,
                   1940: the compilation semantics of a number are to postpone its interpretation
                   1941: semantics until the run-time of the definition that it is being compiled
                   1942: into.)
1.29      crook    1943: @end itemize
                   1944: 
                   1945: The behaviour of a word is not so regular, but most have @i{default
1.30      anton    1946: compilation semantics} which means that they behave like this:
1.29      crook    1947: 
                   1948: @itemize @bullet
1.28      crook    1949: @item
1.30      anton    1950: The @dfn{interpretation semantics} of the word are to do something useful.
                   1951: @item
1.29      crook    1952: The @dfn{compilation semantics} of the word are to append its
1.30      anton    1953: @dfn{interpretation semantics} to the current definition (so that its
                   1954: run-time behaviour is to do something useful).
1.28      crook    1955: @end itemize
                   1956: 
1.30      anton    1957: @cindex immediate words
1.29      crook    1958: The actual behaviour of any particular word depends upon the way in
                   1959: which it was defined. When the text interpreter finds the word in the
                   1960: name dictionary, it not only retrieves the xt for the word, it also
                   1961: retrieves some flags: the @dfn{compile-only} flag and the @dfn{immediate
                   1962: flag}. The compile-only flag indicates that the word has no
1.30      anton    1963: interpretation semantics (the run-time behaviour for the default
                   1964: compilation semantics is not affected by this flag, however); any
                   1965: attempt to interpret a word that has the compile-only flag set will
                   1966: generate an error (for example, @code{IF} has no interpretation
                   1967: semantics). The immediate flag changes the compilation semantics of the
                   1968: word; if it is set, the compilation semantics are equal to the
                   1969: interpretation semantics (again ignoring the compile-only flag).  it. In
                   1970: other words, these so-called @dfn{immediate} words behave like this:
1.29      crook    1971: 
                   1972: @itemize @bullet
                   1973: @item
1.30      anton    1974: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    1975: @item
1.30      anton    1976: The @dfn{compilation semantics} of the word are to do something useful
                   1977: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    1978: @end itemize
1.28      crook    1979: 
1.29      crook    1980: This example shows the difference between an immediate and a
                   1981: non-immediate word:
1.28      crook    1982: 
1.29      crook    1983: @example
                   1984: : show-state state @@ . ;
                   1985: : show-state-now show-state ; immediate
                   1986: : word1 show-state ;
                   1987: : word2 show-state-now ;
1.28      crook    1988: @end example
1.23      crook    1989: 
1.29      crook    1990: The word @code{immediate} after the definition of @code{show-state-now}
                   1991: makes that word an immediate word. These definitions introduce a new
                   1992: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   1993: variable, and leaves it on the stack. Therefore, the behaviour of
                   1994: @code{show-state} is to print a number that represents the current value
                   1995: of @code{state}.
1.28      crook    1996: 
1.29      crook    1997: When you execute @code{word1}, it prints the number 0, indicating that
                   1998: the system is interpreting. When the text interpreter compiled the
                   1999: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    2000: compilation semantics are to append its interpretation semantics to the
1.29      crook    2001: current definition. When you execute @code{word1}, it performs the
1.30      anton    2002: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    2003: (and therefore @code{show-state}) are executed, the system is
                   2004: interpreting.
1.28      crook    2005: 
1.30      anton    2006: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    2007: you should have seen the number -1 printed, followed by ``@code{
                   2008: ok}''. When the text interpreter compiled the definition of
                   2009: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    2010: whose compilation semantics are therefore to perform its interpretation
1.29      crook    2011: semantics. It is executed straight away (even before the text
                   2012: interpreter has moved on to process another group of characters; the
                   2013: @code{;} in this example). The effect of executing it are to display the
                   2014: value of @code{state} @i{at the time that the definition of}
                   2015: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   2016: system is compiling at this time. If you execute @code{word2} it does
                   2017: nothing at all.
1.28      crook    2018: 
1.29      crook    2019: @cindex @code{."}, how it works
                   2020: Before leaving the subject of immediate words, consider the behaviour of
                   2021: @code{."} in the definition of @code{greet}, in the previous
                   2022: section. This word is both a parsing word and an immediate word. Notice
                   2023: that there is a space between @code{."} and the start of the text
                   2024: @code{Hello and welcome}, but that there is no space between the last
                   2025: letter of @code{welcome} and the @code{"} character. The reason for this
                   2026: is that @code{."} is a Forth word; it must have a space after it so that
                   2027: the text interpreter can identify it. The @code{"} is not a Forth word;
                   2028: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   2029: is displayed, there is neither a space before the @code{H} nor after the
                   2030: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   2031: that @code{greet} is defined. When it executes, its behaviour is to
                   2032: search forward in the input line looking for the delimiter. When it
                   2033: finds the delimiter, it updates @code{>IN} to point past the
                   2034: delimiter. It also compiles some magic code into the definition of
                   2035: @code{greet}; the xt of a run-time routine that prints a text string. It
                   2036: compiles the string @code{Hello and welcome} into memory so that it is
                   2037: available to be printed later. When the text interpreter gains control,
                   2038: the next word it finds in the input stream is @code{;} and so it
                   2039: terminates the definition of @code{greet}.
1.28      crook    2040: 
                   2041: 
                   2042: @comment ----------------------------------------------
1.29      crook    2043: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   2044: @section Forth is written in Forth
                   2045: @cindex structure of Forth programs
                   2046: 
                   2047: When you start up a Forth compiler, a large number of definitions
                   2048: already exist. In Forth, you develop a new application using bottom-up
                   2049: programming techniques to create new definitions that are defined in
                   2050: terms of existing definitions. As you create each definition you can
                   2051: test and debug it interactively.
                   2052: 
                   2053: If you have tried out the examples in this section, you will probably
                   2054: have typed them in by hand; when you leave Gforth, your definitions will
                   2055: be lost. You can avoid this by using a text editor to enter Forth source
                   2056: code into a file, and then loading code from the file using
                   2057: @code{include} (@xref{Forth source files}). A Forth source file is
                   2058: processed by the text interpreter, just as though you had typed it in by
                   2059: hand@footnote{Actually, there are some subtle differences -- see
                   2060: @ref{The Text Interpreter}.}.
                   2061: 
                   2062: Gforth also supports the traditional Forth alternative to using text
                   2063: files for program entry (@xref{Blocks}).
1.28      crook    2064: 
1.29      crook    2065: In common with many, if not most, Forth compilers, most of Gforth is
                   2066: actually written in Forth. All of the @file{.fs} files in the
                   2067: installation directory@footnote{For example,
1.30      anton    2068: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    2069: study to see examples of Forth programming.
1.28      crook    2070: 
1.29      crook    2071: Gforth maintains a history file that records every line that you type to
                   2072: the text interpreter. This file is preserved between sessions, and is
                   2073: used to provide a command-line recall facility. If you enter long
                   2074: definitions by hand, you can use a text editor to paste them out of the
                   2075: history file into a Forth source file for reuse at a later time
                   2076: (@pxref{Command-line editing} for more information).
1.28      crook    2077: 
                   2078: 
                   2079: @comment ----------------------------------------------
1.29      crook    2080: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   2081: @section Review - elements of a Forth system
                   2082: @cindex elements of a Forth system
1.28      crook    2083: 
1.29      crook    2084: To summarise this chapter:
1.28      crook    2085: 
                   2086: @itemize @bullet
                   2087: @item
1.29      crook    2088: Forth programs use @dfn{factoring} to break a problem down into small
                   2089: fragments called @dfn{words} or @dfn{definitions}.
                   2090: @item
                   2091: Forth program development is an interactive process.
                   2092: @item
                   2093: The main command loop that accepts input, and controls both
                   2094: interpretation and compilation, is called the @dfn{text interpreter}
                   2095: (also known as the @dfn{outer interpreter}).
                   2096: @item
                   2097: Forth has a very simple syntax, consisting of words and numbers
                   2098: separated by spaces or carriage-return characters. Any additional syntax
                   2099: is imposed by @dfn{parsing words}.
                   2100: @item
                   2101: Forth uses a stack to pass parameters between words. As a result, it
                   2102: uses postfix notation.
                   2103: @item
                   2104: To use a word that has previously been defined, the text interpreter
                   2105: searches for the word in the @dfn{name dictionary}.
                   2106: @item
1.30      anton    2107: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    2108: @item
1.29      crook    2109: The text interpreter uses the value of @code{state} to select between
                   2110: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   2111: semantics} of a word that it encounters.
1.28      crook    2112: @item
1.30      anton    2113: The relationship between the @dfn{interpretation semantics} and
                   2114: @dfn{compilation semantics} for a word
1.29      crook    2115: depend upon the way in which the word was defined (for example, whether
                   2116: it is an @dfn{immediate} word).
1.28      crook    2117: @item
1.29      crook    2118: Forth definitions can be implemented in Forth (called @dfn{high-level
                   2119: definitions}) or in some other way (usually a lower-level language and
                   2120: as a result often called @dfn{low-level definitions}, @dfn{code
                   2121: definitions} or @dfn{primitives}).
1.28      crook    2122: @item
1.29      crook    2123: Many Forth systems are implemented mainly in Forth.
1.28      crook    2124: @end itemize
                   2125: 
                   2126: 
1.29      crook    2127: @comment ----------------------------------------------
                   2128: @node Where to go next,Exercises,Review - elements of a Forth system, Introduction
                   2129: @section Where To Go Next
                   2130: @cindex where to go next
1.28      crook    2131: 
1.29      crook    2132: Amazing as it may seem, if you have read (and understood) this far, you
                   2133: know almost all the fundamentals about the inner workings of a Forth
                   2134: system. You certainly know enough to be able to read and understand the
                   2135: rest of this manual and the ANS Forth document, to learn more about the
                   2136: facilities that Forth in general and Gforth in particular provide. Even
                   2137: scarier, you know almost enough to implement your own Forth system.
1.30      anton    2138: However, that's not a good idea just yet... better to try writing some
1.29      crook    2139: programs in Gforth.
1.28      crook    2140: 
1.29      crook    2141: Forth has such a rich vocabulary that it can be hard to know where to
                   2142: start in learning it. This section suggests a few sets of words that are
                   2143: enough to write small but useful programs. Use the word index in this
                   2144: document to learn more about each word, then try it out and try to write
                   2145: small definitions using it. Start by experimenting with these words:
1.28      crook    2146: 
                   2147: @itemize @bullet
                   2148: @item
1.29      crook    2149: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   2150: @item
                   2151: Comparison: @code{MIN MAX =}
                   2152: @item
                   2153: Logic: @code{AND OR XOR NOT}
                   2154: @item
                   2155: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    2156: @item
1.29      crook    2157: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    2158: @item
1.29      crook    2159: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    2160: @item
1.29      crook    2161: Defining words: @code{: ; CREATE}
1.28      crook    2162: @item
1.29      crook    2163: Memory allocation words: @code{ALLOT ,}
1.28      crook    2164: @item
1.29      crook    2165: Tools: @code{SEE WORDS .S MARKER}
                   2166: @end itemize
                   2167: 
                   2168: When you have mastered those, go on to:
                   2169: 
                   2170: @itemize @bullet
1.28      crook    2171: @item
1.29      crook    2172: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    2173: @item
1.29      crook    2174: Memory access: @code{@@ !}
1.28      crook    2175: @end itemize
1.23      crook    2176: 
1.29      crook    2177: When you have mastered these, there's nothing for it but to read through
                   2178: the whole of this manual and find out what you've missed.
                   2179: 
                   2180: @comment ----------------------------------------------
                   2181: @node Exercises, ,Where to go next, Introduction
                   2182: @section Exercises
                   2183: @cindex exercises
                   2184: 
                   2185: TODO: provide a set of programming excercises linked into the stuff done
                   2186: already and into other sections of the manual. Provide solutions to all
                   2187: the exercises in a .fs file in the distribution.
                   2188: 
                   2189: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   2190: 
                   2191: @c excercises:
                   2192: @c 1. take inches and convert to feet and inches.
                   2193: @c 2. take temperature and convert from fahrenheight to celcius;
                   2194: @c    may need to care about symmetric vs floored??
                   2195: @c 3. take input line and do character substitution
                   2196: @c    to encipher or decipher
                   2197: @c 4. as above but work on a file for in and out
                   2198: @c 5. take input line and convert to pig-latin 
                   2199: @c
                   2200: @c thing of sets of things to exercise then come up with
                   2201: @c problems that need those things.
                   2202: 
                   2203: 
1.26      crook    2204: @c ******************************************************************
1.29      crook    2205: @node Words, Error messages, Introduction, Top
1.1       anton    2206: @chapter Forth Words
1.26      crook    2207: @cindex words
1.1       anton    2208: 
                   2209: @menu
                   2210: * Notation::                    
1.21      crook    2211: * Comments::
                   2212: * Boolean Flags::
1.1       anton    2213: * Arithmetic::                  
                   2214: * Stack Manipulation::          
1.5       anton    2215: * Memory::                      
1.1       anton    2216: * Control Structures::          
                   2217: * Defining Words::              
1.21      crook    2218: * The Text Interpreter::
1.12      anton    2219: * Tokens for Words::            
1.21      crook    2220: * Word Lists::                   
                   2221: * Environmental Queries::
1.12      anton    2222: * Files::                       
                   2223: * Blocks::                      
                   2224: * Other I/O::                   
                   2225: * Programming Tools::           
                   2226: * Assembler and Code Words::    
                   2227: * Threading Words::             
1.26      crook    2228: * Locals::                      
                   2229: * Structures::                  
                   2230: * Object-oriented Forth::       
1.21      crook    2231: * Passing Commands to the OS::
                   2232: * Miscellaneous Words::
1.1       anton    2233: @end menu
                   2234: 
1.21      crook    2235: @node Notation, Comments, Words, Words
1.1       anton    2236: @section Notation
                   2237: @cindex notation of glossary entries
                   2238: @cindex format of glossary entries
                   2239: @cindex glossary notation format
                   2240: @cindex word glossary entry format
                   2241: 
                   2242: The Forth words are described in this section in the glossary notation
                   2243: that has become a de-facto standard for Forth texts, i.e.,
                   2244: 
                   2245: @format
1.29      crook    2246: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    2247: @end format
1.29      crook    2248: @i{Description}
1.1       anton    2249: 
                   2250: @table @var
                   2251: @item word
1.28      crook    2252: The name of the word.
1.1       anton    2253: 
                   2254: @item Stack effect
                   2255: @cindex stack effect
1.29      crook    2256: The stack effect is written in the notation @code{@i{before} --
                   2257: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    2258: stack entries before and after the execution of the word. The rest of
                   2259: the stack is not touched by the word. The top of stack is rightmost,
                   2260: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   2261: uses a separate floating point stack, but a unified stack
1.29      crook    2262: notation. Also, return stack effects are not shown in @i{stack
                   2263: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    2264: the type and/or the function of the item. See below for a discussion of
                   2265: the types.
                   2266: 
                   2267: All words have two stack effects: A compile-time stack effect and a
                   2268: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    2269: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    2270: this standard behaviour, or the word does other unusual things at
                   2271: compile time, both stack effects are shown; otherwise only the run-time
                   2272: stack effect is shown.
                   2273: 
                   2274: @cindex pronounciation of words
                   2275: @item pronunciation
                   2276: How the word is pronounced.
                   2277: 
                   2278: @cindex wordset
                   2279: @item wordset
1.21      crook    2280: The ANS Forth standard is divided into several word sets. A standard
                   2281: system need not support all of them. Therefore, in theory, the fewer
                   2282: word sets your program uses the more portable it will be. However, we
                   2283: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    2284: all word sets. Words that are not defined in ANS Forth have
1.21      crook    2285: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    2286: describes words that will work in future releases of Gforth;
                   2287: @code{gforth-internal} words are more volatile. Environmental query
                   2288: strings are also displayed like words; you can recognize them by the
1.21      crook    2289: @code{environment} in the word set field.
1.1       anton    2290: 
                   2291: @item Description
                   2292: A description of the behaviour of the word.
                   2293: @end table
                   2294: 
                   2295: @cindex types of stack items
                   2296: @cindex stack item types
                   2297: The type of a stack item is specified by the character(s) the name
                   2298: starts with:
                   2299: 
                   2300: @table @code
                   2301: @item f
                   2302: @cindex @code{f}, stack item type
                   2303: Boolean flags, i.e. @code{false} or @code{true}.
                   2304: @item c
                   2305: @cindex @code{c}, stack item type
                   2306: Char
                   2307: @item w
                   2308: @cindex @code{w}, stack item type
                   2309: Cell, can contain an integer or an address
                   2310: @item n
                   2311: @cindex @code{n}, stack item type
                   2312: signed integer
                   2313: @item u
                   2314: @cindex @code{u}, stack item type
                   2315: unsigned integer
                   2316: @item d
                   2317: @cindex @code{d}, stack item type
                   2318: double sized signed integer
                   2319: @item ud
                   2320: @cindex @code{ud}, stack item type
                   2321: double sized unsigned integer
                   2322: @item r
                   2323: @cindex @code{r}, stack item type
                   2324: Float (on the FP stack)
1.21      crook    2325: @item a-
1.1       anton    2326: @cindex @code{a_}, stack item type
                   2327: Cell-aligned address
1.21      crook    2328: @item c-
1.1       anton    2329: @cindex @code{c_}, stack item type
                   2330: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    2331: @item f-
1.1       anton    2332: @cindex @code{f_}, stack item type
                   2333: Float-aligned address
1.21      crook    2334: @item df-
1.1       anton    2335: @cindex @code{df_}, stack item type
                   2336: Address aligned for IEEE double precision float
1.21      crook    2337: @item sf-
1.1       anton    2338: @cindex @code{sf_}, stack item type
                   2339: Address aligned for IEEE single precision float
                   2340: @item xt
                   2341: @cindex @code{xt}, stack item type
                   2342: Execution token, same size as Cell
                   2343: @item wid
                   2344: @cindex @code{wid}, stack item type
1.21      crook    2345: Word list ID, same size as Cell
1.1       anton    2346: @item f83name
                   2347: @cindex @code{f83name}, stack item type
                   2348: Pointer to a name structure
                   2349: @item "
                   2350: @cindex @code{"}, stack item type
1.12      anton    2351: string in the input stream (not on the stack). The terminating character
                   2352: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    2353: quotes.
                   2354: @end table
                   2355: 
1.21      crook    2356: @node Comments, Boolean Flags, Notation, Words
                   2357: @section Comments
1.26      crook    2358: @cindex comments
1.21      crook    2359: 
1.29      crook    2360: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   2361: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    2362: 
1.23      crook    2363: doc-(
1.21      crook    2364: doc-\
1.23      crook    2365: doc-\G
1.21      crook    2366: 
                   2367: @node Boolean Flags, Arithmetic, Comments, Words
                   2368: @section Boolean Flags
1.26      crook    2369: @cindex Boolean flags
1.21      crook    2370: 
                   2371: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   2372: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    2373: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    2374: a cell that has @i{any} bit set as @code{true}.
1.21      crook    2375: 
                   2376: doc-true
                   2377: doc-false
1.29      crook    2378: doc-on
                   2379: doc-off
1.21      crook    2380: 
                   2381: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    2382: @section Arithmetic
                   2383: @cindex arithmetic words
                   2384: 
                   2385: @cindex division with potentially negative operands
                   2386: Forth arithmetic is not checked, i.e., you will not hear about integer
                   2387: overflow on addition or multiplication, you may hear about division by
                   2388: zero if you are lucky. The operator is written after the operands, but
                   2389: the operands are still in the original order. I.e., the infix @code{2-1}
                   2390: corresponds to @code{2 1 -}. Forth offers a variety of division
                   2391: operators. If you perform division with potentially negative operands,
                   2392: you do not want to use @code{/} or @code{/mod} with its undefined
                   2393: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   2394: former, @pxref{Mixed precision}).
1.26      crook    2395: @comment TODO discuss the different division forms and the std approach
1.1       anton    2396: 
                   2397: @menu
                   2398: * Single precision::            
                   2399: * Bitwise operations::          
1.21      crook    2400: * Double precision::            Double-cell integer arithmetic
                   2401: * Numeric comparison::
1.29      crook    2402: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    2403: * Floating Point::              
                   2404: @end menu
                   2405: 
                   2406: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
                   2407: @subsection Single precision
                   2408: @cindex single precision arithmetic words
                   2409: 
1.21      crook    2410: By default, numbers in Forth are single-precision integers that are 1
1.26      crook    2411: cell in size. They can be signed or unsigned, depending upon how you
1.21      crook    2412: treat them. @xref{Number Conversion} for the rules used by the text
                   2413: interpreter for recognising single-precision integers.
                   2414: 
1.1       anton    2415: doc-+
1.21      crook    2416: doc-1+
1.1       anton    2417: doc--
1.21      crook    2418: doc-1-
1.1       anton    2419: doc-*
                   2420: doc-/
                   2421: doc-mod
                   2422: doc-/mod
                   2423: doc-negate
                   2424: doc-abs
                   2425: doc-min
                   2426: doc-max
1.21      crook    2427: doc-d>s
1.27      crook    2428: doc-floored
1.1       anton    2429: 
1.21      crook    2430: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1       anton    2431: @subsection Bitwise operations
                   2432: @cindex bitwise operation words
                   2433: 
                   2434: doc-and
                   2435: doc-or
                   2436: doc-xor
                   2437: doc-invert
1.21      crook    2438: doc-lshift
                   2439: doc-rshift
1.1       anton    2440: doc-2*
1.21      crook    2441: doc-d2*
1.1       anton    2442: doc-2/
1.21      crook    2443: doc-d2/
                   2444: 
                   2445: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
                   2446: @subsection Double precision
                   2447: @cindex double precision arithmetic words
                   2448: 
                   2449: @xref{Number Conversion} for the rules used by the text interpreter for
                   2450: recognising double-precision integers.
                   2451: 
                   2452: A double precision number is represented by a cell pair, with the most
1.31      anton    2453: significant cell at the TOS. It is trivial to convert an unsigned
1.26      crook    2454: single to an (unsigned) double; simply push a @code{0} onto the
                   2455: TOS. Since numbers are represented by Gforth using 2's complement
                   2456: arithmetic, converting a signed single to a (signed) double requires
1.31      anton    2457: sign-extension across the most significant cell. This can be achieved
1.26      crook    2458: using @code{s>d}. The moral of the story is that you cannot convert a
                   2459: number without knowing whether it represents an unsigned or a
                   2460: signed number.
1.21      crook    2461: 
                   2462: doc-s>d
                   2463: doc-d+
                   2464: doc-d-
                   2465: doc-dnegate
                   2466: doc-dabs
                   2467: doc-dmin
                   2468: doc-dmax
                   2469: 
                   2470: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
                   2471: @subsection Numeric comparison
                   2472: @cindex numeric comparison words
                   2473: 
1.28      crook    2474: doc-<
                   2475: doc-<=
                   2476: doc-<>
                   2477: doc-=
                   2478: doc->
                   2479: doc->=
                   2480: 
1.21      crook    2481: doc-0<
1.23      crook    2482: doc-0<=
1.21      crook    2483: doc-0<>
                   2484: doc-0=
1.23      crook    2485: doc-0>
                   2486: doc-0>=
1.28      crook    2487: 
                   2488: doc-u<
                   2489: doc-u<=
1.31      anton    2490: @c TODO why u<> and u= ... they are the same as <> and =
                   2491: @c commented them out because they are unnecessary
                   2492: @c doc-u<>
                   2493: @c doc-u=
1.28      crook    2494: doc-u>
                   2495: doc-u>=
                   2496: 
                   2497: doc-within
                   2498: 
                   2499: doc-d<
                   2500: doc-d<=
                   2501: doc-d<>
                   2502: doc-d=
                   2503: doc-d>
                   2504: doc-d>=
1.23      crook    2505: 
1.21      crook    2506: doc-d0<
1.23      crook    2507: doc-d0<=
                   2508: doc-d0<>
1.21      crook    2509: doc-d0=
1.23      crook    2510: doc-d0>
                   2511: doc-d0>=
                   2512: 
1.21      crook    2513: doc-du<
1.28      crook    2514: doc-du<=
1.31      anton    2515: @c doc-du<>
                   2516: @c doc-du=
1.28      crook    2517: doc-du>
                   2518: doc-du>=
1.1       anton    2519: 
1.21      crook    2520: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    2521: @subsection Mixed precision
                   2522: @cindex mixed precision arithmetic words
                   2523: 
                   2524: doc-m+
                   2525: doc-*/
                   2526: doc-*/mod
                   2527: doc-m*
                   2528: doc-um*
                   2529: doc-m*/
                   2530: doc-um/mod
                   2531: doc-fm/mod
                   2532: doc-sm/rem
                   2533: 
1.21      crook    2534: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    2535: @subsection Floating Point
                   2536: @cindex floating point arithmetic words
                   2537: 
1.21      crook    2538: @xref{Number Conversion} for the rules used by the text interpreter for
                   2539: recognising floating-point numbers.
1.1       anton    2540: 
1.32      anton    2541: Gforth has a separate floating point
1.26      crook    2542: stack, but the documentation uses the unified notation.
1.1       anton    2543: 
                   2544: @cindex floating-point arithmetic, pitfalls
                   2545: Floating point numbers have a number of unpleasant surprises for the
                   2546: unwary (e.g., floating point addition is not associative) and even a few
                   2547: for the wary. You should not use them unless you know what you are doing
                   2548: or you don't care that the results you get are totally bogus. If you
                   2549: want to learn about the problems of floating point numbers (and how to
                   2550: avoid them), you might start with @cite{David Goldberg, What Every
                   2551: Computer Scientist Should Know About Floating-Point Arithmetic, ACM
1.17      anton    2552: Computing Surveys 23(1):5@minus{}48, March 1991}
                   2553: (@url{http://www.validgh.com/goldberg/paper.ps}).
1.1       anton    2554: 
1.21      crook    2555: doc-d>f
                   2556: doc-f>d
1.1       anton    2557: doc-f+
                   2558: doc-f-
                   2559: doc-f*
                   2560: doc-f/
                   2561: doc-fnegate
                   2562: doc-fabs
                   2563: doc-fmax
                   2564: doc-fmin
                   2565: doc-floor
                   2566: doc-fround
                   2567: doc-f**
                   2568: doc-fsqrt
                   2569: doc-fexp
                   2570: doc-fexpm1
                   2571: doc-fln
                   2572: doc-flnp1
                   2573: doc-flog
                   2574: doc-falog
1.32      anton    2575: doc-f2*
                   2576: doc-f2/
                   2577: doc-1/f
                   2578: doc-precision
                   2579: doc-set-precision
                   2580: 
                   2581: @cindex angles in trigonometric operations
                   2582: @cindex trigonometric operations
                   2583: Angles in floating point operations are given in radians (a full circle
                   2584: has 2 pi radians).
                   2585: 
1.1       anton    2586: doc-fsin
                   2587: doc-fcos
                   2588: doc-fsincos
                   2589: doc-ftan
                   2590: doc-fasin
                   2591: doc-facos
                   2592: doc-fatan
                   2593: doc-fatan2
                   2594: doc-fsinh
                   2595: doc-fcosh
                   2596: doc-ftanh
                   2597: doc-fasinh
                   2598: doc-facosh
                   2599: doc-fatanh
1.21      crook    2600: doc-pi
1.28      crook    2601: 
1.32      anton    2602: @cindex equality of floats
                   2603: @cindex floating-point comparisons
1.31      anton    2604: One particular problem with floating-point arithmetic is that comparison
                   2605: for equality often fails when you would expect it to succeed.  For this
                   2606: reason approximate equality is often preferred (but you still have to
                   2607: know what you are doing).  The comparison words are:
                   2608: 
                   2609: doc-f~rel
                   2610: doc-f~abs
                   2611: doc-f=
                   2612: doc-f~
                   2613: doc-f<>
                   2614: 
                   2615: doc-f<
                   2616: doc-f<=
                   2617: doc-f>
                   2618: doc-f>=
                   2619: 
1.21      crook    2620: doc-f0<
1.28      crook    2621: doc-f0<=
                   2622: doc-f0<>
1.21      crook    2623: doc-f0=
1.28      crook    2624: doc-f0>
                   2625: doc-f0>=
                   2626: 
1.1       anton    2627: 
                   2628: @node Stack Manipulation, Memory, Arithmetic, Words
                   2629: @section Stack Manipulation
                   2630: @cindex stack manipulation words
                   2631: 
                   2632: @cindex floating-point stack in the standard
1.21      crook    2633: Gforth maintains a number of separate stacks:
                   2634: 
1.29      crook    2635: @cindex data stack
                   2636: @cindex parameter stack
1.21      crook    2637: @itemize @bullet
                   2638: @item
1.29      crook    2639: A data stack (also known as the @dfn{parameter stack}) -- for
                   2640: characters, cells, addresses, and double cells.
1.21      crook    2641: 
1.29      crook    2642: @cindex floating-point stack
1.21      crook    2643: @item
                   2644: A floating point stack -- for floating point numbers.
                   2645: 
1.29      crook    2646: @cindex return stack
1.21      crook    2647: @item
                   2648: A return stack -- for storing the return addresses of colon
1.32      anton    2649: definitions and other (non-FP) data.
1.21      crook    2650: 
1.29      crook    2651: @cindex locals stack
1.21      crook    2652: @item
                   2653: A locals stack for storing local variables.
                   2654: @end itemize
                   2655: 
1.1       anton    2656: @menu
                   2657: * Data stack::                  
                   2658: * Floating point stack::        
                   2659: * Return stack::                
                   2660: * Locals stack::                
                   2661: * Stack pointer manipulation::  
                   2662: @end menu
                   2663: 
                   2664: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   2665: @subsection Data stack
                   2666: @cindex data stack manipulation words
                   2667: @cindex stack manipulations words, data stack
                   2668: 
                   2669: doc-drop
                   2670: doc-nip
                   2671: doc-dup
                   2672: doc-over
                   2673: doc-tuck
                   2674: doc-swap
1.21      crook    2675: doc-pick
1.1       anton    2676: doc-rot
                   2677: doc--rot
                   2678: doc-?dup
                   2679: doc-roll
                   2680: doc-2drop
                   2681: doc-2nip
                   2682: doc-2dup
                   2683: doc-2over
                   2684: doc-2tuck
                   2685: doc-2swap
                   2686: doc-2rot
                   2687: 
                   2688: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   2689: @subsection Floating point stack
                   2690: @cindex floating-point stack manipulation words
                   2691: @cindex stack manipulation words, floating-point stack
                   2692: 
1.32      anton    2693: Whilst every sane Forth has a separate floating-point stack, it is not
                   2694: strictly required; an ANS Forth system could theoretically keep
                   2695: floating-point numbers on the data stack. As an additional difficulty,
                   2696: you don't know how many cells a floating-point number takes. It is
                   2697: reportedly possible to write words in a way that they work also for a
                   2698: unified stack model, but we do not recommend trying it. Instead, just
                   2699: say that your program has an environmental dependency on a separate
                   2700: floating-point stack.
                   2701: 
                   2702: doc-floating-stack
                   2703: 
1.1       anton    2704: doc-fdrop
                   2705: doc-fnip
                   2706: doc-fdup
                   2707: doc-fover
                   2708: doc-ftuck
                   2709: doc-fswap
1.21      crook    2710: doc-fpick
1.1       anton    2711: doc-frot
                   2712: 
                   2713: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   2714: @subsection Return stack
                   2715: @cindex return stack manipulation words
                   2716: @cindex stack manipulation words, return stack
                   2717: 
1.32      anton    2718: @cindex return stack and locals
                   2719: @cindex locals and return stack
                   2720: A Forth system is allowed to keep local variables on the
                   2721: return stack. This is reasonable, as local variables usually eliminate
                   2722: the need to use the return stack explicitly. So, if you want to produce
                   2723: a standard compliant program and you are using local variables in a
                   2724: word, forget about return stack manipulations in that word (refer to the
                   2725: standard document for the exact rules).
                   2726: 
1.1       anton    2727: doc->r
                   2728: doc-r>
                   2729: doc-r@
                   2730: doc-rdrop
                   2731: doc-2>r
                   2732: doc-2r>
                   2733: doc-2r@
                   2734: doc-2rdrop
                   2735: 
                   2736: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   2737: @subsection Locals stack
                   2738: 
1.26      crook    2739: @comment TODO
1.21      crook    2740: 
1.1       anton    2741: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   2742: @subsection Stack pointer manipulation
                   2743: @cindex stack pointer manipulation words
                   2744: 
1.21      crook    2745: doc-sp0
1.1       anton    2746: doc-sp@
                   2747: doc-sp!
1.21      crook    2748: doc-fp0
1.1       anton    2749: doc-fp@
                   2750: doc-fp!
1.21      crook    2751: doc-rp0
1.1       anton    2752: doc-rp@
                   2753: doc-rp!
1.21      crook    2754: doc-lp0
1.1       anton    2755: doc-lp@
                   2756: doc-lp!
                   2757: 
                   2758: @node Memory, Control Structures, Stack Manipulation, Words
                   2759: @section Memory
1.26      crook    2760: @cindex memory words
1.1       anton    2761: 
1.32      anton    2762: @menu
                   2763: * Memory model::                
                   2764: * Dictionary allocation::       
                   2765: * Heap Allocation::             
                   2766: * Memory Access::               
                   2767: * Address arithmetic::          
                   2768: * Memory Blocks::               
                   2769: @end menu
                   2770: 
                   2771: @node Memory model, Dictionary allocation, Memory, Memory
                   2772: @subsection ANS Forth and Gforth memory models
                   2773: 
                   2774: @c The ANS Forth description is a mess (e.g., is the heap part of
                   2775: @c the dictionary?), so let's not stick to closely with it.
                   2776: 
                   2777: ANS Forth considers a Forth system as consisting of several memories, of
                   2778: which only @dfn{data space} is managed and accessible with the memory
                   2779: words.  Memory not necessarily in data space includes the stacks, the
                   2780: code (called code space) and the headers (called name space). In Gforth
                   2781: everything is in data space, but the code for the primitives is usually
                   2782: read-only.
                   2783: 
                   2784: Data space is divided into a number of areas: The (data space portion of
                   2785: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   2786: refer to the search data structure embodied in word lists and headers,
                   2787: because it is used for looking up names, just as you would in a
                   2788: conventional dictionary.}, the heap, and a number of system-allocated
                   2789: buffers.
                   2790: 
                   2791: In ANS Forth data space is also divided into contiguous regions.  You
                   2792: can only use address arithmetic within a contiguous region, not between
                   2793: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    2794: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    2795: allocation}).
                   2796: 
                   2797: Gforth provides one big address space, and address arithmetic can be
                   2798: performed between any addresses. However, in the dictionary headers or
                   2799: code are interleaved with data, so almost the only contiguous data space
                   2800: regions there are those described by ANS Forth as contiguous; but you
                   2801: can be sure that the dictionary is allocated towards increasing
                   2802: addresses even between contiguous regions.  The memory order of
                   2803: allocations in the heap is platform-dependent (and possibly different
                   2804: from one run to the next).
                   2805: 
                   2806: @subsubsection ANS Forth dictionary details
                   2807: 
                   2808: @c !! I have deleted some of the stuff this section refers to - anton
1.27      crook    2809: 
1.32      anton    2810: This section is just informative, you can skip it if you are in a hurry.
1.27      crook    2811: 
1.29      crook    2812: When you create a colon definition, the text interpreter compiles the
1.32      anton    2813: code for the definition into the code space and compiles the name
                   2814: of the definition into the header space, together with other
1.27      crook    2815: information about the definition (such as its execution token).
                   2816: 
                   2817: When you create a variable, the execution of @code{variable} will
1.32      anton    2818: compile some code, assign one cell in data space, and compile the name
                   2819: of the variable into the header space.
1.27      crook    2820: 
                   2821: @cindex memory regions - relationship between them
                   2822: ANS Forth does not specify the relationship between the three memory
                   2823: regions, and specifies that a Standard program must not access code or
                   2824: data space directly -- it may only access data space directly. In
                   2825: addition, the Standard defines what relationships you may and may not
                   2826: rely on when allocating regions in data space. These constraints are
                   2827: simply a reflection of the many diverse techniques that are used to
                   2828: implement Forth systems; understanding and following the requirements of
                   2829: the Standard allows you to write portable programs -- programs that run
                   2830: in the same way on any of these diverse systems. Another way of looking
                   2831: at this is to say that ANS Forth was designed to permit compliant Forth
                   2832: systems to be implemented in many diverse ways.
                   2833: 
                   2834: @cindex memory regions - how they are assigned
1.29      crook    2835: Here are some examples of ways in which name, code and data spaces
                   2836: might be assigned in different Forth implementations:
1.27      crook    2837: 
                   2838: @itemize @bullet
                   2839: @item
                   2840: For a Forth system that runs from RAM under a general-purpose operating
                   2841: system, it can be convenient to interleave name, code and data spaces in
                   2842: a single contiguous memory region. This organisation can be
                   2843: memory-efficient (for example, because the relationship between the name
1.32      anton    2844: dictionary entry and the associated code space entry can be
1.27      crook    2845: implicit, rather than requiring an explicit memory pointer to reference
1.32      anton    2846: from the header space and the code space). This is the
1.27      crook    2847: organisation used by Gforth, as this example@footnote{The addresses
                   2848: in the example have been truncated to fit it onto the page, and the
                   2849: addresses and data shown will not match the output from your system} shows:
                   2850: @example
                   2851: hex
                   2852: variable fred 123456 fred !
                   2853: variable jim abcd jim !
                   2854: : foo + / - ;
                   2855: ' fred 10 - 50 dump 
                   2856: ..80: 5C 46 0E 40  84 66 72 65 - 64 20 20 20  20 20 20 20  \F.@.fred       
                   2857: ..90: D0 9B 04 08  00 00 00 00 - 56 34 12 00  80 46 0E 40  ........V4...F.@
                   2858: ..A0: 83 6A 69 6D  20 20 20 20 - D0 9B 04 08  00 00 00 00  .jim    ........
                   2859: ..B0: CD AB 00 00  9C 46 0E 40 - 83 66 6F 6F  20 20 20 20  .....F.@.foo    
                   2860: ..C0: 80 9B 04 08  00 00 00 00 - E4 2E 05 08  0C 2F 05 08  ............./..
                   2861: @end example
                   2862: 
                   2863: @item
                   2864: For a high-performance system running on a modern RISC processor with a
                   2865: modified Harvard architecture (one that has a unified main memory but
                   2866: separate instruction and data caches), it is desirable to separate
                   2867: processor instructions from processor data. This encourages a high cache
1.32      anton    2868: density and therefore a high cache hit rate. The Forth code space
1.27      crook    2869: is not necessarily made up entirely of processor instructions; its
                   2870: nature is dependent upon the Forth implementation. 
                   2871: 
                   2872: @item
                   2873: A Forth compiler that runs on a segmented 8086 processor could be
                   2874: designed to interleave the name, code and data spaces within a single
                   2875: 64Kbyte segment. A more common implementation choice is to use a
                   2876: separate 64Kbyte segment for each region, which provides more memory
                   2877: overall but provides an address map in which only the data space is
                   2878: accessible.
                   2879: 
                   2880: @item
                   2881: Microprocessors exist that run Forth (or many of the primitives required
                   2882: to implement the Forth virtual machine efficiently) directly. On these
                   2883: processors, the relationship between name, code and data spaces may be
1.32      anton    2884: imposed as a side-effect of the architecture of the processor.
1.27      crook    2885: 
                   2886: @item
                   2887: A Forth compiler that executes from ROM on an embedded system needs its
                   2888: data space separated from the name and code spaces so that the data
                   2889: space can be mapped to a RAM area.
                   2890: 
                   2891: @item 
                   2892: A Forth compiler that runs on an embedded system may have a requirement
                   2893: for a small memory footprint. On such a system it can be useful to
1.32      anton    2894: separate the header space from the data and code spaces; once the
                   2895: application has been compiled, the header space is no longer
1.27      crook    2896: required@footnote{more strictly speaking, most applications can be
1.32      anton    2897: designed so that this is the case}. The header space can be deleted
1.29      crook    2898: entirely, or could be stored in memory on a remote @i{host} system for
1.27      crook    2899: debug and development purposes. In the latter case, the compiler running
1.29      crook    2900: on the @i{target} system could implement a protocol across a
1.32      anton    2901: communication link that would allow it to interrogate the header space.
1.27      crook    2902: @end itemize
                   2903: 
1.1       anton    2904: 
1.32      anton    2905: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   2906: @subsection Dictionary allocation
1.27      crook    2907: @cindex reserving data space
                   2908: @cindex data space - reserving some
                   2909: 
1.32      anton    2910: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   2911: you want to deallocate X, you also deallocate everything
                   2912: allocated after X.
                   2913: 
                   2914: The allocations using the words below are contiguous and grow the region
                   2915: towards increasing addresses.  Other words that allocate dictionary
                   2916: memory of any kind (i.e., defining words including @code{:noname}) end
                   2917: the contiguous region and start a new one.
                   2918: 
                   2919: In ANS Forth only @code{create}d words are guaranteed to produce an
                   2920: address that is the start of the following contiguous region.  In
                   2921: particular, the cell allocated by @code{variable} is not guaranteed to
                   2922: be contiguous with following @code{allot}ed memory.
                   2923: 
                   2924: You can deallocate memory by using @code{allot} with a negative argument
                   2925: (with some restrictions, see @code{allot}). For larger deallocations use
                   2926: @code{marker}.
1.27      crook    2927: 
1.29      crook    2928: 
1.27      crook    2929: doc-here
                   2930: doc-unused
                   2931: doc-allot
                   2932: doc-c,
1.29      crook    2933: doc-f,
1.27      crook    2934: doc-,
                   2935: doc-2,
1.29      crook    2936: @cindex user space
                   2937: doc-udp
                   2938: doc-uallot
1.27      crook    2939: 
1.32      anton    2940: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   2941: course you should allocate memory in an aligned way, too. I.e., before
                   2942: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   2943: The words below align @code{here} if it is not already.  Basically it is
                   2944: only already aligned for a type, if the last allocation was a multiple
                   2945: of the size of this type and if @code{here} was aligned for this type
                   2946: before.
                   2947: 
                   2948: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   2949: ANS Forth (@code{maxalign}ed in Gforth).
                   2950: 
                   2951: doc-align
                   2952: doc-falign
                   2953: doc-sfalign
                   2954: doc-dfalign
                   2955: doc-maxalign
                   2956: doc-cfalign
                   2957: 
                   2958: 
                   2959: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   2960: @subsection Heap allocation
                   2961: @cindex heap allocation
                   2962: @cindex dynamic allocation of memory
                   2963: @cindex memory-allocation word set
                   2964: 
                   2965: Heap allocation supports deallocation of allocated memory in any
                   2966: order. Dictionary allocation is not affected by it (i.e., it does not
                   2967: end a contiguous region). In Gforth, these words are implemented using
                   2968: the standard C library calls malloc(), free() and resize().
                   2969: 
                   2970: doc-allocate
                   2971: doc-free
                   2972: doc-resize
                   2973: 
1.27      crook    2974: 
1.32      anton    2975: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    2976: @subsection Memory Access
                   2977: @cindex memory access words
                   2978: 
                   2979: doc-@
                   2980: doc-!
                   2981: doc-+!
                   2982: doc-c@
                   2983: doc-c!
                   2984: doc-2@
                   2985: doc-2!
                   2986: doc-f@
                   2987: doc-f!
                   2988: doc-sf@
                   2989: doc-sf!
                   2990: doc-df@
                   2991: doc-df!
                   2992: 
1.32      anton    2993: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   2994: @subsection Address arithmetic
1.1       anton    2995: @cindex address arithmetic words
                   2996: 
1.32      anton    2997: Address arithmetic is the foundation on which data structures like
                   2998: arrays, records (@pxref{Structures}) and objects (@pxref{Object-oriented
                   2999: Forth}) are built.
                   3000: 
1.1       anton    3001: ANS Forth does not specify the sizes of the data types. Instead, it
                   3002: offers a number of words for computing sizes and doing address
1.29      crook    3003: arithmetic. Address arithmetic is performed in terms of address units
                   3004: (aus); on most systems the address unit is one byte. Note that a
                   3005: character may have more than one au, so @code{chars} is no noop (on
                   3006: systems where it is a noop, it compiles to nothing).
1.1       anton    3007: 
                   3008: @cindex alignment of addresses for types
                   3009: ANS Forth also defines words for aligning addresses for specific
                   3010: types. Many computers require that accesses to specific data types
                   3011: must only occur at specific addresses; e.g., that cells may only be
                   3012: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   3013: accesses, it can usually perform aligned accesses faster. 
                   3014: 
                   3015: For the performance-conscious: alignment operations are usually only
                   3016: necessary during the definition of a data structure, not during the
                   3017: (more frequent) accesses to it.
                   3018: 
                   3019: ANS Forth defines no words for character-aligning addresses. This is not
                   3020: an oversight, but reflects the fact that addresses that are not
                   3021: char-aligned have no use in the standard and therefore will not be
                   3022: created.
                   3023: 
                   3024: @cindex @code{CREATE} and alignment
1.29      crook    3025: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    3026: are cell-aligned; in addition, Gforth guarantees that these addresses
                   3027: are aligned for all purposes.
                   3028: 
1.26      crook    3029: Note that the ANS Forth word @code{char} has nothing to do with address
                   3030: arithmetic.
1.1       anton    3031: 
                   3032: doc-chars
                   3033: doc-char+
                   3034: doc-cells
                   3035: doc-cell+
                   3036: doc-cell
                   3037: doc-aligned
                   3038: doc-floats
                   3039: doc-float+
                   3040: doc-float
                   3041: doc-faligned
                   3042: doc-sfloats
                   3043: doc-sfloat+
                   3044: doc-sfaligned
                   3045: doc-dfloats
                   3046: doc-dfloat+
                   3047: doc-dfaligned
                   3048: doc-maxaligned
                   3049: doc-cfaligned
                   3050: doc-address-unit-bits
                   3051: 
1.32      anton    3052: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    3053: @subsection Memory Blocks
                   3054: @cindex memory block words
1.27      crook    3055: @cindex character strings - moving and copying
                   3056: 
                   3057: Memory blocks often represent character strings; @xref{String Formats}
                   3058: for ways of storing character strings in memory. @xref{Displaying
                   3059: characters and strings} for other string-processing words.
1.1       anton    3060: 
1.32      anton    3061: Some of these words work on address units. Others work on character
                   3062: units (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
                   3063: address. Choose the correct operation depending upon your data type.
1.21      crook    3064: 
                   3065: When copying characters between overlapping memory regions, choose
                   3066: carefully between @code{cmove} and @code{cmove>}.
                   3067: 
1.29      crook    3068: You can only use any of these words @i{portably} to access data space.
1.21      crook    3069: 
1.27      crook    3070: @comment TODO - think the naming of the arguments is wrong for move
1.29      crook    3071: @comment well, really it seems to be the Standard that's wrong; it
                   3072: @comment describes MOVE as a word that requires a CELL-aligned source
                   3073: @comment and destination address but a xtranfer count that need not
                   3074: @comment be a multiple of CELL.
1.1       anton    3075: doc-move
                   3076: doc-erase
                   3077: doc-cmove
                   3078: doc-cmove>
                   3079: doc-fill
                   3080: doc-blank
1.21      crook    3081: doc-compare
                   3082: doc-search
1.27      crook    3083: doc--trailing
                   3084: doc-/string
                   3085: 
                   3086: @comment TODO examples
                   3087: 
1.1       anton    3088: 
1.26      crook    3089: @node Control Structures, Defining Words, Memory, Words
1.1       anton    3090: @section Control Structures
                   3091: @cindex control structures
                   3092: 
1.33      anton    3093: Control structures in Forth cannot be used interpretively, only in a
                   3094: colon definition@footnote{To be precise, they have no interpretation
                   3095: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   3096: not like this limitation, but have not seen a satisfying way around it
                   3097: yet, although many schemes have been proposed.
1.1       anton    3098: 
                   3099: @menu
1.33      anton    3100: * Selection::                   IF ... ELSE ... ENDIF
                   3101: * Simple Loops::                BEGIN ...
1.29      crook    3102: * Counted Loops::               DO
                   3103: * Arbitrary control structures::
                   3104: * Calls and returns::
1.1       anton    3105: * Exception Handling::          
                   3106: @end menu
                   3107: 
                   3108: @node Selection, Simple Loops, Control Structures, Control Structures
                   3109: @subsection Selection
                   3110: @cindex selection control structures
                   3111: @cindex control structures for selection
                   3112: 
1.33      anton    3113: @c what's the purpose of all these @i? Maybe we should define a macro
                   3114: @c so we can produce logical markup.  - anton
                   3115: 
1.1       anton    3116: @cindex @code{IF} control structure
                   3117: @example
1.29      crook    3118: @i{flag}
1.1       anton    3119: IF
1.29      crook    3120:   @i{code}
1.1       anton    3121: ENDIF
                   3122: @end example
1.21      crook    3123: @noindent
1.33      anton    3124: 
                   3125: @var{code} is executed if @var{flag} is non-zero (that's truth as far as
                   3126: @code{IF} etc. are concerned).
                   3127: 
1.1       anton    3128: @example
1.29      crook    3129: @i{flag}
1.1       anton    3130: IF
1.29      crook    3131:   @i{code1}
1.1       anton    3132: ELSE
1.29      crook    3133:   @i{code2}
1.1       anton    3134: ENDIF
                   3135: @end example
                   3136: 
1.33      anton    3137: If @var{flag} is true, perform @var{code1}, otherwise @var{code2}.
                   3138: 
1.1       anton    3139: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   3140: standard, and @code{ENDIF} is not, although it is quite popular. We
                   3141: recommend using @code{ENDIF}, because it is less confusing for people
                   3142: who also know other languages (and is not prone to reinforcing negative
                   3143: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   3144: system that only supplies @code{THEN} is simple:
                   3145: @example
1.21      crook    3146: : ENDIF   POSTPONE THEN ; immediate
1.1       anton    3147: @end example
                   3148: 
                   3149: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   3150: (adv.)}  has the following meanings:
                   3151: @quotation
                   3152: ... 2b: following next after in order ... 3d: as a necessary consequence
                   3153: (if you were there, then you saw them).
                   3154: @end quotation
                   3155: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   3156: and many other programming languages has the meaning 3d.]
                   3157: 
1.21      crook    3158: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    3159: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    3160: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    3161: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   3162: @file{compat/control.fs}.
                   3163: 
                   3164: @cindex @code{CASE} control structure
                   3165: @example
1.29      crook    3166: @i{n}
1.1       anton    3167: CASE
1.29      crook    3168:   @i{n1} OF @i{code1} ENDOF
                   3169:   @i{n2} OF @i{code2} ENDOF
1.1       anton    3170:   @dots{}
                   3171: ENDCASE
                   3172: @end example
                   3173: 
1.29      crook    3174: Executes the first @i{codei}, where the @i{ni} is equal to
                   3175: @i{n}. A default case can be added by simply writing the code after
                   3176: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
1.1       anton    3177: but must not consume it.
                   3178: 
                   3179: @node Simple Loops, Counted Loops, Selection, Control Structures
                   3180: @subsection Simple Loops
                   3181: @cindex simple loops
                   3182: @cindex loops without count 
                   3183: 
                   3184: @cindex @code{WHILE} loop
                   3185: @example
                   3186: BEGIN
1.29      crook    3187:   @i{code1}
                   3188:   @i{flag}
1.1       anton    3189: WHILE
1.29      crook    3190:   @i{code2}
1.1       anton    3191: REPEAT
                   3192: @end example
                   3193: 
1.29      crook    3194: @i{code1} is executed and @i{flag} is computed. If it is true,
                   3195: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    3196: false, execution continues after the @code{REPEAT}.
                   3197: 
                   3198: @cindex @code{UNTIL} loop
                   3199: @example
                   3200: BEGIN
1.29      crook    3201:   @i{code}
                   3202:   @i{flag}
1.1       anton    3203: UNTIL
                   3204: @end example
                   3205: 
1.29      crook    3206: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    3207: 
                   3208: @cindex endless loop
                   3209: @cindex loops, endless
                   3210: @example
                   3211: BEGIN
1.29      crook    3212:   @i{code}
1.1       anton    3213: AGAIN
                   3214: @end example
                   3215: 
                   3216: This is an endless loop.
                   3217: 
                   3218: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   3219: @subsection Counted Loops
                   3220: @cindex counted loops
                   3221: @cindex loops, counted
                   3222: @cindex @code{DO} loops
                   3223: 
                   3224: The basic counted loop is:
                   3225: @example
1.29      crook    3226: @i{limit} @i{start}
1.1       anton    3227: ?DO
1.29      crook    3228:   @i{body}
1.1       anton    3229: LOOP
                   3230: @end example
                   3231: 
1.29      crook    3232: This performs one iteration for every integer, starting from @i{start}
                   3233: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    3234: accessed with @code{i}. For example, the loop:
1.1       anton    3235: @example
                   3236: 10 0 ?DO
                   3237:   i .
                   3238: LOOP
                   3239: @end example
1.21      crook    3240: @noindent
                   3241: prints @code{0 1 2 3 4 5 6 7 8 9}
                   3242: 
1.1       anton    3243: The index of the innermost loop can be accessed with @code{i}, the index
                   3244: of the next loop with @code{j}, and the index of the third loop with
                   3245: @code{k}.
                   3246: 
                   3247: doc-i
                   3248: doc-j
                   3249: doc-k
                   3250: 
                   3251: The loop control data are kept on the return stack, so there are some
1.21      crook    3252: restrictions on mixing return stack accesses and counted loop words. In
                   3253: particuler, if you put values on the return stack outside the loop, you
                   3254: cannot read them inside the loop@footnote{well, not in a way that is
                   3255: portable.}. If you put values on the return stack within a loop, you
                   3256: have to remove them before the end of the loop and before accessing the
                   3257: index of the loop.
1.1       anton    3258: 
                   3259: There are several variations on the counted loop:
                   3260: 
1.21      crook    3261: @itemize @bullet
                   3262: @item
                   3263: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   3264: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   3265: 
                   3266: @example
                   3267: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   3268: @end example
                   3269: prints @code{0 1 2 3}
                   3270: 
1.1       anton    3271: 
1.21      crook    3272: @item
                   3273: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   3274: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   3275: return stack so @code{EXIT} can get to its return address. For example:
                   3276: 
                   3277: @example
                   3278: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   3279: @end example
                   3280: prints @code{0 1 2 3}
                   3281: 
                   3282: 
                   3283: @item
1.29      crook    3284: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    3285: (and @code{LOOP} iterates until they become equal by wrap-around
                   3286: arithmetic). This behaviour is usually not what you want. Therefore,
                   3287: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    3288: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   3289: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    3290: unsigned loop parameters.
                   3291: 
1.21      crook    3292: @item
                   3293: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   3294: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   3295: if you know that the loop is entered in any case. Such knowledge tends
                   3296: to become invalid during maintenance of a program, and then the
                   3297: @code{DO} will make trouble.
                   3298: 
                   3299: @item
1.29      crook    3300: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   3301: index by @i{n} instead of by 1. The loop is terminated when the border
                   3302: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    3303: 
1.21      crook    3304: @example
                   3305: 4 0 +DO  i .  2 +LOOP
                   3306: @end example
                   3307: @noindent
                   3308: prints @code{0 2}
                   3309: 
                   3310: @example
                   3311: 4 1 +DO  i .  2 +LOOP
                   3312: @end example
                   3313: @noindent
                   3314: prints @code{1 3}
1.1       anton    3315: 
                   3316: 
                   3317: @cindex negative increment for counted loops
                   3318: @cindex counted loops with negative increment
1.29      crook    3319: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    3320: 
1.21      crook    3321: @example
                   3322: -1 0 ?DO  i .  -1 +LOOP
                   3323: @end example
                   3324: @noindent
                   3325: prints @code{0 -1}
1.1       anton    3326: 
1.21      crook    3327: @example
                   3328: 0 0 ?DO  i .  -1 +LOOP
                   3329: @end example
                   3330: prints nothing.
1.1       anton    3331: 
1.29      crook    3332: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   3333: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   3334: index by @i{u} each iteration. The loop is terminated when the border
                   3335: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    3336: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   3337: 
1.21      crook    3338: @example
                   3339: -2 0 -DO  i .  1 -LOOP
                   3340: @end example
                   3341: @noindent
                   3342: prints @code{0 -1}
1.1       anton    3343: 
1.21      crook    3344: @example
                   3345: -1 0 -DO  i .  1 -LOOP
                   3346: @end example
                   3347: @noindent
                   3348: prints @code{0}
                   3349: 
                   3350: @example
                   3351: 0 0 -DO  i .  1 -LOOP
                   3352: @end example
                   3353: @noindent
                   3354: prints nothing.
1.1       anton    3355: 
1.21      crook    3356: @end itemize
1.1       anton    3357: 
                   3358: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    3359: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   3360: for these words that uses only standard words is provided in
                   3361: @file{compat/loops.fs}.
1.1       anton    3362: 
                   3363: 
                   3364: @cindex @code{FOR} loops
1.26      crook    3365: Another counted loop is:
1.1       anton    3366: @example
1.29      crook    3367: @i{n}
1.1       anton    3368: FOR
1.29      crook    3369:   @i{body}
1.1       anton    3370: NEXT
                   3371: @end example
                   3372: This is the preferred loop of native code compiler writers who are too
1.26      crook    3373: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    3374: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   3375: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    3376: Forth systems may behave differently, even if they support @code{FOR}
                   3377: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    3378: 
                   3379: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   3380: @subsection Arbitrary control structures
                   3381: @cindex control structures, user-defined
                   3382: 
                   3383: @cindex control-flow stack
                   3384: ANS Forth permits and supports using control structures in a non-nested
                   3385: way. Information about incomplete control structures is stored on the
                   3386: control-flow stack. This stack may be implemented on the Forth data
                   3387: stack, and this is what we have done in Gforth.
                   3388: 
                   3389: @cindex @code{orig}, control-flow stack item
                   3390: @cindex @code{dest}, control-flow stack item
                   3391: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   3392: entry represents a backward branch target. A few words are the basis for
                   3393: building any control structure possible (except control structures that
                   3394: need storage, like calls, coroutines, and backtracking).
                   3395: 
                   3396: doc-if
                   3397: doc-ahead
                   3398: doc-then
                   3399: doc-begin
                   3400: doc-until
                   3401: doc-again
                   3402: doc-cs-pick
                   3403: doc-cs-roll
                   3404: 
1.21      crook    3405: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   3406: manipulate the control-flow stack in a portable way. Without them, you
                   3407: would need to know how many stack items are occupied by a control-flow
                   3408: entry (many systems use one cell. In Gforth they currently take three,
                   3409: but this may change in the future).
                   3410: 
1.1       anton    3411: Some standard control structure words are built from these words:
                   3412: 
                   3413: doc-else
                   3414: doc-while
                   3415: doc-repeat
                   3416: 
                   3417: Gforth adds some more control-structure words:
                   3418: 
                   3419: doc-endif
                   3420: doc-?dup-if
                   3421: doc-?dup-0=-if
                   3422: 
                   3423: Counted loop words constitute a separate group of words:
                   3424: 
                   3425: doc-?do
                   3426: doc-+do
                   3427: doc-u+do
                   3428: doc--do
                   3429: doc-u-do
                   3430: doc-do
                   3431: doc-for
                   3432: doc-loop
                   3433: doc-+loop
                   3434: doc--loop
                   3435: doc-next
                   3436: doc-leave
                   3437: doc-?leave
                   3438: doc-unloop
                   3439: doc-done
                   3440: 
1.21      crook    3441: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   3442: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    3443: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   3444: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   3445: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   3446: resolved (by using one of the loop-ending words or @code{DONE}).
                   3447: 
1.26      crook    3448: Another group of control structure words are:
1.1       anton    3449: 
                   3450: doc-case
                   3451: doc-endcase
                   3452: doc-of
                   3453: doc-endof
                   3454: 
1.21      crook    3455: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   3456: @code{CS-ROLL}.
1.1       anton    3457: 
                   3458: @subsubsection Programming Style
                   3459: 
                   3460: In order to ensure readability we recommend that you do not create
                   3461: arbitrary control structures directly, but define new control structure
                   3462: words for the control structure you want and use these words in your
1.26      crook    3463: program. For example, instead of writing:
1.1       anton    3464: 
                   3465: @example
1.26      crook    3466: BEGIN
1.1       anton    3467:   ...
1.26      crook    3468: IF [ 1 CS-ROLL ]
1.1       anton    3469:   ...
1.26      crook    3470: AGAIN THEN
1.1       anton    3471: @end example
                   3472: 
1.21      crook    3473: @noindent
1.1       anton    3474: we recommend defining control structure words, e.g.,
                   3475: 
                   3476: @example
1.26      crook    3477: : WHILE ( DEST -- ORIG DEST )
                   3478:  POSTPONE IF
                   3479:  1 CS-ROLL ; immediate
                   3480: 
                   3481: : REPEAT ( orig dest -- )
                   3482:  POSTPONE AGAIN
                   3483:  POSTPONE THEN ; immediate
1.1       anton    3484: @end example
                   3485: 
1.21      crook    3486: @noindent
1.1       anton    3487: and then using these to create the control structure:
                   3488: 
                   3489: @example
1.26      crook    3490: BEGIN
1.1       anton    3491:   ...
1.26      crook    3492: WHILE
1.1       anton    3493:   ...
1.26      crook    3494: REPEAT
1.1       anton    3495: @end example
                   3496: 
                   3497: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   3498: @code{WHILE} are predefined, so in this example it would not be
                   3499: necessary to define them.
                   3500: 
                   3501: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   3502: @subsection Calls and returns
                   3503: @cindex calling a definition
                   3504: @cindex returning from a definition
                   3505: 
1.3       anton    3506: @cindex recursive definitions
                   3507: A definition can be called simply be writing the name of the definition
1.26      crook    3508: to be called. Normally a definition is invisible during its own
1.3       anton    3509: definition. If you want to write a directly recursive definition, you
1.26      crook    3510: can use @code{recursive} to make the current definition visible, or
                   3511: @code{recurse} to call the current definition directly.
1.3       anton    3512: 
                   3513: doc-recursive
                   3514: doc-recurse
                   3515: 
1.21      crook    3516: @comment TODO add example of the two recursion methods
1.12      anton    3517: @quotation
                   3518: @progstyle
                   3519: I prefer using @code{recursive} to @code{recurse}, because calling the
                   3520: definition by name is more descriptive (if the name is well-chosen) than
                   3521: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   3522: implementation, it is much better to read (and think) ``now sort the
                   3523: partitions'' than to read ``now do a recursive call''.
                   3524: @end quotation
1.3       anton    3525: 
1.29      crook    3526: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    3527: 
                   3528: @example
1.28      crook    3529: Defer foo
1.3       anton    3530: 
                   3531: : bar ( ... -- ... )
                   3532:  ... foo ... ;
                   3533: 
                   3534: :noname ( ... -- ... )
                   3535:  ... bar ... ;
                   3536: IS foo
                   3537: @end example
                   3538: 
1.33      anton    3539: Deferred words are discussed in more detail in @ref{Simple
                   3540: Defining Words}.
                   3541: 
1.26      crook    3542: The current definition returns control to the calling definition when
1.33      anton    3543: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    3544: 
                   3545: doc-exit
                   3546: doc-;s
                   3547: 
                   3548: @node Exception Handling,  , Calls and returns, Control Structures
                   3549: @subsection Exception Handling
1.26      crook    3550: @cindex exceptions
1.1       anton    3551: 
1.26      crook    3552: If your program detects a fatal error condition, the simplest action
                   3553: that it can take is to @code{quit}. This resets the return stack and
                   3554: restarts the text interpreter, but does not print any error message.
1.21      crook    3555: 
1.26      crook    3556: The next stage in severity is to execute @code{abort}, which has the
                   3557: same effect as @code{quit}, with the addition that it resets the data
                   3558: stack.
1.1       anton    3559: 
1.26      crook    3560: A slightly more sophisticated approach is use use @code{abort"}, which
                   3561: compiles a string to be used as an error message and does a conditional
                   3562: @code{abort} at run-time. For example:
1.1       anton    3563: 
1.26      crook    3564: @example
1.30      anton    3565: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}}  ok
                   3566: @kbd{0 checker@key{RET}} A false flag ok
                   3567: @kbd{1 checker@key{RET}}
1.26      crook    3568: :1: That flag was true
                   3569: 1 checker
                   3570:   ^^^^^^^
                   3571: $400D1648 throw 
                   3572: $400E4660
                   3573: @end example
1.1       anton    3574: 
1.26      crook    3575: These simple techniques allow a program to react to a fatal error
                   3576: condition, but they are not exactly user-friendly. The ANS Forth
                   3577: Exception word set provides the pair of words @code{throw} and
                   3578: @code{catch}, which can be used to provide sophisticated error-handling.
1.1       anton    3579: 
1.26      crook    3580: @code{catch} has a similar behaviour to @code{execute}, in that it takes
1.29      crook    3581: an @i{xt} as a parameter and starts execution of the xt. However,
1.26      crook    3582: before passing control to the xt, @code{catch} pushes an
1.29      crook    3583: @dfn{exception frame} onto the @dfn{exception stack}. This exception
1.26      crook    3584: frame is used to restore the system to a known state if a detected error
                   3585: occurs during the execution of the xt. A typical way to use @code{catch}
                   3586: would be:
1.1       anton    3587: 
1.26      crook    3588: @example
                   3589: ... ['] foo catch IF ...
                   3590: @end example
1.1       anton    3591: 
1.33      anton    3592: @c TOS is undefined. - anton
1.26      crook    3593: Whilst @code{foo} executes, it can call other words to any level of
                   3594: nesting, as usual.  If @code{foo} (and all the words that it calls)
1.33      anton    3595: execute successfully, control will ultimately pass to the word following
                   3596: the @code{catch}, and there will be a 0 at TOS.  However, if any word
                   3597: detects an error, it can terminate the execution of @code{foo} by
                   3598: pushing a non-zero error code onto the stack and then performing a
                   3599: @code{throw}. The execution of @code{throw} will pass control to the
                   3600: word following the @code{catch}, but this time the TOS will hold the
                   3601: error code. Therefore, the @code{IF} in the example can be used to
                   3602: determine whether @code{foo} executed successfully.
1.1       anton    3603: 
1.26      crook    3604: This simple example shows how you can use @code{throw} and @code{catch}
                   3605: to ``take over'' exception handling from the system:
1.1       anton    3606: @example
1.26      crook    3607: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1       anton    3608: @end example
                   3609: 
1.26      crook    3610: The next example is more sophisticated and shows a multi-level
                   3611: @code{throw} and @code{catch}. To understand this example, start at the
                   3612: definition of @code{top-level} and work backwards:
                   3613: 
1.1       anton    3614: @example
1.26      crook    3615: : lowest-level ( -- c )
                   3616:     key dup 27 = if
                   3617:        1 throw \ ESCAPE key pressed
                   3618:     else
                   3619:        ." lowest-level successfull" CR
                   3620:     then
                   3621: ;
                   3622: 
                   3623: : lower-level ( -- c )
                   3624:     lowest-level
                   3625:     \ at this level consider a CTRL-U to be a fatal error
                   3626:     dup 21 = if \ CTRL-U
                   3627:        2 throw
                   3628:     else
                   3629:        ." lower-level successfull" CR
                   3630:     then
                   3631: ;
                   3632: 
                   3633: : low-level ( -- c )
                   3634:     ['] lower-level catch
                   3635:     ?dup if
                   3636:        \ error occurred - do we recognise it?
                   3637:        dup 1 = if
                   3638:            \ ESCAPE key pressed.. pretend it was an E
                   3639:            [char] E
                   3640:        else throw \ propogate the error upwards
                   3641:        then
                   3642:     then
                   3643:     ." low-level successfull" CR
                   3644: ;
                   3645: 
                   3646: : top-level ( -- )
                   3647:     CR ['] low-level catch \ CATCH is used like EXECUTE
                   3648:     ?dup if \ error occurred..
                   3649:        ." Error " . ." occurred - contact your supplier"
                   3650:     else
                   3651:        ." The '" emit ." ' key was pressed" CR
                   3652:     then
                   3653: ;
1.1       anton    3654: @end example
                   3655: 
1.26      crook    3656: The ANS Forth document assigns @code{throw} codes thus:
1.1       anton    3657: 
1.26      crook    3658: @itemize @bullet
                   3659: @item
                   3660: codes in the range -1 -- -255 are reserved to be assigned by the
                   3661: Standard. Assignments for codes in the range -1 -- -58 are currently
                   3662: documented in the Standard. In particular, @code{-1 throw} is equivalent
                   3663: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
                   3664: @item
                   3665: codes in the range -256 -- -4095 are reserved to be assigned by the system.
                   3666: @item
                   3667: all other codes may be assigned by programs.
                   3668: @end itemize
1.1       anton    3669: 
1.26      crook    3670: Gforth provides the word @code{exception} as a mechanism for assigning
                   3671: system throw codes to applications. This allows multiple applications to
                   3672: co-exist in memory without any clash of @code{throw} codes. A definition
                   3673: of @code{exception} in ANS Forth is provided in
                   3674: @file{compat/exception.fs}.
1.1       anton    3675: 
1.26      crook    3676: doc-quit
                   3677: doc-abort
                   3678: doc-abort"
1.1       anton    3679: 
1.26      crook    3680: doc-catch
1.29      crook    3681: doc-throw
                   3682: doc---exception-exception
                   3683: 
                   3684: 
                   3685: @c -------------------------------------------------------------
                   3686: @node Defining Words, The Text Interpreter, Control Structures, Words
                   3687: @section Defining Words
                   3688: @cindex defining words
                   3689: 
                   3690: @menu
                   3691: * Simple Defining Words::       Variables, values and constants
                   3692: * Colon Definitions::
                   3693: * User-defined Defining Words::
                   3694: * Supplying names::
                   3695: * Interpretation and Compilation Semantics::
                   3696: @end menu
                   3697: 
                   3698: @node Simple Defining Words, Colon Definitions, Defining Words, Defining Words
                   3699: @subsection Simple Defining Words
                   3700: @cindex simple defining words
                   3701: @cindex defining words, simple
                   3702: 
1.33      anton    3703: @c split this section?
                   3704: 
1.29      crook    3705: Defining words are used to create new entries in the dictionary. The
                   3706: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   3707: this:
                   3708: 
                   3709: @example
                   3710: CREATE new-word1
                   3711: @end example
                   3712: 
                   3713: @code{CREATE} is a parsing word that generates a dictionary entry for
                   3714: @code{new-word1}. When @code{new-word1} is executed, all that it does is
                   3715: leave an address on the stack. The address represents the value of
                   3716: the data space pointer (@code{HERE}) at the time that @code{new-word1}
                   3717: was defined. Therefore, @code{CREATE} is a way of associating a name
                   3718: with the address of a region of memory.
                   3719: 
1.34      anton    3720: doc-create
                   3721: 
1.29      crook    3722: By extending this example to reserve some memory in data space, we end
                   3723: up with a @i{variable}. Here are two different ways to do it:
                   3724: 
                   3725: @example
                   3726: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   3727: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   3728: @end example
                   3729: 
                   3730: The variable can be examined and modified using @code{@@} (``fetch'') and
                   3731: @code{!} (``store'') like this:
                   3732: 
                   3733: @example
                   3734: new-word2 @@ .      \ get address, fetch from it and display
                   3735: 1234 new-word2 !   \ new value, get address, store to it
                   3736: @end example
                   3737: 
                   3738: As a final refinement, the whole code sequence can be wrapped up in a
                   3739: defining word (pre-empting the subject of the next section), making it
                   3740: easier to create new variables:
                   3741: 
                   3742: @example
1.33      anton    3743: : myvariable ( "name" -- a-addr ) CREATE 0 , ;
1.29      crook    3744: 
                   3745: myvariable foo
                   3746: myvariable joe
                   3747: 
                   3748: 45 3 * foo !   \ set foo to 135
                   3749: 1234 joe !     \ set joe to 1234
                   3750: 3 joe +!       \ increment joe by 3.. to 1237
                   3751: @end example
                   3752: 
                   3753: Not surprisingly, there is no need to define @code{myvariable}, since
                   3754: Forth already has a definition @code{Variable}. It behaves in exactly
1.33      anton    3755: the same way as @code{myvariable}. Forth also provides @code{2Variable}
                   3756: and @code{fvariable} for double and floating-point variables,
                   3757: respectively.
1.29      crook    3758: 
1.34      anton    3759: doc-variable
                   3760: doc-2variable
                   3761: doc-fvariable
                   3762: 
1.29      crook    3763: @cindex arrays
                   3764: A similar mechanism can be used to create arrays. For example, an
                   3765: 80-character text input buffer:
                   3766: 
                   3767: @example
                   3768: CREATE text-buf 80 chars allot
                   3769: 
                   3770: text-buf 0 chars c@@ \ the 1st character (offset 0)
                   3771: text-buf 3 chars c@@ \ the 4th character (offset 3)
                   3772: @end example
                   3773: 
                   3774: You can build arbitrarily complex data structures by allocating
                   3775: appropriate areas of memory. @xref{Structures} for further discussions
                   3776: of this, and to learn about some Gforth tools that make it easier.
                   3777: 
                   3778: @cindex user variables
                   3779: @cindex user space
                   3780: The defining word @code{User} behaves in the same way as @code{Variable}.
                   3781: The difference is that it reserves space in @i{user (data) space} rather
                   3782: than normal data space. In a Forth system that has a multi-tasker, each
                   3783: task has its own set of user variables.
                   3784: 
1.34      anton    3785: doc-user
                   3786: 
1.29      crook    3787: @comment TODO is that stuff about user variables strictly correct? Is it
                   3788: @comment just terminal tasks that have user variables?
                   3789: @comment should document tasker.fs (with some examples) elsewhere
                   3790: @comment in this manual, then expand on user space and user variables.
                   3791: 
                   3792: After @code{CREATE} and @code{Variable}s, the next defining word to
                   3793: consider is @code{Constant}. @code{Constant} allows you to declare a
                   3794: fixed value and refer to it by name. For example:
                   3795: 
                   3796: @example
                   3797: 12 Constant INCHES-PER-FOOT
                   3798: 3E+08 fconstant SPEED-O-LIGHT
                   3799: @end example
                   3800: 
                   3801: A @code{Variable} can be both read and written, so its run-time
                   3802: behaviour is to supply an address through which its current value can be
                   3803: manipulated. In contrast, the value of a @code{Constant} cannot be
                   3804: changed once it has been declared@footnote{Well, often it can be -- but
                   3805: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   3806: on).} so it's not necessary to supply the address -- it is more
                   3807: efficient to return the value of the constant directly. That's exactly
                   3808: what happens; the run-time effect of a constant is to put its value on
                   3809: the top of the stack (@ref{User-defined Defining Words} describes one
                   3810: way of implementing @code{Constant}).
                   3811: 
                   3812: Gforth also provides @code{2Constant} and @code{fconstant} for defining
                   3813: double and floating-point constants, respectively.
                   3814: 
1.34      anton    3815: doc-constant
                   3816: doc-2constant
                   3817: doc-fconstant
                   3818: 
                   3819: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.29      crook    3820: Constants in Forth behave differently from their equivalents in other
                   3821: programming languages. In other languages, a constant (such as an EQU in
                   3822: assembler or a #define in C) only exists at compile-time; in the
                   3823: executable program the constant has been translated into an absolute
                   3824: number and, unless you are using a symbolic debugger, it's impossible to
                   3825: know what abstract thing that number represents. In Forth a constant has
1.32      anton    3826: an entry in the header space and remains there after the code that
1.29      crook    3827: uses it has been defined. In fact, it must remain in the dictionary
                   3828: since it has run-time duties to perform. For example:
                   3829: 
                   3830: @example
                   3831: 12 Constant INCHES-PER-FOOT
                   3832: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   3833: @end example
                   3834: 
                   3835: @cindex in-lining of constants
                   3836: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   3837: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   3838: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   3839: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   3840: attempt to optimise constants by in-lining them where they are used. You
                   3841: can force Gforth to in-line a constant like this:
                   3842: 
                   3843: @example
                   3844: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   3845: @end example
                   3846: 
                   3847: If you use @code{see} to decompile @i{this} version of
                   3848: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.33      anton    3849: longer present. @xref{Interpret/Compile states} and @ref{Literals} on
                   3850: how this works.
1.29      crook    3851: 
                   3852: In-lining constants in this way might improve execution time
                   3853: fractionally, and can ensure that a constant is now only referenced at
                   3854: compile-time. However, the definition of the constant still remains in
                   3855: the dictionary. Some Forth compilers provide a mechanism for controlling
                   3856: a second dictionary for holding transient words such that this second
                   3857: dictionary can be deleted later in order to recover memory
                   3858: space. However, there is no standard way of doing this.
                   3859: 
                   3860: One aspect of constants and variables that can sometimes be confusing is
                   3861: that they have different stack effects; one returns its value whilst the
                   3862: other returns the address of its value. The defining word @code{Value}
                   3863: provides an alternative to @code{Variable}, and has the same stack
                   3864: effect as a constant. A @code{Value} needs an additional word, @code{TO}
                   3865: to allow its value to be changed. Here are some examples:
                   3866: 
                   3867: @example
                   3868: 12 Value APPLES \ a Value is initialised when it is declared.. like a
                   3869:                 \ constant but unlike a variable
                   3870: 34 TO APPLES    \ Change the value of APPLES. TO is a parsing word
                   3871: APPLES          \ puts 34 on the top of the stack.
                   3872: @end example
                   3873: 
1.34      anton    3874: doc-value
                   3875: doc-to
                   3876: 
1.29      crook    3877: The defining word @code{Defer} allows you to define a word by name
                   3878: without defining its behaviour; the definition of its behaviour is
                   3879: deferred. Here are two situation where this can be useful:
                   3880: 
                   3881: @itemize @bullet
                   3882: @item
                   3883: Where you want to allow the behaviour of a word to be altered later, and
                   3884: for all precompiled references to the word to change when its behaviour
                   3885: is changed.
                   3886: @item
                   3887: For mutual recursion; @xref{Calls and returns}.
                   3888: @end itemize
                   3889: 
                   3890: In the following example, @code{foo} always invokes the version of
                   3891: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   3892: always invokes the version that prints ``@code{Hello}''. There is no way
                   3893: of getting @code{foo} to use the later version without re-ordering the
                   3894: source code and recompilng it.
                   3895: 
                   3896: @example
                   3897: : greet ." Good morning" ;
                   3898: : foo ... greet ... ;
                   3899: : greet ." Hello" ;
                   3900: : bar ... greet ... ;
                   3901: @end example
                   3902: 
                   3903: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   3904: word. The behaviour of a @code{Defer}red word can be defined and
                   3905: redefined at any time by using @code{IS} to associate the xt of a
                   3906: previously-defined word with it. The previous example becomes:
                   3907: 
                   3908: @example
                   3909: Defer greet
                   3910: : foo ... greet ... ;
                   3911: : bar ... greet ... ;
                   3912: : greet1 ." Good morning" ;
                   3913: : greet2 ." Hello" ;
1.35      anton    3914: ' greet2 <IS> greet  \ make greet behave like greet2
                   3915: @end example
                   3916: 
                   3917: One thing to note is that @code{<IS>} consumes it's name when it is
                   3918: executed.  If you want to specify the name at compile time, use
                   3919: @code{[IS]}:
                   3920: 
                   3921: @example
                   3922: : set-greet ( xt -- )
                   3923:   [IS] greet ;
                   3924: 
                   3925: ' greet1 set-greet
1.29      crook    3926: @end example
                   3927: 
                   3928: A deferred word can only inherit default semantics from the xt (because
                   3929: that is all that an xt can represent -- @pxref{Tokens for Words} for
                   3930: more discussion of this). However, the semantics of the deferred word
                   3931: itself can be modified at the time that it is defined. For example:
                   3932: 
                   3933: @example
                   3934: : bar .... ; compile-only
                   3935: Defer fred immediate
                   3936: Defer jim
                   3937: 
1.35      anton    3938: ' bar <IS> jim  \ jim has default semantics
                   3939: ' bar <IS> fred \ fred is immediate
1.29      crook    3940: @end example
1.1       anton    3941: 
1.34      anton    3942: doc-defer
1.35      anton    3943: doc-<is>
                   3944: doc-[is]
                   3945: @comment TODO document these: what's defers [is]
1.34      anton    3946: doc-what's
                   3947: doc-defers
                   3948: 
                   3949: Definitions in ANS Forth for @code{defer}, @code{<is>} and
                   3950: @code{[is]} are provided in @file{compat/defer.fs}.
                   3951: 
1.29      crook    3952: The defining word @code{Alias} allows you to define a word by name that
                   3953: has the same behaviour as some other word. Here are two situation where
                   3954: this can be useful:
1.1       anton    3955: 
1.29      crook    3956: @itemize @bullet
                   3957: @item
                   3958: When you want access to a word's definition from a different word list
                   3959: (for an example of this, see the definition of the @code{Root} word list
                   3960: in the Gforth source).
                   3961: @item
                   3962: When you want to create a synonym; a definition that can be known by
                   3963: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   3964: aliases).
                   3965: @end itemize
1.1       anton    3966: 
1.29      crook    3967: The word whose behaviour the alias is to inherit is represented by an
1.34      anton    3968: xt. Therefore, the alias only inherits default semantics from its
1.29      crook    3969: ancestor. The semantics of the alias itself can be modified at the time
                   3970: that it is defined. For example:
1.1       anton    3971: 
1.29      crook    3972: @example
                   3973: : foo ... ; immediate
1.1       anton    3974: 
1.29      crook    3975: ' foo Alias bar \ bar is not an immediate word
                   3976: ' foo Alias fooby immediate \ fooby is an immediate word
                   3977: @end example
1.26      crook    3978: 
1.34      anton    3979: @c "combined words" is an undefined term
                   3980: Words that are aliases have the same xt, different headers in the
                   3981: dictionary, and consequently different name tokens (@pxref{Tokens for
                   3982: Words}) and possibly different immediate flags.  An alias can only have
                   3983: default or immediate compilation semantics; you can define aliases for
                   3984: combined words with @code{interpret/compile:}.
1.27      crook    3985: 
1.33      anton    3986: @c distribute this to the appropriate paragraphs? - anton
1.29      crook    3987: doc-alias
1.1       anton    3988: 
1.26      crook    3989: @node Colon Definitions, User-defined Defining Words, Simple Defining Words, Defining Words
                   3990: @subsection Colon Definitions
                   3991: @cindex colon definitions
1.1       anton    3992: 
1.26      crook    3993: @example
                   3994: : name ( ... -- ... )
                   3995:     word1 word2 word3 ;
                   3996: @end example
1.1       anton    3997: 
1.29      crook    3998: @noindent
                   3999: Creates a word called @code{name} that, upon execution, executes
1.26      crook    4000: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.1       anton    4001: 
1.29      crook    4002: The explanation above is somewhat superficial. @xref{Your first
                   4003: definition} for simple examples of colon definitions, then
                   4004: @xref{Interpretation and Compilation Semantics} for an in-depth
                   4005: discussion of some of the issues involved.
1.26      crook    4006: 
                   4007: doc-:
                   4008: doc-;
1.1       anton    4009: 
1.26      crook    4010: @node User-defined Defining Words, Supplying names, Colon Definitions, Defining Words
                   4011: @subsection User-defined Defining Words
                   4012: @cindex user-defined defining words
                   4013: @cindex defining words, user-defined
1.1       anton    4014: 
1.29      crook    4015: You can create a new defining word by wrapping defining-time code around
                   4016: an existing defining word and putting the sequence in a colon
                   4017: definition. For example, suppose that you have a word @code{stats} that
                   4018: gathers statistics about colon definitions given the @i{xt} of the
                   4019: definition, and you want every colon definition in your application to
                   4020: make a call to @code{stats}. You can define and use a new version of
                   4021: @code{:} like this:
                   4022: 
                   4023: @example
                   4024: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   4025:   ... ;  \ other code
                   4026: 
                   4027: : my: : lastxt postpone literal ['] stats compile, ;
                   4028: 
                   4029: my: foo + - ;
                   4030: @end example
                   4031: 
                   4032: When @code{foo} is defined using @code{my:} these steps occur:
                   4033: 
                   4034: @itemize @bullet
                   4035: @item
                   4036: @code{my:} is executed.
                   4037: @item
                   4038: The @code{:} within the definition (the one between @code{my:} and
                   4039: @code{lastxt}) is executed, and does just what it always does; it parses
                   4040: the input stream for a name, builds a dictionary header for the name
                   4041: @code{foo} and switches @code{state} from interpret to compile.
                   4042: @item
                   4043: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
                   4044: being defined -- @code{foo} -- onto the stack.
                   4045: @item
                   4046: The code that was produced by @code{postpone literal} is executed; this
                   4047: causes the value on the stack to be compiled as a literal in the code
                   4048: area of @code{foo}.
                   4049: @item
                   4050: The code @code{['] stats} compiles a literal into the definition of
                   4051: @code{my:}. When @code{compile,} is executed, that literal -- the
                   4052: execution token for @code{stats} -- is layed down in the code area of
                   4053: @code{foo} , following the literal@footnote{Strictly speaking, the
                   4054: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   4055: in the code area is implementation-dependent. A threaded implementation
                   4056: might spit out the execution token directly whilst another
                   4057: implementation might spit out a native code sequence.}.
                   4058: @item
                   4059: At this point, the execution of @code{my:} is complete, and control
                   4060: returns to the text interpreter. The text interpreter is in compile
                   4061: state, so subsequent text @code{+ -} is compiled into the definition of
                   4062: @code{foo} and the @code{;} terminates the definition as always.
                   4063: @end itemize
                   4064: 
                   4065: You can use @code{see} to decompile a word that was defined using
                   4066: @code{my:} and see how it is different from a normal @code{:}
                   4067: definition. For example:
                   4068: 
                   4069: @example
                   4070: : bar + - ;  \ like foo but using : rather than my:
                   4071: see bar
                   4072: : bar
                   4073:   + - ;
                   4074: see foo
                   4075: : foo
                   4076:   107645672 stats + - ;
                   4077: 
                   4078: \ use ' stats . to show that 107645672 is the xt for stats
                   4079: @end example
                   4080: 
                   4081: 
1.33      anton    4082: @c a deferred word is not neccessary for these examples. - anton
1.29      crook    4083: Rather than edit your application's source code to change every @code{:}
                   4084: to a @code{my:}, use a deferred word:
                   4085: 
                   4086: @example
                   4087: : real: : ;     \ retain access to the original
                   4088: defer :         \ redefine as a deferred word
                   4089: ' my: IS :      \ use special version of :
                   4090: \
                   4091: \ load application here
                   4092: \
                   4093: ' real: IS :    \ go back to the original
                   4094: @end example
                   4095: 
                   4096: You can use techniques like this to make new defining words in terms of
                   4097: @i{any} existing defining word.
1.1       anton    4098: 
                   4099: 
1.29      crook    4100: @cindex defining defining words
1.26      crook    4101: @cindex @code{CREATE} ... @code{DOES>}
                   4102: If you want the words defined with your defining words to behave
                   4103: differently from words defined with standard defining words, you can
                   4104: write your defining word like this:
1.1       anton    4105: 
                   4106: @example
1.26      crook    4107: : def-word ( "name" -- )
1.29      crook    4108:     CREATE @i{code1}
1.26      crook    4109: DOES> ( ... -- ... )
1.29      crook    4110:     @i{code2} ;
1.26      crook    4111: 
                   4112: def-word name
1.1       anton    4113: @end example
                   4114: 
1.29      crook    4115: @cindex child words
                   4116: This fragment defines a @dfn{defining word} @code{def-word} and then
                   4117: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   4118: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   4119: is not executed at this time. The word @code{name} is sometimes called a
                   4120: @dfn{child} of @code{def-word}.
                   4121: 
                   4122: When you execute @code{name}, the address of the body of @code{name} is
                   4123: put on the data stack and @i{code2} is executed (the address of the body
                   4124: of @code{name} is the address @code{HERE} returns immediately after the
                   4125: @code{CREATE}).
                   4126: 
                   4127: @cindex atavism in child words
1.33      anton    4128: You can use @code{def-word} to define a set of child words that behave
1.29      crook    4129: differently, though atavistically; they all have a common run-time
                   4130: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
                   4131: builds a data area in the body of the child word. The structure of the
                   4132: data is common to all children of @code{def-word}, but the data values
                   4133: are specific -- and private -- to each child word. When a child word is
                   4134: executed, the address of its private data area is passed as a parameter
                   4135: on TOS to be used and manipulated@footnote{It is legitimate both to read
                   4136: and write to this data area.} by @i{code2}.
                   4137: 
                   4138: The two fragments of code that make up the defining words act (are
                   4139: executed) at two completely separate times:
1.1       anton    4140: 
1.29      crook    4141: @itemize @bullet
                   4142: @item
                   4143: At @i{define time}, the defining word executes @i{code1} to generate a
                   4144: child word
                   4145: @item
                   4146: At @i{child execution time}, when a child word is invoked, @i{code2}
                   4147: is executed, using parameters (data) that are private and specific to
                   4148: the child word.
                   4149: @end itemize
                   4150: 
                   4151: @c NAC I think this is a really bad example, because it diminishes
                   4152: @c rather than emphasising the fact that some important stuff happens
                   4153: @c at define time, and other important stuff happens at child-invocation
                   4154: @c time, and that those two times are potentially very different.
1.33      anton    4155: 
                   4156: @c Well, IMO CREATE-DOES> is usually presented with much ado, making
                   4157: @c people think that it's hard to understand, and making those people who
                   4158: @c understand it easily think that it's hyped.  I prefer presenting it in a
                   4159: @c diminished way and only emphasize the special issues later. - anton
                   4160: 
                   4161: In other words, if you make the following definitions:
                   4162: @example
                   4163: : def-word1 ( "name" -- )
                   4164:     CREATE @i{code1} ;
                   4165: 
                   4166: : action1 ( ... -- ... )
                   4167:     @i{code2} ;
                   4168: 
                   4169: def-word1 name1
                   4170: @end example
                   4171: 
                   4172: Using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    4173: 
1.29      crook    4174: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    4175: 
1.1       anton    4176: @example
1.29      crook    4177: : CONSTANT ( w "name" -- )
                   4178:     CREATE ,
1.26      crook    4179: DOES> ( -- w )
                   4180:     @@ ;
1.1       anton    4181: @end example
                   4182: 
1.29      crook    4183: @comment There is a beautiful description of how this works and what
                   4184: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   4185: @comment commentary on the Counting Fruits problem.
                   4186: 
                   4187: When you create a constant with @code{5 CONSTANT five}, a set of
                   4188: define-time actions take place; first a new word @code{five} is created,
                   4189: then the value 5 is laid down in the body of @code{five} with
                   4190: @code{,}. When @code{five} is invoked, the address of the body is put on
                   4191: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   4192: no code of its own; it simply contains a data field and a pointer to the
                   4193: code that follows @code{DOES>} in its defining word. That makes words
                   4194: created in this way very compact.
                   4195: 
                   4196: The final example in this section is intended to remind you that space
                   4197: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   4198: both read and written by a Standard program@footnote{Exercise: use this
                   4199: example as a starting point for your own implementation of @code{Value}
                   4200: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   4201: @code{[']}.}:
                   4202: 
                   4203: @example
                   4204: : foo ( "name" -- )
                   4205:     CREATE -1 ,
                   4206: DOES> ( -- )
1.33      anton    4207:     @@ . ;
1.29      crook    4208: 
                   4209: foo first-word
                   4210: foo second-word
                   4211: 
                   4212: 123 ' first-word >BODY !
                   4213: @end example
                   4214: 
                   4215: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   4216: have executed it to get the address of its data field. However, since it
                   4217: was defined to have @code{DOES>} actions, its execution semantics are to
                   4218: perform those @code{DOES>} actions. To get the address of its data field
                   4219: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   4220: translate the xt into the address of the data field.  When you execute
                   4221: @code{first-word}, it will display @code{123}. When you execute
                   4222: @code{second-word} it will display @code{-1}.
1.26      crook    4223: 
                   4224: @cindex stack effect of @code{DOES>}-parts
                   4225: @cindex @code{DOES>}-parts, stack effect
1.29      crook    4226: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    4227: the stack effect of the defined words, not the stack effect of the
                   4228: following code (the following code expects the address of the body on
                   4229: the top of stack, which is not reflected in the stack comment). This is
                   4230: the convention that I use and recommend (it clashes a bit with using
                   4231: locals declarations for stack effect specification, though).
1.1       anton    4232: 
1.26      crook    4233: @subsubsection Applications of @code{CREATE..DOES>}
                   4234: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    4235: 
1.26      crook    4236: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    4237: 
1.26      crook    4238: @cindex factoring similar colon definitions
                   4239: When you see a sequence of code occurring several times, and you can
                   4240: identify a meaning, you will factor it out as a colon definition. When
                   4241: you see similar colon definitions, you can factor them using
                   4242: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   4243: that look very similar:
1.1       anton    4244: @example
1.26      crook    4245: : ori, ( reg-target reg-source n -- )
                   4246:     0 asm-reg-reg-imm ;
                   4247: : andi, ( reg-target reg-source n -- )
                   4248:     1 asm-reg-reg-imm ;
1.1       anton    4249: @end example
                   4250: 
1.26      crook    4251: @noindent
                   4252: This could be factored with:
                   4253: @example
                   4254: : reg-reg-imm ( op-code -- )
                   4255:     CREATE ,
                   4256: DOES> ( reg-target reg-source n -- )
                   4257:     @@ asm-reg-reg-imm ;
                   4258: 
                   4259: 0 reg-reg-imm ori,
                   4260: 1 reg-reg-imm andi,
                   4261: @end example
1.1       anton    4262: 
1.26      crook    4263: @cindex currying
                   4264: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   4265: supply a part of the parameters for a word (known as @dfn{currying} in
                   4266: the functional language community). E.g., @code{+} needs two
                   4267: parameters. Creating versions of @code{+} with one parameter fixed can
                   4268: be done like this:
1.1       anton    4269: @example
1.26      crook    4270: : curry+ ( n1 -- )
                   4271:     CREATE ,
                   4272: DOES> ( n2 -- n1+n2 )
                   4273:     @@ + ;
                   4274: 
                   4275:  3 curry+ 3+
                   4276: -2 curry+ 2-
1.1       anton    4277: @end example
                   4278: 
1.26      crook    4279: @subsubsection The gory details of @code{CREATE..DOES>}
                   4280: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    4281: 
1.26      crook    4282: doc-does>
1.1       anton    4283: 
1.26      crook    4284: @cindex @code{DOES>} in a separate definition
                   4285: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   4286: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    4287: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    4288: @example
                   4289: : does1 
                   4290: DOES> ( ... -- ... )
                   4291:     ... ;
1.1       anton    4292: 
1.26      crook    4293: : does2
                   4294: DOES> ( ... -- ... )
                   4295:     ... ;
1.1       anton    4296: 
1.26      crook    4297: : def-word ( ... -- ... )
                   4298:     create ...
                   4299:     IF
                   4300:        does1
                   4301:     ELSE
                   4302:        does2
                   4303:     ENDIF ;
                   4304: @end example
1.1       anton    4305: 
1.26      crook    4306: In this example, the selection of whether to use @code{does1} or
                   4307: @code{does2} is made at compile-time; at the time that the child word is
1.29      crook    4308: @code{CREATE}d.
1.1       anton    4309: 
1.26      crook    4310: @cindex @code{DOES>} in interpretation state
                   4311: In a standard program you can apply a @code{DOES>}-part only if the last
                   4312: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   4313: will override the behaviour of the last word defined in any case. In a
                   4314: standard program, you can use @code{DOES>} only in a colon
                   4315: definition. In Gforth, you can also use it in interpretation state, in a
                   4316: kind of one-shot mode; for example:
1.1       anton    4317: @example
1.26      crook    4318: CREATE name ( ... -- ... )
1.29      crook    4319:   @i{initialization}
1.26      crook    4320: DOES>
1.29      crook    4321:   @i{code} ;
1.1       anton    4322: @end example
                   4323: 
1.26      crook    4324: @noindent
                   4325: is equivalent to the standard:
1.1       anton    4326: @example
1.26      crook    4327: :noname
                   4328: DOES>
1.29      crook    4329:     @i{code} ;
1.26      crook    4330: CREATE name EXECUTE ( ... -- ... )
1.29      crook    4331:     @i{initialization}
1.1       anton    4332: @end example
                   4333: 
1.26      crook    4334: You can get the address of the body of a word with:
                   4335: 
                   4336: doc->body
1.1       anton    4337: 
1.26      crook    4338: @node Supplying names, Interpretation and Compilation Semantics, User-defined Defining Words, Defining Words
1.29      crook    4339: @subsection Supplying the name of a defined word
1.26      crook    4340: @cindex names for defined words
                   4341: @cindex defining words, name parameter
1.1       anton    4342: 
1.26      crook    4343: @cindex defining words, name given in a string
1.29      crook    4344: By default, a defining word takes the name for the defined word from the
1.26      crook    4345: input stream. Sometimes you want to supply the name from a string. You
                   4346: can do this with:
1.1       anton    4347: 
1.26      crook    4348: doc-nextname
1.1       anton    4349: 
1.26      crook    4350: For example:
1.1       anton    4351: 
1.26      crook    4352: @example
                   4353: s" foo" nextname create
                   4354: @end example
                   4355: @noindent
                   4356: is equivalent to:
                   4357: @example
                   4358: create foo
                   4359: @end example
1.1       anton    4360: 
1.26      crook    4361: @cindex defining words without name
1.29      crook    4362: Sometimes you want to define an @dfn{anonymous word}; a word without a
1.26      crook    4363: name. You can do this with:
1.1       anton    4364: 
1.26      crook    4365: doc-:noname
1.1       anton    4366: 
1.26      crook    4367: This leaves the execution token for the word on the stack after the
                   4368: closing @code{;}. Here's an example in which a deferred word is
                   4369: initialised with an @code{xt} from an anonymous colon definition:
                   4370: @example
                   4371: Defer deferred
                   4372: :noname ( ... -- ... )
                   4373:   ... ;
                   4374: IS deferred
                   4375: @end example
1.1       anton    4376: 
1.29      crook    4377: @noindent
1.26      crook    4378: Gforth provides an alternative way of doing this, using two separate
                   4379: words:
1.1       anton    4380: 
1.26      crook    4381: doc-noname
                   4382: @cindex execution token of last defined word
                   4383: doc-lastxt
1.1       anton    4384: 
1.29      crook    4385: @noindent
1.26      crook    4386: The previous example can be rewritten using @code{noname} and
                   4387: @code{lastxt}:
1.1       anton    4388: 
1.26      crook    4389: @example
                   4390: Defer deferred
                   4391: noname : ( ... -- ... )
                   4392:   ... ;
                   4393: lastxt IS deferred
                   4394: @end example
1.1       anton    4395: 
1.29      crook    4396: @noindent
1.33      anton    4397: @code{noname} and @code{nextname} work with any defining word, not just
                   4398: @code{:}.
                   4399: 
1.26      crook    4400: @code{lastxt} also works when the last word was not defined as
1.29      crook    4401: @code{noname}. It also has the useful property that is is valid as soon
                   4402: as the header for a definition has been build. Thus:
                   4403: 
                   4404: @example
                   4405: lastxt . : foo [ lastxt . ] ; ' foo .
                   4406: @end example
                   4407: 
                   4408: @noindent
                   4409: prints 3 numbers; the last two are the same.
1.1       anton    4410: 
                   4411: 
1.26      crook    4412: @node Interpretation and Compilation Semantics,  , Supplying names, Defining Words
                   4413: @subsection Interpretation and Compilation Semantics
                   4414: @cindex semantics, interpretation and compilation
1.1       anton    4415: 
1.26      crook    4416: @cindex interpretation semantics
                   4417: The @dfn{interpretation semantics} of a word are what the text
                   4418: interpreter does when it encounters the word in interpret state. It also
                   4419: appears in some other contexts, e.g., the execution token returned by
1.29      crook    4420: @code{' @i{word}} identifies the interpretation semantics of
                   4421: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
                   4422: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    4423: 
1.26      crook    4424: @cindex compilation semantics
                   4425: The @dfn{compilation semantics} of a word are what the text interpreter
                   4426: does when it encounters the word in compile state. It also appears in
1.29      crook    4427: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26      crook    4428: standard terminology, ``appends to the current definition''.} the
1.29      crook    4429: compilation semantics of @i{word}.
1.1       anton    4430: 
1.26      crook    4431: @cindex execution semantics
                   4432: The standard also talks about @dfn{execution semantics}. They are used
                   4433: only for defining the interpretation and compilation semantics of many
                   4434: words. By default, the interpretation semantics of a word are to
                   4435: @code{execute} its execution semantics, and the compilation semantics of
                   4436: a word are to @code{compile,} its execution semantics.@footnote{In
                   4437: standard terminology: The default interpretation semantics are its
                   4438: execution semantics; the default compilation semantics are to append its
                   4439: execution semantics to the execution semantics of the current
                   4440: definition.}
                   4441: 
                   4442: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   4443: 
                   4444: @cindex immediate words
                   4445: @cindex compile-only words
                   4446: You can change the semantics of the most-recently defined word:
                   4447: 
                   4448: doc-immediate
                   4449: doc-compile-only
                   4450: doc-restrict
                   4451: 
                   4452: Note that ticking (@code{'}) a compile-only word gives an error
                   4453: (``Interpreting a compile-only word'').
1.1       anton    4454: 
1.26      crook    4455: Gforth also allows you to define words with arbitrary combinations of
                   4456: interpretation and compilation semantics.
1.1       anton    4457: 
1.26      crook    4458: doc-interpret/compile:
1.1       anton    4459: 
1.26      crook    4460: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   4461: recommend that you do not define such words, as cute as they may be:
                   4462: they make it hard to get at both parts of the word in some contexts.
                   4463: E.g., assume you want to get an execution token for the compilation
                   4464: part. Instead, define two words, one that embodies the interpretation
                   4465: part, and one that embodies the compilation part.  Once you have done
                   4466: that, you can define a combined word with @code{interpret/compile:} for
                   4467: the convenience of your users.
1.1       anton    4468: 
1.26      crook    4469: You might try to use this feature to provide an optimizing
                   4470: implementation of the default compilation semantics of a word. For
                   4471: example, by defining:
1.1       anton    4472: @example
1.26      crook    4473: :noname
                   4474:    foo bar ;
                   4475: :noname
                   4476:    POSTPONE foo POSTPONE bar ;
1.29      crook    4477: interpret/compile: opti-foobar
1.1       anton    4478: @end example
1.26      crook    4479: 
1.23      crook    4480: @noindent
1.26      crook    4481: as an optimizing version of:
                   4482: 
1.1       anton    4483: @example
1.26      crook    4484: : foobar
                   4485:     foo bar ;
1.1       anton    4486: @end example
                   4487: 
1.26      crook    4488: Unfortunately, this does not work correctly with @code{[compile]},
                   4489: because @code{[compile]} assumes that the compilation semantics of all
                   4490: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    4491: opti-foobar} would compile compilation semantics, whereas
                   4492: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    4493: 
1.26      crook    4494: @cindex state-smart words (are a bad idea)
1.29      crook    4495: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    4496: by @code{interpret/compile:} (words are state-smart if they check
                   4497: @code{STATE} during execution). E.g., they would try to code
                   4498: @code{foobar} like this:
1.1       anton    4499: 
1.26      crook    4500: @example
                   4501: : foobar
                   4502:   STATE @@
                   4503:   IF ( compilation state )
                   4504:     POSTPONE foo POSTPONE bar
                   4505:   ELSE
                   4506:     foo bar
                   4507:   ENDIF ; immediate
                   4508: @end example
1.1       anton    4509: 
1.26      crook    4510: Although this works if @code{foobar} is only processed by the text
                   4511: interpreter, it does not work in other contexts (like @code{'} or
                   4512: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   4513: for a state-smart word, not for the interpretation semantics of the
                   4514: original @code{foobar}; when you execute this execution token (directly
                   4515: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   4516: state, the result will not be what you expected (i.e., it will not
                   4517: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   4518: write them@footnote{For a more detailed discussion of this topic, see
                   4519: @cite{@code{State}-smartness -- Why it is Evil and How to Exorcise it} by Anton
                   4520: Ertl; presented at EuroForth '98 and available from
1.33      anton    4521: @url{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz}}!
1.1       anton    4522: 
1.26      crook    4523: @cindex defining words with arbitrary semantics combinations
                   4524: It is also possible to write defining words that define words with
                   4525: arbitrary combinations of interpretation and compilation semantics. In
                   4526: general, they look like this:
1.1       anton    4527: 
1.26      crook    4528: @example
                   4529: : def-word
                   4530:     create-interpret/compile
1.29      crook    4531:     @i{code1}
1.26      crook    4532: interpretation>
1.29      crook    4533:     @i{code2}
1.26      crook    4534: <interpretation
                   4535: compilation>
1.29      crook    4536:     @i{code3}
1.26      crook    4537: <compilation ;
                   4538: @end example
1.1       anton    4539: 
1.29      crook    4540: For a @i{word} defined with @code{def-word}, the interpretation
                   4541: semantics are to push the address of the body of @i{word} and perform
                   4542: @i{code2}, and the compilation semantics are to push the address of
                   4543: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    4544: can also be defined like this (except that the defined constants don't
                   4545: behave correctly when @code{[compile]}d):
1.1       anton    4546: 
1.26      crook    4547: @example
                   4548: : constant ( n "name" -- )
                   4549:     create-interpret/compile
                   4550:     ,
                   4551: interpretation> ( -- n )
                   4552:     @@
                   4553: <interpretation
                   4554: compilation> ( compilation. -- ; run-time. -- n )
                   4555:     @@ postpone literal
                   4556: <compilation ;
                   4557: @end example
1.1       anton    4558: 
1.26      crook    4559: doc-create-interpret/compile
                   4560: doc-interpretation>
                   4561: doc-<interpretation
                   4562: doc-compilation>
                   4563: doc-<compilation
1.1       anton    4564: 
1.29      crook    4565: Words defined with @code{interpret/compile:} and
1.26      crook    4566: @code{create-interpret/compile} have an extended header structure that
                   4567: differs from other words; however, unless you try to access them with
                   4568: plain address arithmetic, you should not notice this. Words for
                   4569: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    4570: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   4571: with @code{create-interpret/compile}.
1.1       anton    4572: 
1.27      crook    4573: doc-postpone
1.29      crook    4574: @comment TODO -- expand glossary text for POSTPONE
1.27      crook    4575: 
1.26      crook    4576: @c ----------------------------------------------------------
                   4577: @node The Text Interpreter, Tokens for Words, Defining Words, Words
                   4578: @section  The Text Interpreter
                   4579: @cindex interpreter - outer
                   4580: @cindex text interpreter
                   4581: @cindex outer interpreter
1.1       anton    4582: 
1.34      anton    4583: @c Should we really describe all these ugly details?  IMO the text
                   4584: @c interpreter should be much cleaner, but that may not be possible within
                   4585: @c ANS Forth. - anton
                   4586: 
1.29      crook    4587: The text interpreter@footnote{This is an expanded version of the
                   4588: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    4589: that processes input from the current input device. It is also called
                   4590: the outer interpreter, in contrast to the inner interpreter
                   4591: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   4592: implementations.
1.27      crook    4593: 
1.29      crook    4594: @cindex interpret state
                   4595: @cindex compile state
                   4596: The text interpreter operates in one of two states: @dfn{interpret
                   4597: state} and @dfn{compile state}. The current state is defined by the
                   4598: aptly-named variable, @code{state}.
                   4599: 
                   4600: This section starts by describing how the text interpreter behaves when
                   4601: it is in interpret state, processing input from the user input device --
                   4602: the keyboard. This is the mode that a Forth system is in after it starts
                   4603: up.
                   4604: 
                   4605: @cindex input buffer
                   4606: @cindex terminal input buffer
                   4607: The text interpreter works from an area of memory called the @dfn{input
                   4608: buffer}@footnote{When the text interpreter is processing input from the
                   4609: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   4610: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   4611: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    4612: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    4613: leading spaces (called @dfn{delimiters}) then parses a string (a
                   4614: sequence of non-space characters) until it reaches either a space
                   4615: character or the end of the buffer. Having parsed a string, it makes two
                   4616: attempts to process it:
1.27      crook    4617: 
1.29      crook    4618: @cindex dictionary
1.27      crook    4619: @itemize @bullet
                   4620: @item
1.29      crook    4621: It looks for the string in a @dfn{dictionary} of definitions. If the
                   4622: string is found, the string names a @dfn{definition} (also known as a
                   4623: @dfn{word}) and the dictionary search returns information that allows
                   4624: the text interpreter to perform the word's @dfn{interpretation
                   4625: semantics}. In most cases, this simply means that the word will be
                   4626: executed.
1.27      crook    4627: @item
                   4628: If the string is not found in the dictionary, the text interpreter
1.29      crook    4629: attempts to treat it as a number, using the rules described in
                   4630: @ref{Number Conversion}. If the string represents a legal number in the
                   4631: current radix, the number is pushed onto a parameter stack (the data
                   4632: stack for integers, the floating-point stack for floating-point
                   4633: numbers).
                   4634: @end itemize
                   4635: 
                   4636: If both attempts fail, or if the word is found in the dictionary but has
                   4637: no interpretation semantics@footnote{This happens if the word was
                   4638: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   4639: remainder of the input buffer, issues an error message and waits for
                   4640: more input. If one of the attempts succeeds, the text interpreter
                   4641: repeats the parsing process until the whole of the input buffer has been
                   4642: processed, at which point it prints the status message ``@code{ ok}''
                   4643: and waits for more input.
                   4644: 
                   4645: @cindex parse area
                   4646: The text interpreter keeps track of its position in the input buffer by
                   4647: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   4648: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   4649: of the input buffer. The region from offset @code{>IN @@} to the end of
                   4650: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   4651: the text interpreter processes the contents of the input buffer by
                   4652: parsing strings from the parse area until the parse area is empty.}.
                   4653: This example shows how @code{>IN} changes as the text interpreter parses
                   4654: the input buffer:
                   4655: 
                   4656: @example
                   4657: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   4658:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   4659: 
                   4660: 1 2 3 remaining + remaining . 
                   4661: 
                   4662: : foo 1 2 3 remaining SWAP remaining ;
                   4663: @end example
                   4664: 
                   4665: @noindent
                   4666: The result is:
                   4667: 
                   4668: @example
                   4669: ->+ remaining .<-
                   4670: ->.<-5  ok
                   4671: 
                   4672: ->SWAP remaining ;-<
                   4673: ->;<-  ok
                   4674: @end example
                   4675: 
                   4676: @cindex parsing words
                   4677: The value of @code{>IN} can also be modified by a word in the input
                   4678: buffer that is executed by the text interpreter.  This means that a word
                   4679: can ``trick'' the text interpreter into either skipping a section of the
                   4680: input buffer@footnote{This is how parsing words work.} or into parsing a
                   4681: section twice. For example:
1.27      crook    4682: 
1.29      crook    4683: @example
                   4684: : lat ." <<lat>>" ;
                   4685: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
                   4686: @end example
                   4687: 
                   4688: @noindent
                   4689: When @code{flat} is executed, this output is produced@footnote{Exercise
                   4690: for the reader: what would happen if the @code{3} were replaced with
                   4691: @code{4}?}:
                   4692: 
                   4693: @example
                   4694: <<flat>><<lat>>
                   4695: @end example
                   4696: 
                   4697: @noindent
                   4698: Two important notes about the behaviour of the text interpreter:
1.27      crook    4699: 
                   4700: @itemize @bullet
                   4701: @item
                   4702: It processes each input string to completion before parsing additional
1.29      crook    4703: characters from the input buffer.
                   4704: @item
                   4705: It treats the input buffer as a read-only region (and so must your code).
                   4706: @end itemize
                   4707: 
                   4708: @noindent
                   4709: When the text interpreter is in compile state, its behaviour changes in
                   4710: these ways:
                   4711: 
                   4712: @itemize @bullet
                   4713: @item
                   4714: If a parsed string is found in the dictionary, the text interpreter will
                   4715: perform the word's @dfn{compilation semantics}. In most cases, this
                   4716: simply means that the execution semantics of the word will be appended
                   4717: to the current definition.
1.27      crook    4718: @item
1.29      crook    4719: When a number is encountered, it is compiled into the current definition
                   4720: (as a literal) rather than being pushed onto a parameter stack.
                   4721: @item
                   4722: If an error occurs, @code{state} is modified to put the text interpreter
                   4723: back into interpret state.
                   4724: @item
                   4725: Each time a line is entered from the keyboard, Gforth prints
                   4726: ``@code{ compiled}'' rather than `` @code{ok}''.
                   4727: @end itemize
                   4728: 
                   4729: @cindex text interpreter - input sources
                   4730: When the text interpreter is using an input device other than the
                   4731: keyboard, its behaviour changes in these ways:
                   4732: 
                   4733: @itemize @bullet
                   4734: @item
                   4735: When the parse area is empty, the text interpreter attempts to refill
                   4736: the input buffer from the input source. When the input source is
                   4737: exhausted, the input source is set back to the user input device.
                   4738: @item
                   4739: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   4740: time the parse area is emptied.
                   4741: @item
                   4742: If an error occurs, the input source is set back to the user input
                   4743: device.
1.27      crook    4744: @end itemize
1.21      crook    4745: 
1.29      crook    4746: @ref{Input Sources} describes this in more detail.
                   4747: 
1.26      crook    4748: doc->in
1.27      crook    4749: doc-source
                   4750: 
1.26      crook    4751: doc-tib
                   4752: doc-#tib
1.1       anton    4753: 
1.26      crook    4754: @menu
1.29      crook    4755: * Input Sources::
1.26      crook    4756: * Number Conversion::
                   4757: * Interpret/Compile states::
                   4758: * Literals::
                   4759: * Interpreter Directives::
                   4760: @end menu
1.1       anton    4761: 
1.29      crook    4762: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   4763: @subsection Input Sources
                   4764: @cindex input sources
                   4765: @cindex text interpreter - input sources
                   4766: 
                   4767: By default, the text interpreter accepts input from the user input
                   4768: device (the keyboard) when Forth starts up. The text interpreter can
                   4769: process input from any of these sources:
                   4770: 
                   4771: @itemize @bullet
                   4772: @item
                   4773: The user input device -- the keyboard.
                   4774: @item
                   4775: A file, using the words described in @ref{Forth source files}.
                   4776: @item
                   4777: A block, using the words described in @ref{Blocks}.
                   4778: @item
                   4779: A text string, using @code{evaluate}.
                   4780: @end itemize
                   4781: 
                   4782: A program can identify the current input device from the values of
                   4783: @code{source-id} and @code{blk}.
                   4784: 
                   4785: doc-source-id
                   4786: doc-blk
                   4787: 
                   4788: doc-save-input
                   4789: doc-restore-input
                   4790: 
                   4791: doc-evaluate
1.1       anton    4792: 
1.29      crook    4793: 
                   4794: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    4795: @subsection Number Conversion
                   4796: @cindex number conversion
                   4797: @cindex double-cell numbers, input format
                   4798: @cindex input format for double-cell numbers
                   4799: @cindex single-cell numbers, input format
                   4800: @cindex input format for single-cell numbers
                   4801: @cindex floating-point numbers, input format
                   4802: @cindex input format for floating-point numbers
1.1       anton    4803: 
1.29      crook    4804: This section describes the rules that the text interpreter uses when it
                   4805: tries to convert a string into a number.
1.1       anton    4806: 
1.26      crook    4807: Let <digit> represent any character that is a legal digit in the current
1.29      crook    4808: number base@footnote{For example, 0-9 when the number base is decimal or
                   4809: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    4810: 
1.26      crook    4811: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    4812: 
1.29      crook    4813: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   4814: in the braces (@i{a} or @i{b} or neither).
1.1       anton    4815: 
1.26      crook    4816: Let * represent any number of instances of the previous character
                   4817: (including none).
1.1       anton    4818: 
1.26      crook    4819: Let any other character represent itself.
1.1       anton    4820: 
1.29      crook    4821: @noindent
1.26      crook    4822: Now, the conversion rules are:
1.21      crook    4823: 
1.26      crook    4824: @itemize @bullet
                   4825: @item
                   4826: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    4827: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    4828: @item
                   4829: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    4830: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    4831: arithmetic. Examples are -45 -5681 -0
                   4832: @item
                   4833: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    4834: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   4835: (all three of these represent the same number).
1.26      crook    4836: @item
                   4837: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    4838: double-precision (double-cell-sized) negative integer, and is
1.26      crook    4839: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    4840: -34.65 (all three of these represent the same number).
1.26      crook    4841: @item
1.29      crook    4842: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   4843: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    4844: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    4845: number) +12.E-4
1.26      crook    4846: @end itemize
1.1       anton    4847: 
1.26      crook    4848: By default, the number base used for integer number conversion is given
1.35      anton    4849: by the contents of the variable @code{base}.  Note that a lot of
                   4850: confusion can result from unexpected values of @code{base}.  If you
                   4851: change @code{base} anywhere, make sure to save the old value and restore
                   4852: it afterwards.  In general I recommend keeping @code{base} decimal, and
                   4853: using the prefixes described below for the popular non-decimal bases.
1.1       anton    4854: 
1.29      crook    4855: doc-dpl
1.26      crook    4856: doc-base
                   4857: doc-hex
                   4858: doc-decimal
1.1       anton    4859: 
1.26      crook    4860: @cindex '-prefix for character strings
                   4861: @cindex &-prefix for decimal numbers
                   4862: @cindex %-prefix for binary numbers
                   4863: @cindex $-prefix for hexadecimal numbers
1.35      anton    4864: Gforth allows you to override the value of @code{base} by using a
1.29      crook    4865: prefix@footnote{Some Forth implementations provide a similar scheme by
                   4866: implementing @code{$} etc. as parsing words that process the subsequent
                   4867: number in the input stream and push it onto the stack. For example, see
                   4868: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   4869: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   4870: is required between the prefix and the number.} before the first digit
                   4871: of an (integer) number. Four prefixes are supported:
1.1       anton    4872: 
1.26      crook    4873: @itemize @bullet
                   4874: @item
1.35      anton    4875: @code{&} -- decimal
1.26      crook    4876: @item
1.35      anton    4877: @code{%} -- binary
1.26      crook    4878: @item
1.35      anton    4879: @code{$} -- hexadecimal
1.26      crook    4880: @item
1.35      anton    4881: @code{'} -- base @code{max-char+1}
1.26      crook    4882: @end itemize
1.1       anton    4883: 
1.26      crook    4884: Here are some examples, with the equivalent decimal number shown after
                   4885: in braces:
1.1       anton    4886: 
1.26      crook    4887: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
                   4888: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
                   4889: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
                   4890: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    4891: 
1.26      crook    4892: @cindex number conversion - traps for the unwary
1.29      crook    4893: @noindent
1.26      crook    4894: Number conversion has a number of traps for the unwary:
1.1       anton    4895: 
1.26      crook    4896: @itemize @bullet
                   4897: @item
                   4898: You cannot determine the current number base using the code sequence
1.35      anton    4899: @code{base @@ .} -- the number base is always 10 in the current number
                   4900: base. Instead, use something like @code{base @@ dec.}
1.26      crook    4901: @item
                   4902: If the number base is set to a value greater than 14 (for example,
                   4903: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   4904: it to be intepreted as either a single-precision integer or a
                   4905: floating-point number (Gforth treats it as an integer). The ambiguity
                   4906: can be resolved by explicitly stating the sign of the mantissa and/or
                   4907: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   4908: ambiguity arises; either representation will be treated as a
                   4909: floating-point number.
                   4910: @item
1.29      crook    4911: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    4912: It is used to specify file types.
                   4913: @item
                   4914: ANS Forth requires the @code{.} of a double-precision number to
                   4915: be the final character in the string. Allowing the @code{.} to be
                   4916: anywhere after the first digit is a Gforth extension.
                   4917: @item
                   4918: The number conversion process does not check for overflow.
                   4919: @item
                   4920: In Gforth, number conversion to floating-point numbers always use base
1.35      anton    4921: 10, irrespective of the value of @code{base}. In ANS Forth,
1.26      crook    4922: conversion to floating-point numbers whilst the value of
1.35      anton    4923: @code{base} is not 10 is an ambiguous condition.
1.26      crook    4924: @end itemize
1.1       anton    4925: 
1.29      crook    4926: @ref{Input} describes words that you can use to read numbers into your
                   4927: programs.
1.1       anton    4928: 
1.26      crook    4929: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
                   4930: @subsection Interpret/Compile states
                   4931: @cindex Interpret/Compile states
1.1       anton    4932: 
1.29      crook    4933: A standard program is not permitted to change @code{state}
                   4934: explicitly. However, it can change @code{state} implicitly, using the
                   4935: words @code{[} and @code{]}. When @code{[} is executed it switches
                   4936: @code{state} to interpret state, and therefore the text interpreter
                   4937: starts interpreting. When @code{]} is executed it switches @code{state}
                   4938: to compile state and therefore the text interpreter starts
                   4939: compiling. The most common usage for these words is to compile literals,
                   4940: as shown in @ref{Literals}. However, they give you the freedom to switch
1.35      anton    4941: modes at will.
                   4942: 
                   4943: @c This is a bad example: It's non-standard, and it's not necessary.
                   4944: @c However, I can't think of a good example for switching into compile
                   4945: @c state when there is no current word (@code{state}-smart words are not a
                   4946: @c good reason).  So maybe we should use an example for switching into
                   4947: @c interpret @code{state} in a colon def. - anton
                   4948: 
                   4949: Here is an example of building a jump-table of execution
1.29      crook    4950: tokens:
                   4951: 
                   4952: @example
                   4953: : AA ." this is A" ;
                   4954: : BB ." this is B" ;
                   4955: : CC ." this is C" ;
                   4956: 
                   4957: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
                   4958: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   4959:   cells table + @ execute ;
                   4960: @end example
                   4961: 
                   4962: @noindent
                   4963: Now @code{0 go} will display ``@code{this is A}''. The table can be
                   4964: built far more neatly@footnote{The source code is neater.. what is
                   4965: compiled in memory in each case is identical.} like this:
                   4966: 
                   4967: @example
                   4968: create table ] aa bb cc [
                   4969: @end example
                   4970: 
                   4971: The problem with this code is that it is not portable; it will only work
                   4972: on systems where code space and data space co-incide. The reason is that
                   4973: both tables @i{compile} execution tokens -- into code space. The
                   4974: Standard only allows data space to be assigned for a @code{CREATE}d
                   4975: word. In addition, the Standard only allows @code{@@} to access data
                   4976: space, whilst this example is using it to access code space. The only
                   4977: portable, Standard way to build this table is to build it in data space,
                   4978: like this:
                   4979: 
                   4980: @example
                   4981: create table ' aa , ' bb , ' cc ,
                   4982: @end example
                   4983: 
                   4984: @noindent
                   4985: A similar technique can be used to build a table of constants:
                   4986: 
                   4987: @example
                   4988: create primes 1 , 3 , 5 , 7 , 11 ,
                   4989: @end example
1.1       anton    4990: 
1.26      crook    4991: doc-state
                   4992: doc-[
                   4993: doc-]
1.1       anton    4994: 
1.26      crook    4995: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
                   4996: @subsection Literals
                   4997: @cindex Literals
1.21      crook    4998: 
1.29      crook    4999: Often, you want to use a number within a colon definition. When you do
                   5000: this, the text interpreter automatically compiles the number as a
                   5001: @i{literal}. A literal is a number whose run-time effect is to be pushed
                   5002: onto the stack.  If you had to do some maths to generate the number, you
                   5003: might write it like this:
                   5004: 
                   5005: @example
                   5006: : HOUR-TO-SEC ( n1 -- n2 )
                   5007:   60 *      \ to minutes
                   5008:   60 * ;    \ to seconds
                   5009: @end example
                   5010: 
                   5011: It is very clear what this definition is doing, but it's inefficient
                   5012: since it is performing 2 multiples at run-time. An alternative would be
                   5013: to write:
                   5014: 
                   5015: @example
                   5016: : HOUR-TO-SEC ( n1 -- n2 )
                   5017:   3600 * ;  \ to seconds
                   5018: @end example
                   5019: 
                   5020: Which does the same thing, and has the advantage of using a single
                   5021: multiply. Ideally, we'd like the efficiency of the second with the
                   5022: readability of the first.
                   5023: 
                   5024: @code{Literal} allows us to achieve that. It takes a number from the
                   5025: stack and lays it down in the current definition just as though the
                   5026: number had been typed directly into the definition. Our first attempt
                   5027: might look like this:
                   5028: 
                   5029: @example
                   5030: 60          \ mins per hour
                   5031: 60 *        \ seconds per minute
                   5032: : HOUR-TO-SEC ( n1 -- n2 )
                   5033:   Literal * ;  \ to seconds
                   5034: @end example
                   5035: 
                   5036: But this produces the error message @code{unstructured}. What happened?
                   5037: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
                   5038: @i{colon-sys} is implementation-defined. In other words, once we start a
                   5039: colon definition we can't portably access anything that was on the stack
                   5040: before the definition began@footnote{@cite{Two Problems in ANS Forth},
                   5041: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
                   5042: some situations where you might want to access stack items above
                   5043: colon-sys, and provides a solution to the problem.}. The correct way of
                   5044: solving this problem in this instance is to use @code{[ ]} like this:
                   5045: 
                   5046: @example
                   5047: : HOUR-TO-SEC ( n1 -- n2 )
                   5048:   [ 60          \ minutes per hour
                   5049:     60 * ]      \ seconds per minute
                   5050:   LITERAL * ;   \ to seconds
                   5051: @end example
1.23      crook    5052: 
1.26      crook    5053: doc-literal
                   5054: doc-]L
                   5055: doc-2literal
                   5056: doc-fliteral
1.1       anton    5057: 
1.29      crook    5058: @node Interpreter Directives, , Literals, The Text Interpreter
1.26      crook    5059: @subsection Interpreter Directives
                   5060: @cindex interpreter directives
1.1       anton    5061: 
1.29      crook    5062: These words are usually used in interpret state; typically to control
                   5063: which parts of a source file are processed by the text
1.26      crook    5064: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   5065: supplements these with a rich set of immediate control structure words
                   5066: to compensate for the fact that the non-immediate versions can only be
1.29      crook    5067: used in compile state (@pxref{Control Structures}). Typical usages:
                   5068: 
                   5069: @example
                   5070: FALSE Constant ASSEMBLER
                   5071: .
                   5072: .
                   5073: ASSEMBLER [IF]
                   5074: : ASSEMBLER-FEATURE
                   5075:   ...
                   5076: ;
                   5077: [ENDIF]
                   5078: .
                   5079: .
                   5080: : SEE
                   5081:   ... \ general-purpose SEE code
                   5082:   [ ASSEMBLER [IF] ]
                   5083:   ... \ assembler-specific SEE code
                   5084:   [ [ENDIF] ]
                   5085: ;
                   5086: @end example
1.1       anton    5087: 
1.26      crook    5088: doc-[IF]
                   5089: doc-[ELSE]
                   5090: doc-[THEN]
                   5091: doc-[ENDIF]
1.1       anton    5092: 
1.26      crook    5093: doc-[IFDEF]
                   5094: doc-[IFUNDEF]
1.1       anton    5095: 
1.26      crook    5096: doc-[?DO]
                   5097: doc-[DO]
                   5098: doc-[FOR]
                   5099: doc-[LOOP]
                   5100: doc-[+LOOP]
                   5101: doc-[NEXT]
1.1       anton    5102: 
1.26      crook    5103: doc-[BEGIN]
                   5104: doc-[UNTIL]
                   5105: doc-[AGAIN]
                   5106: doc-[WHILE]
                   5107: doc-[REPEAT]
1.1       anton    5108: 
1.27      crook    5109: 
                   5110: 
1.26      crook    5111: @c -------------------------------------------------------------
                   5112: @node Tokens for Words, Word Lists, The Text Interpreter, Words
                   5113: @section Tokens for Words
                   5114: @cindex tokens for words
1.1       anton    5115: 
1.28      crook    5116: This section describes the creation and use of tokens that represent
1.29      crook    5117: words.
                   5118: 
1.32      anton    5119: Named words have information stored in their header space entries to
1.29      crook    5120: indicate any non-default semantics (@pxref{Interpretation and
                   5121: Compilation Semantics}). The semantics can be modified, using
                   5122: @code{immediate} and/or @code{compile-only}, at the time that the words
1.32      anton    5123: are defined. Unnamed words have (by definition) no header space
1.29      crook    5124: entry, and therefore must have default semantics.
1.21      crook    5125: 
1.26      crook    5126: Named words have interpretation and compilation semantics. Unnamed words
                   5127: just have execution semantics.
1.21      crook    5128: 
1.29      crook    5129: @cindex xt
                   5130: @cindex execution token
                   5131: The execution semantics of an unnamed word are represented by an
                   5132: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
                   5133: the execution token of the last word defined can be produced with
                   5134: @code{lastxt}.
                   5135: 
                   5136: The interpretation semantics of a named word are also represented by an
                   5137: execution token. You can produce the execution token using @code{'} or
                   5138: @code{[']}. A simple example shows the difference between the two:
1.21      crook    5139: 
1.29      crook    5140: @example
                   5141: : greet ( -- )   ." Hello" ;
1.36      anton    5142: : foo ( -- xt )  ['] greet execute ; \ ['] parses greet at compile-time
                   5143: : bar ( -- )     ' execute ; \  '  parses at run-time
1.1       anton    5144: 
1.29      crook    5145: \ the next four lines all do the same thing
1.36      anton    5146: foo
                   5147: bar greet
1.29      crook    5148: greet
                   5149: ' greet EXECUTE
                   5150: @end example
1.1       anton    5151: 
1.29      crook    5152: An execution token occupies one cell.
1.26      crook    5153: @cindex code field address
                   5154: @cindex CFA
1.29      crook    5155: In Gforth, the abstract data type @i{execution token} is implemented
1.26      crook    5156: as a code field address (CFA).
                   5157: @comment TODO note that the standard does not say what it represents..
                   5158: @comment and you cannot necessarily compile it in all Forths (eg native
                   5159: @comment compilers?).
1.1       anton    5160: 
1.29      crook    5161: For literals, use @code{'} in interpreted code and @code{[']} in
                   5162: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
                   5163: unusually by complaining about compile-only words. To get the execution
                   5164: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
                   5165: or @code{[COMP'] @i{name} DROP}.
1.1       anton    5166: 
1.26      crook    5167: @cindex compilation token
1.29      crook    5168: The compilation semantics of a named word are represented by a
                   5169: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   5170: @i{xt} is an execution token. The compilation semantics represented by
                   5171: the compilation token can be performed with @code{execute}, which
                   5172: consumes the whole compilation token, with an additional stack effect
                   5173: determined by the represented compilation semantics.
                   5174: 
                   5175: At present, the @i{w} part of a compilation token is an execution token,
                   5176: and the @i{xt} part represents either @code{execute} or
                   5177: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   5178: word. If the word has default compilation semantics, the @i{xt} will
1.36      anton    5179: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   5180: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   5181: knowledge, unless necessary; future versions of Gforth may introduce
                   5182: unusual compilation tokens (e.g., a compilation token that represents
                   5183: the compilation semantics of a literal).
1.1       anton    5184: 
1.26      crook    5185: You can compile the compilation semantics with @code{postpone,}. I.e.,
1.29      crook    5186: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
                   5187: @i{word}}.
1.21      crook    5188: 
1.26      crook    5189: @cindex name token
                   5190: @cindex name field address
                   5191: @cindex NFA
1.29      crook    5192: Named words are also represented by the @dfn{name token}, (@i{nt}). In
                   5193: Gforth, the abstract data type @emph{name token} is implemented as a
                   5194: name field address (NFA).
                   5195: 
                   5196: doc-execute
                   5197: doc-compile,
                   5198: doc-[']
                   5199: doc-'
                   5200: doc-[comp']
                   5201: doc-comp'
                   5202: doc-postpone,
1.1       anton    5203: 
1.26      crook    5204: doc-find-name
                   5205: doc-name>int
                   5206: doc-name?int
                   5207: doc-name>comp
                   5208: doc-name>string
1.1       anton    5209: 
1.26      crook    5210: @c -------------------------------------------------------------
                   5211: @node Word Lists, Environmental Queries, Tokens for Words, Words
                   5212: @section Word Lists
                   5213: @cindex word lists
1.32      anton    5214: @cindex header space
1.1       anton    5215: 
1.36      anton    5216: A wordlist is a list of named words; you can add new words and look up
                   5217: words by name (and you can remove words in a restricted way with
                   5218: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   5219: 
                   5220: @cindex search order stack
                   5221: The text interpreter searches the wordlists present in the search order
                   5222: (a stack of wordlists), from the top to the bottom.  Within each
                   5223: wordlist, the search starts conceptually at the newest word; i.e., if
                   5224: two words in a wordlist have the same name, the newer word is found.
1.1       anton    5225: 
1.26      crook    5226: @cindex compilation word list
1.36      anton    5227: New words are added to the @dfn{compilation wordlist} (aka current
                   5228: wordlist).
1.1       anton    5229: 
1.36      anton    5230: @cindex wid
                   5231: A word list is identified by a cell-sized word list identifier (@i{wid})
                   5232: in much the same way as a file is identified by a file handle. The
                   5233: numerical value of the wid has no (portable) meaning, and might change
                   5234: from session to session.
1.1       anton    5235: 
1.29      crook    5236: The ANS Forth ``Search order'' word set is intended to provide a set of
                   5237: low-level tools that allow various different schemes to be
1.26      crook    5238: implemented. Gforth provides @code{vocabulary}, a traditional Forth
                   5239: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
                   5240: Standard Forth.
1.1       anton    5241: 
1.27      crook    5242: @comment TODO: locals section refers to here, saying that every word list (aka
                   5243: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1       anton    5244: 
1.27      crook    5245: @comment the thisone- prefix is used to pick out the true definition of a
                   5246: @comment word from the source files, rather than some alias.
1.26      crook    5247: doc-forth-wordlist
                   5248: doc-definitions
                   5249: doc-get-current
                   5250: doc-set-current
                   5251: doc-get-order
1.27      crook    5252: doc---thisone-set-order
1.26      crook    5253: doc-wordlist
1.30      anton    5254: doc-table
1.36      anton    5255: doc-push-order
                   5256: doc-previous
1.26      crook    5257: doc-also
1.27      crook    5258: doc---thisone-forth
1.26      crook    5259: doc-only
1.27      crook    5260: doc---thisone-order
1.15      anton    5261: 
1.26      crook    5262: doc-find
                   5263: doc-search-wordlist
1.15      anton    5264: 
1.26      crook    5265: doc-words
                   5266: doc-vlist
1.1       anton    5267: 
1.26      crook    5268: doc-mappedwordlist
                   5269: doc-root
                   5270: doc-vocabulary
                   5271: doc-seal
                   5272: doc-vocs
                   5273: doc-current
                   5274: doc-context
1.1       anton    5275: 
1.26      crook    5276: @menu
                   5277: * Why use word lists?::
                   5278: * Word list examples::
                   5279: @end menu
                   5280: 
                   5281: @node Why use word lists?, Word list examples, Word Lists, Word Lists
                   5282: @subsection Why use word lists?
                   5283: @cindex word lists - why use them?
                   5284: 
1.29      crook    5285: Here are some reasons for using multiple word lists:
1.26      crook    5286: 
                   5287: @itemize @bullet
                   5288: @item
1.32      anton    5289: To improve compilation speed by reducing the number of header space
1.26      crook    5290: entries that must be searched. This is achieved by creating a new
                   5291: word list that contains all of the definitions that are used in the
                   5292: definition of a Forth system but which would not usually be used by
                   5293: programs running on that system. That word list would be on the search
                   5294: list when the Forth system was compiled but would be removed from the
                   5295: search list for normal operation. This can be a useful technique for
                   5296: low-performance systems (for example, 8-bit processors in embedded
                   5297: systems) but is unlikely to be necessary in high-performance desktop
                   5298: systems.
                   5299: @item
                   5300: To prevent a set of words from being used outside the context in which
                   5301: they are valid. Two classic examples of this are an integrated editor
                   5302: (all of the edit commands are defined in a separate word list; the
                   5303: search order is set to the editor word list when the editor is invoked;
                   5304: the old search order is restored when the editor is terminated) and an
                   5305: integrated assembler (the op-codes for the machine are defined in a
                   5306: separate word list which is used when a @code{CODE} word is defined).
                   5307: @item
                   5308: To prevent a name-space clash between multiple definitions with the same
                   5309: name. For example, when building a cross-compiler you might have a word
                   5310: @code{IF} that generates conditional code for your target system. By
                   5311: placing this definition in a different word list you can control whether
                   5312: the host system's @code{IF} or the target system's @code{IF} get used in
                   5313: any particular context by controlling the order of the word lists on the
                   5314: search order stack.
                   5315: @end itemize
1.1       anton    5316: 
1.26      crook    5317: @node Word list examples, ,Why use word lists?, Word Lists
                   5318: @subsection Word list examples
                   5319: @cindex word lists - examples
1.1       anton    5320: 
1.26      crook    5321: Here is an example of creating and using a new wordlist using ANS
                   5322: Forth Standard words:
1.1       anton    5323: 
                   5324: @example
1.26      crook    5325: wordlist constant my-new-words-wordlist
                   5326: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21      crook    5327: 
1.26      crook    5328: \ add it to the search order
                   5329: also my-new-words
1.21      crook    5330: 
1.26      crook    5331: \ alternatively, add it to the search order and make it
                   5332: \ the compilation word list
                   5333: also my-new-words definitions
                   5334: \ type "order" to see the problem
1.21      crook    5335: @end example
                   5336: 
1.26      crook    5337: The problem with this example is that @code{order} has no way to
                   5338: associate the name @code{my-new-words} with the wid of the word list (in
                   5339: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   5340: that has no associated name). There is no Standard way of associating a
                   5341: name with a wid.
                   5342: 
                   5343: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   5344: associates a name with a wid:
1.21      crook    5345: 
1.26      crook    5346: @example
                   5347: vocabulary my-new-words
1.21      crook    5348: 
1.26      crook    5349: \ add it to the search order
                   5350: my-new-words
1.21      crook    5351: 
1.26      crook    5352: \ alternatively, add it to the search order and make it
                   5353: \ the compilation word list
                   5354: my-new-words definitions
                   5355: \ type "order" to see that the problem is solved
                   5356: @end example
1.23      crook    5357: 
1.26      crook    5358: @c -------------------------------------------------------------
                   5359: @node Environmental Queries, Files, Word Lists, Words
                   5360: @section Environmental Queries
                   5361: @cindex environmental queries
1.21      crook    5362: 
1.26      crook    5363: ANS Forth introduced the idea of ``environmental queries'' as a way
                   5364: for a program running on a system to determine certain characteristics of the system.
                   5365: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    5366: 
1.32      anton    5367: The Standard requires that the header space used for environmental queries
                   5368: be distinct from the header space used for definitions.
1.21      crook    5369: 
1.26      crook    5370: Typically, environmental queries are supported by creating a set of
1.29      crook    5371: definitions in a word list that is @i{only} used during environmental
1.26      crook    5372: queries; that is what Gforth does. There is no Standard way of adding
                   5373: definitions to the set of recognised environmental queries, but any
                   5374: implementation that supports the loading of optional word sets must have
                   5375: some mechanism for doing this (after loading the word set, the
                   5376: associated environmental query string must return @code{true}). In
                   5377: Gforth, the word list used to honour environmental queries can be
                   5378: manipulated just like any other word list.
1.21      crook    5379: 
1.26      crook    5380: doc-environment?
                   5381: doc-environment-wordlist
1.21      crook    5382: 
1.26      crook    5383: doc-gforth
                   5384: doc-os-class
1.21      crook    5385: 
1.26      crook    5386: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   5387: returning two items on the stack, querying it using @code{environment?}
                   5388: will return an additional item; the @code{true} flag that shows that the
                   5389: string was recognised.
1.21      crook    5390: 
1.26      crook    5391: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    5392: 
1.26      crook    5393: Here are some examples of using environmental queries:
1.21      crook    5394: 
1.26      crook    5395: @example
                   5396: s" address-unit-bits" environment? 0=
                   5397: [IF]
                   5398:      cr .( environmental attribute address-units-bits unknown... ) cr
                   5399: [THEN]
1.21      crook    5400: 
1.26      crook    5401: s" block" environment? [IF] DROP include block.fs [THEN]
1.21      crook    5402: 
1.26      crook    5403: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21      crook    5404: 
1.26      crook    5405: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   5406:                         [ELSE] .( Not Gforth..) [THEN]
                   5407: @end example
1.21      crook    5408: 
                   5409: 
1.26      crook    5410: Here is an example of adding a definition to the environment word list:
1.21      crook    5411: 
1.26      crook    5412: @example
                   5413: get-current environment-wordlist set-current
                   5414: true constant block
                   5415: true constant block-ext
                   5416: set-current
                   5417: @end example
1.21      crook    5418: 
1.26      crook    5419: You can see what definitions are in the environment word list like this:
1.21      crook    5420: 
1.26      crook    5421: @example
                   5422: get-order 1+ environment-wordlist swap set-order words previous
                   5423: @end example
1.21      crook    5424: 
                   5425: 
1.26      crook    5426: @c -------------------------------------------------------------
                   5427: @node Files, Blocks, Environmental Queries, Words
                   5428: @section Files
1.28      crook    5429: @cindex files
                   5430: @cindex I/O - file-handling
1.21      crook    5431: 
1.26      crook    5432: Gforth provides facilities for accessing files that are stored in the
                   5433: host operating system's file-system. Files that are processed by Gforth
                   5434: can be divided into two categories:
1.21      crook    5435: 
1.23      crook    5436: @itemize @bullet
                   5437: @item
1.29      crook    5438: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    5439: @item
1.29      crook    5440: Files that are processed by some other program (@dfn{general files}).
1.26      crook    5441: @end itemize
                   5442: 
                   5443: @menu
                   5444: * Forth source files::
                   5445: * General files::         
                   5446: * Search Paths::                 
                   5447: * Forth Search Paths::    
                   5448: * General Search Paths::        
                   5449: @end menu
                   5450: 
1.21      crook    5451: 
1.26      crook    5452: @c -------------------------------------------------------------
                   5453: @node Forth source files, General files, Files, Files
                   5454: @subsection Forth source files
                   5455: @cindex including files
                   5456: @cindex Forth source files
1.21      crook    5457: 
1.26      crook    5458: The simplest way to interpret the contents of a file is to use one of
                   5459: these two formats:
1.21      crook    5460: 
1.26      crook    5461: @example
                   5462: include mysource.fs
                   5463: s" mysource.fs" included
                   5464: @end example
1.21      crook    5465: 
1.26      crook    5466: Sometimes you want to include a file only if it is not included already
                   5467: (by, say, another source file). In that case, you can use one of these
                   5468: fomats:
1.21      crook    5469: 
1.26      crook    5470: @example
                   5471: require mysource.fs
                   5472: needs mysource.fs
                   5473: s" mysource.fs" required
                   5474: @end example
1.21      crook    5475: 
1.26      crook    5476: @cindex stack effect of included files
                   5477: @cindex including files, stack effect
                   5478: I recommend that you write your source files such that interpreting them
                   5479: does not change the stack. This allows using these files with
                   5480: @code{required} and friends without complications. For example:
1.21      crook    5481: 
1.26      crook    5482: @example
                   5483: 1 require foo.fs drop
                   5484: @end example
1.21      crook    5485: 
1.26      crook    5486: doc-include-file
                   5487: doc-included
1.28      crook    5488: doc-included?
1.26      crook    5489: doc-include
                   5490: doc-required
                   5491: doc-require
                   5492: doc-needs
1.28      crook    5493: doc-init-included-files
1.21      crook    5494: 
1.26      crook    5495: A definition in ANS Forth for @code{required} is provided in
                   5496: @file{compat/required.fs}.
1.21      crook    5497: 
1.26      crook    5498: @c -------------------------------------------------------------
                   5499: @node General files, Search Paths, Forth source files, Files
                   5500: @subsection General files
                   5501: @cindex general files
                   5502: @cindex file-handling
1.21      crook    5503: 
1.26      crook    5504: Files are opened/created by name and type. The following types are
                   5505: recognised:
1.1       anton    5506: 
1.26      crook    5507: doc-r/o
                   5508: doc-r/w
                   5509: doc-w/o
                   5510: doc-bin
1.1       anton    5511: 
1.26      crook    5512: When a file is opened/created, it returns a file identifier,
1.29      crook    5513: @i{wfileid} that is used for all other file commands. All file
                   5514: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    5515: successful operation and an implementation-defined non-zero value in the
                   5516: case of an error.
1.21      crook    5517: 
1.26      crook    5518: doc-open-file
                   5519: doc-create-file
1.21      crook    5520: 
1.26      crook    5521: doc-close-file
                   5522: doc-delete-file
                   5523: doc-rename-file
                   5524: doc-read-file
                   5525: doc-read-line
                   5526: doc-write-file
                   5527: doc-write-line
                   5528: doc-emit-file
                   5529: doc-flush-file
1.21      crook    5530: 
1.26      crook    5531: doc-file-status
                   5532: doc-file-position
                   5533: doc-reposition-file
                   5534: doc-file-size
                   5535: doc-resize-file
1.21      crook    5536: 
1.26      crook    5537: @c ---------------------------------------------------------
                   5538: @node Search Paths, Forth Search Paths, General files, Files
                   5539: @subsection Search Paths
                   5540: @cindex path for @code{included}
                   5541: @cindex file search path
                   5542: @cindex @code{include} search path
                   5543: @cindex search path for files
1.21      crook    5544: 
1.26      crook    5545: If you specify an absolute filename (i.e., a filename starting with
                   5546: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   5547: @samp{C:...})) for @code{included} and friends, that file is included
                   5548: just as you would expect.
1.21      crook    5549: 
1.26      crook    5550: For relative filenames, Gforth uses a search path similar to Forth's
                   5551: search order (@pxref{Word Lists}). It tries to find the given filename
                   5552: in the directories present in the path, and includes the first one it
                   5553: finds. There are separate search paths for Forth source files and
                   5554: general files.
1.21      crook    5555: 
1.26      crook    5556: If the search path contains the directory @file{.} (as it should), this
                   5557: refers to the directory that the present file was @code{included}
                   5558: from. This allows files to include other files relative to their own
                   5559: position (irrespective of the current working directory or the absolute
                   5560: position).  This feature is essential for libraries consisting of
                   5561: several files, where a file may include other files from the library.
                   5562: It corresponds to @code{#include "..."} in C. If the current input
                   5563: source is not a file, @file{.} refers to the directory of the innermost
                   5564: file being included, or, if there is no file being included, to the
                   5565: current working directory.
1.21      crook    5566: 
1.26      crook    5567: Use @file{~+} to refer to the current working directory (as in the
                   5568: @code{bash}).
1.1       anton    5569: 
1.26      crook    5570: If the filename starts with @file{./}, the search path is not searched
                   5571: (just as with absolute filenames), and the @file{.} has the same meaning
                   5572: as described above.
1.1       anton    5573: 
1.26      crook    5574: @c ---------------------------------------------------------
                   5575: @node Forth Search Paths, General Search Paths, Search Paths, Files
                   5576: @subsubsection Forth Search Paths
1.28      crook    5577: @cindex search path control - Forth
1.5       anton    5578: 
1.26      crook    5579: The search path is initialized when you start Gforth (@pxref{Invoking
                   5580: Gforth}). You can display it and change it using these words:
1.5       anton    5581: 
1.26      crook    5582: doc-.fpath
                   5583: doc-fpath+
                   5584: doc-fpath=
                   5585: doc-open-fpath-file
1.5       anton    5586: 
1.26      crook    5587: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    5588: 
1.26      crook    5589: @example
                   5590: fpath= /usr/lib/forth/|./
                   5591: require timer.fs
                   5592: @end example
1.5       anton    5593: 
1.26      crook    5594: @c ---------------------------------------------------------
                   5595: @node General Search Paths,  , Forth Search Paths, Files
                   5596: @subsubsection General Search Paths
                   5597: @cindex search path control - for user applications
1.5       anton    5598: 
1.26      crook    5599: Your application may need to search files in several directories, like
                   5600: @code{included} does. To facilitate this, Gforth allows you to define
                   5601: and use your own search paths, by providing generic equivalents of the
                   5602: Forth search path words:
1.5       anton    5603: 
1.26      crook    5604: doc-.path
                   5605: doc-path+
                   5606: doc-path=
                   5607: doc-open-path-file
1.5       anton    5608: 
1.26      crook    5609: Here's an example of creating a search path:
1.5       anton    5610: 
1.26      crook    5611: @example
                   5612: \ Make a buffer for the path:
                   5613: create mypath   100 chars ,     \ maximum length (is checked)
                   5614:                 0 ,             \ real len
                   5615:                 100 chars allot \ space for path
                   5616: @end example
1.5       anton    5617: 
1.26      crook    5618: @c -------------------------------------------------------------
                   5619: @node Blocks, Other I/O, Files, Words
                   5620: @section Blocks
1.28      crook    5621: @cindex I/O - blocks
                   5622: @cindex blocks
                   5623: 
                   5624: When you run Gforth on a modern desk-top computer, it runs under the
                   5625: control of an operating system which provides certain services.  One of
                   5626: these services is @var{file services}, which allows Forth source code
                   5627: and data to be stored in files and read into Gforth (@pxref{Files}).
                   5628: 
                   5629: Traditionally, Forth has been an important programming language on
                   5630: systems where it has interfaced directly to the underlying hardware with
                   5631: no intervening operating system. Forth provides a mechanism, called
1.29      crook    5632: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    5633: 
                   5634: A block is a 1024-byte data area, which can be used to hold data or
                   5635: Forth source code. No structure is imposed on the contents of the
                   5636: block. A block is identified by its number; blocks are numbered
                   5637: contiguously from 1 to an implementation-defined maximum.
                   5638: 
                   5639: A typical system that used blocks but no operating system might use a
                   5640: single floppy-disk drive for mass storage, with the disks formatted to
                   5641: provide 256-byte sectors. Blocks would be implemented by assigning the
                   5642: first four sectors of the disk to block 1, the second four sectors to
                   5643: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   5644: would not contain any file system information, just the set of blocks.
                   5645: 
1.29      crook    5646: @cindex blocks file
1.28      crook    5647: On systems that do provide file services, blocks are typically
1.29      crook    5648: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    5649: file}.  The size of the blocks file will be an exact multiple of 1024
                   5650: bytes, corresponding to the number of blocks it contains. This is the
                   5651: mechanism that Gforth uses.
                   5652: 
1.29      crook    5653: @cindex @file{blocks.fb}
1.28      crook    5654: Only 1 blocks file can be open at a time. If you use block words without
                   5655: having specified a blocks file, Gforth defaults to the blocks file
                   5656: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
                   5657: locate a blocks file (@pxref{Forth Search Paths}).
                   5658: 
1.29      crook    5659: @cindex block buffers
1.28      crook    5660: When you read and write blocks under program control, Gforth uses a
1.29      crook    5661: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    5662: not used when you use @code{load} to interpret the contents of a block.
                   5663: 
                   5664: The behaviour of the block buffers is directly analagous to that of a
                   5665: cache. Each block buffer has three states:
                   5666: 
                   5667: @itemize @bullet
                   5668: @item
                   5669: Unassigned
                   5670: @item
                   5671: Assigned-clean
                   5672: @item
                   5673: Assigned-dirty
                   5674: @end itemize
                   5675: 
1.29      crook    5676: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    5677: block, the block (specified by its block number) must be assigned to a
                   5678: block buffer.
                   5679: 
                   5680: The assignment of a block to a block buffer is performed by @code{block}
                   5681: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   5682: contents of a block. Use @code{buffer} when you don't care about the
                   5683: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    5684: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    5685: with the particular block is already stored in a block buffer due to an
                   5686: earlier @code{block} command, @code{buffer} will return that block
                   5687: buffer and the existing contents of the block will be
                   5688: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    5689: block buffer for the block.}.
1.28      crook    5690: 
                   5691: Once a block has been assigned to a block buffer, the block buffer state
1.29      crook    5692: becomes @i{assigned-clean}. Data can now be manipulated within the
1.28      crook    5693: block buffer.
                   5694: 
                   5695: When the contents of a block buffer is changed it is necessary,
                   5696: @i{before calling} @code{block} @i{or} @code{buffer} @i{again}, to
                   5697: either abandon the changes (by doing nothing) or commit the changes,
                   5698: using @code{update}. Using @code{update} does not change the blocks
1.29      crook    5699: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28      crook    5700: 
1.29      crook    5701: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28      crook    5702: written back to the blocks file on disk. Leaving Gforth using @code{bye}
                   5703: also causes a @code{flush} to be performed.
                   5704: 
1.29      crook    5705: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    5706: algorithm to assign a block buffer to a block. That means that any
                   5707: particular block can only be assigned to one specific block buffer,
1.29      crook    5708: called (for the particular operation) the @i{victim buffer}. If the
                   5709: victim buffer is @i{unassigned} or @i{assigned-clean} it can be
                   5710: allocated to the new block immediately. If it is @i{assigned-dirty}
1.28      crook    5711: its current contents must be written out to disk before it can be
                   5712: allocated to the new block.
                   5713: 
                   5714: Although no structure is imposed on the contents of a block, it is
                   5715: traditional to display the contents as 16 lines each of 64 characters.  A
                   5716: block provides a single, continuous stream of input (for example, it
                   5717: acts as a single parse area) -- there are no end-of-line characters
                   5718: within a block, and no end-of-file character at the end of a
                   5719: block. There are two consequences of this:
1.26      crook    5720: 
1.28      crook    5721: @itemize @bullet
                   5722: @item
                   5723: The last character of one line wraps straight into the first character
                   5724: of the following line
                   5725: @item
                   5726: The word @code{\} -- comment to end of line -- requires special
                   5727: treatment; in the context of a block it causes all characters until the
                   5728: end of the current 64-character ``line'' to be ignored.
                   5729: @end itemize
                   5730: 
                   5731: In Gforth, when you use @code{block} with a non-existent block number,
                   5732: the current block file will be extended to the appropriate size and the
                   5733: block buffer will be initialised with spaces.
                   5734: 
1.29      crook    5735: Gforth doesn't encourage the use of blocks; the mechanism is only
                   5736: provided for backward compatibility -- ANS Forth requires blocks to be
                   5737: available when files are.
1.28      crook    5738: 
                   5739: Common techniques that are used when working with blocks include:
                   5740: 
                   5741: @itemize @bullet
                   5742: @item
                   5743: A screen editor that allows you to edit blocks without leaving the Forth
                   5744: environment.
                   5745: @item
                   5746: Shadow screens; where every code block has an associated block
                   5747: containing comments (for example: code in odd block numbers, comments in
                   5748: even block numbers). Typically, the block editor provides a convenient
                   5749: mechanism to toggle between code and comments.
                   5750: @item
                   5751: Load blocks; a single block (typically block 1) contains a number of
                   5752: @code{thru} commands which @code{load} the whole of the application.
                   5753: @end itemize
1.26      crook    5754: 
1.29      crook    5755: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   5756: integrated into a Forth programming environment.
1.26      crook    5757: 
                   5758: @comment TODO what about errors on open-blocks?
                   5759: doc-open-blocks
                   5760: doc-use
                   5761: doc-get-block-fid
                   5762: doc-block-position
1.28      crook    5763: 
                   5764: doc-scr
                   5765: doc-list
                   5766: 
                   5767: doc---block-block
                   5768: doc-buffer
                   5769: 
1.26      crook    5770: doc-update
1.28      crook    5771: doc-updated?
1.26      crook    5772: doc-save-buffers
                   5773: doc-empty-buffers
                   5774: doc-empty-buffer
                   5775: doc-flush
1.28      crook    5776: 
1.26      crook    5777: doc-load
                   5778: doc-thru
                   5779: doc-+load
                   5780: doc-+thru
1.35      anton    5781: xdoc--gforth--->
1.26      crook    5782: doc-block-included
                   5783: 
                   5784: @c -------------------------------------------------------------
                   5785: @node Other I/O, Programming Tools, Blocks, Words
                   5786: @section Other I/O
1.28      crook    5787: @cindex I/O - keyboard and display
1.26      crook    5788: 
                   5789: @menu
                   5790: * Simple numeric output::       Predefined formats
                   5791: * Formatted numeric output::    Formatted (pictured) output
                   5792: * String Formats::              How Forth stores strings in memory
                   5793: * Displaying characters and strings:: Other stuff
                   5794: * Input::                       Input
                   5795: @end menu
                   5796: 
                   5797: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   5798: @subsection Simple numeric output
1.28      crook    5799: @cindex numeric output - simple/free-format
1.5       anton    5800: 
1.26      crook    5801: The simplest output functions are those that display numbers from the
                   5802: data or floating-point stacks. Floating-point output is always displayed
                   5803: using base 10. Numbers displayed from the data stack use the value stored
                   5804: in @code{base}.
1.5       anton    5805: 
1.26      crook    5806: doc-.
                   5807: doc-dec.
                   5808: doc-hex.
                   5809: doc-u.
                   5810: doc-.r
                   5811: doc-u.r
                   5812: doc-d.
                   5813: doc-ud.
                   5814: doc-d.r
                   5815: doc-ud.r
                   5816: doc-f.
                   5817: doc-fe.
                   5818: doc-fs.
1.5       anton    5819: 
1.26      crook    5820: Examples of printing the number 1234.5678E23 in the different floating-point output
                   5821: formats are shown below:
1.5       anton    5822: 
                   5823: @example
1.26      crook    5824: f. 123456779999999000000000000.
                   5825: fe. 123.456779999999E24
                   5826: fs. 1.23456779999999E26
1.5       anton    5827: @end example
                   5828: 
                   5829: 
1.26      crook    5830: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   5831: @subsection Formatted numeric output
1.28      crook    5832: @cindex formatted numeric output
1.26      crook    5833: @cindex pictured numeric output
1.28      crook    5834: @cindex numeric output - formatted
1.26      crook    5835: 
1.29      crook    5836: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    5837: output} for formatted printing of integers.  In this technique, digits
                   5838: are extracted from the number (using the current output radix defined by
                   5839: @code{base}), converted to ASCII codes and appended to a string that is
                   5840: built in a scratch-pad area of memory (@pxref{core-idef,
                   5841: Implementation-defined options, Implementation-defined
                   5842: options}). Arbitrary characters can be appended to the string during the
                   5843: extraction process. The completed string is specified by an address
                   5844: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   5845: under program control.
1.5       anton    5846: 
1.26      crook    5847: All of the words described in the previous section for simple numeric
                   5848: output are implemented in Gforth using pictured numeric output.
1.5       anton    5849: 
1.26      crook    5850: Three important things to remember about Pictured Numeric Output:
1.5       anton    5851: 
1.26      crook    5852: @itemize @bullet
                   5853: @item
1.28      crook    5854: It always operates on double-precision numbers; to display a
                   5855: single-precision number, convert it first (@pxref{Double precision} for
                   5856: ways of doing this).
1.26      crook    5857: @item
1.28      crook    5858: It always treats the double-precision number as though it were
                   5859: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    5860: @item
                   5861: The string is built up from right to left; least significant digit first.
                   5862: @end itemize
1.5       anton    5863: 
1.26      crook    5864: doc-<#
                   5865: doc-#
                   5866: doc-#s
                   5867: doc-hold
                   5868: doc-sign
                   5869: doc-#>
1.5       anton    5870: 
1.26      crook    5871: doc-represent
1.5       anton    5872: 
1.26      crook    5873: Here are some examples of using pictured numeric output:
1.5       anton    5874: 
                   5875: @example
1.26      crook    5876: : my-u. ( u -- )
                   5877:   \ Simplest use of pns.. behaves like Standard u. 
                   5878:   0              \ convert to unsigned double
                   5879:   <#             \ start conversion
                   5880:   #s             \ convert all digits
                   5881:   #>             \ complete conversion
                   5882:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5883: 
1.26      crook    5884: : cents-only ( u -- )
                   5885:   0              \ convert to unsigned double
                   5886:   <#             \ start conversion
                   5887:   # #            \ convert two least-significant digits
                   5888:   #>             \ complete conversion, discard other digits
                   5889:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5890: 
1.26      crook    5891: : dollars-and-cents ( u -- )
                   5892:   0              \ convert to unsigned double
                   5893:   <#             \ start conversion
                   5894:   # #            \ convert two least-significant digits
                   5895:   [char] . hold  \ insert decimal point
                   5896:   #s             \ convert remaining digits
                   5897:   [char] $ hold  \ append currency symbol
                   5898:   #>             \ complete conversion
                   5899:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5900: 
1.26      crook    5901: : my-. ( n -- )
                   5902:   \ handling negatives.. behaves like Standard .
                   5903:   s>d            \ convert to signed double
                   5904:   swap over dabs \ leave sign byte followed by unsigned double
                   5905:   <#             \ start conversion
                   5906:   #s             \ convert all digits
                   5907:   rot sign       \ get at sign byte, append "-" if needed
                   5908:   #>             \ complete conversion
                   5909:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5910: 
1.26      crook    5911: : account. ( n -- )
                   5912:   \ accountants don't like minus signs, they use braces
                   5913:   \ for negative numbers
                   5914:   s>d            \ convert to signed double
                   5915:   swap over dabs \ leave sign byte followed by unsigned double
                   5916:   <#             \ start conversion
                   5917:   2 pick         \ get copy of sign byte
                   5918:   0< IF [char] ) hold THEN \ right-most character of output
                   5919:   #s             \ convert all digits
                   5920:   rot            \ get at sign byte
                   5921:   0< IF [char] ( hold THEN
                   5922:   #>             \ complete conversion
                   5923:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    5924: @end example
                   5925: 
1.26      crook    5926: Here are some examples of using these words:
1.5       anton    5927: 
                   5928: @example
1.26      crook    5929: 1 my-u. 1
                   5930: hex -1 my-u. decimal FFFFFFFF
                   5931: 1 cents-only 01
                   5932: 1234 cents-only 34
                   5933: 2 dollars-and-cents $0.02
                   5934: 1234 dollars-and-cents $12.34
                   5935: 123 my-. 123
                   5936: -123 my. -123
                   5937: 123 account. 123
                   5938: -456 account. (456)
1.5       anton    5939: @end example
                   5940: 
                   5941: 
1.26      crook    5942: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   5943: @subsection String Formats
1.27      crook    5944: @cindex strings - see character strings
                   5945: @cindex character strings - formats
1.28      crook    5946: @cindex I/O - see character strings
1.26      crook    5947: 
1.27      crook    5948: Forth commonly uses two different methods for representing character
                   5949: strings:
1.26      crook    5950: 
                   5951: @itemize @bullet
                   5952: @item
                   5953: @cindex address of counted string
1.29      crook    5954: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   5955: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   5956: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    5957: memory.
                   5958: @item
1.29      crook    5959: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   5960: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    5961: first byte of the string.
                   5962: @end itemize
                   5963: 
                   5964: ANS Forth encourages the use of the second format when representing
                   5965: strings on the stack, whilst conceeding that the counted string format
                   5966: remains useful as a way of storing strings in memory.
                   5967: 
                   5968: doc-count
                   5969: 
                   5970: @xref{Memory Blocks} for words that move, copy and search
                   5971: for strings. @xref{Displaying characters and strings,} for words that
                   5972: display characters and strings.
                   5973: 
                   5974: 
                   5975: @node Displaying characters and strings, Input, String Formats, Other I/O
                   5976: @subsection Displaying characters and strings
1.27      crook    5977: @cindex characters - compiling and displaying
                   5978: @cindex character strings - compiling and displaying
1.26      crook    5979: 
                   5980: This section starts with a glossary of Forth words and ends with a set
                   5981: of examples.
                   5982: 
                   5983: doc-bl
                   5984: doc-space
                   5985: doc-spaces
                   5986: doc-emit
                   5987: doc-toupper
                   5988: doc-."
                   5989: doc-.(
                   5990: doc-type
                   5991: doc-cr
1.27      crook    5992: @cindex cursor control
1.26      crook    5993: doc-at-xy
                   5994: doc-page
                   5995: doc-s"
                   5996: doc-c"
                   5997: doc-char
                   5998: doc-[char]
                   5999: doc-sliteral
                   6000: 
                   6001: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    6002: 
                   6003: @example
1.26      crook    6004: .( text-1)
                   6005: : my-word
                   6006:   ." text-2" cr
                   6007:   .( text-3)
                   6008: ;
                   6009: 
                   6010: ." text-4"
                   6011: 
                   6012: : my-char
                   6013:   [char] ALPHABET emit
                   6014:   char emit
                   6015: ;
1.5       anton    6016: @end example
                   6017: 
1.26      crook    6018: When you load this code into Gforth, the following output is generated:
1.5       anton    6019: 
1.26      crook    6020: @example
1.30      anton    6021: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    6022: @end example
1.5       anton    6023: 
1.26      crook    6024: @itemize @bullet
                   6025: @item
                   6026: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   6027: is an immediate word; it behaves in the same way whether it is used inside
                   6028: or outside a colon definition.
                   6029: @item
                   6030: Message @code{text-4} is displayed because of Gforth's added interpretation
                   6031: semantics for @code{."}.
                   6032: @item
1.29      crook    6033: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    6034: performs the compilation semantics for @code{."} within the definition of
                   6035: @code{my-word}.
                   6036: @end itemize
1.5       anton    6037: 
1.26      crook    6038: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    6039: 
1.26      crook    6040: @example
1.30      anton    6041: @kbd{my-word @key{RET}} text-2
1.26      crook    6042:  ok
1.30      anton    6043: @kbd{my-char fred @key{RET}} Af ok
                   6044: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    6045: @end example
1.5       anton    6046: 
                   6047: @itemize @bullet
                   6048: @item
1.26      crook    6049: Message @code{text-2} is displayed because of the run-time behaviour of
                   6050: @code{."}.
                   6051: @item
                   6052: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   6053: on the stack at run-time. @code{emit} always displays the character
                   6054: when @code{my-char} is executed.
                   6055: @item
                   6056: @code{char} parses a string at run-time and the second @code{emit} displays
                   6057: the first character of the string.
1.5       anton    6058: @item
1.26      crook    6059: If you type @code{see my-char} you can see that @code{[char]} discarded
                   6060: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   6061: definition of @code{my-char}.
1.5       anton    6062: @end itemize
                   6063: 
                   6064: 
                   6065: 
1.26      crook    6066: @node Input, , Displaying characters and strings, Other I/O
                   6067: @subsection Input
                   6068: @cindex input
1.28      crook    6069: @cindex I/O - see input
                   6070: @cindex parsing a string
1.5       anton    6071: 
1.27      crook    6072: @xref{String Formats} for ways of storing character strings in memory.
1.5       anton    6073: 
1.27      crook    6074: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29      crook    6075: @comment then index them
1.27      crook    6076: 
                   6077: doc-key
                   6078: doc-key?
1.26      crook    6079: doc->number
                   6080: doc->float
                   6081: doc-accept
1.27      crook    6082: doc-pad
                   6083: doc-parse
                   6084: doc-word
                   6085: doc-sword
                   6086: doc-refill
                   6087: @comment obsolescent words..
                   6088: doc-convert
1.26      crook    6089: doc-query
                   6090: doc-expect
1.27      crook    6091: doc-span
1.5       anton    6092: 
                   6093: 
                   6094: @c -------------------------------------------------------------
1.26      crook    6095: @node Programming Tools, Assembler and Code Words, Other I/O, Words
                   6096: @section Programming Tools
                   6097: @cindex programming tools
1.12      anton    6098: 
                   6099: @menu
1.26      crook    6100: * Debugging::                   Simple and quick.
                   6101: * Assertions::                  Making your programs self-checking.
                   6102: * Singlestep Debugger::                Executing your program word by word.
1.5       anton    6103: @end menu
                   6104: 
1.26      crook    6105: @node Debugging, Assertions, Programming Tools, Programming Tools
                   6106: @subsection Debugging
                   6107: @cindex debugging
1.5       anton    6108: 
1.26      crook    6109: Languages with a slow edit/compile/link/test development loop tend to
                   6110: require sophisticated tracing/stepping debuggers to facilate
                   6111: productive debugging.
1.5       anton    6112: 
1.26      crook    6113: A much better (faster) way in fast-compiling languages is to add
                   6114: printing code at well-selected places, let the program run, look at
                   6115: the output, see where things went wrong, add more printing code, etc.,
                   6116: until the bug is found.
1.5       anton    6117: 
1.26      crook    6118: The simple debugging aids provided in @file{debugs.fs}
                   6119: are meant to support this style of debugging. In addition, there are
                   6120: words for non-destructively inspecting the stack and memory:
1.5       anton    6121: 
1.26      crook    6122: doc-.s
                   6123: doc-f.s
1.5       anton    6124: 
1.29      crook    6125: There is a word @code{.r} but it does @i{not} display the return
1.26      crook    6126: stack! It is used for formatted numeric output.
1.5       anton    6127: 
1.26      crook    6128: doc-depth
                   6129: doc-fdepth
                   6130: doc-clearstack
                   6131: doc-?
                   6132: doc-dump
1.5       anton    6133: 
1.26      crook    6134: The word @code{~~} prints debugging information (by default the source
                   6135: location and the stack contents). It is easy to insert. If you use Emacs
                   6136: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   6137: query-replace them with nothing). The deferred words
                   6138: @code{printdebugdata} and @code{printdebugline} control the output of
                   6139: @code{~~}. The default source location output format works well with
                   6140: Emacs' compilation mode, so you can step through the program at the
                   6141: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   6142: is that you can step in any direction and you know where the crash has
                   6143: happened or where the strange data has occurred).
1.5       anton    6144: 
1.26      crook    6145: The default actions of @code{~~} clobber the contents of the pictured
                   6146: numeric output string, so you should not use @code{~~}, e.g., between
                   6147: @code{<#} and @code{#>}.
1.5       anton    6148: 
1.26      crook    6149: doc-~~
                   6150: doc-printdebugdata
                   6151: doc-printdebugline
1.5       anton    6152: 
1.26      crook    6153: doc-see
                   6154: doc-marker
1.5       anton    6155: 
1.26      crook    6156: Here's an example of using @code{marker} at the start of a source file
                   6157: that you are debugging; it ensures that you only ever have one copy of
                   6158: the file's definitions compiled at any time:
1.5       anton    6159: 
1.26      crook    6160: @example
                   6161: [IFDEF] my-code
                   6162:     my-code
                   6163: [ENDIF]
1.5       anton    6164: 
1.26      crook    6165: marker my-code
1.28      crook    6166: init-included-files
1.5       anton    6167: 
1.26      crook    6168: \ .. definitions start here
                   6169: \ .
                   6170: \ .
                   6171: \ end
                   6172: @end example
1.5       anton    6173: 
                   6174: 
                   6175: 
1.26      crook    6176: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   6177: @subsection Assertions
                   6178: @cindex assertions
1.5       anton    6179: 
1.26      crook    6180: It is a good idea to make your programs self-checking, especially if you
                   6181: make an assumption that may become invalid during maintenance (for
                   6182: example, that a certain field of a data structure is never zero). Gforth
1.29      crook    6183: supports @dfn{assertions} for this purpose. They are used like this:
1.23      crook    6184: 
1.26      crook    6185: @example
1.29      crook    6186: assert( @i{flag} )
1.26      crook    6187: @end example
1.23      crook    6188: 
1.26      crook    6189: The code between @code{assert(} and @code{)} should compute a flag, that
                   6190: should be true if everything is alright and false otherwise. It should
                   6191: not change anything else on the stack. The overall stack effect of the
                   6192: assertion is @code{( -- )}. E.g.
1.23      crook    6193: 
1.26      crook    6194: @example
                   6195: assert( 1 1 + 2 = ) \ what we learn in school
                   6196: assert( dup 0<> ) \ assert that the top of stack is not zero
                   6197: assert( false ) \ this code should not be reached
                   6198: @end example
1.23      crook    6199: 
1.26      crook    6200: The need for assertions is different at different times. During
                   6201: debugging, we want more checking, in production we sometimes care more
                   6202: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   6203: becomes a comment. Depending on the importance of an assertion and the
                   6204: time it takes to check it, you may want to turn off some assertions and
                   6205: keep others turned on. Gforth provides several levels of assertions for
                   6206: this purpose:
1.23      crook    6207: 
1.26      crook    6208: doc-assert0(
                   6209: doc-assert1(
                   6210: doc-assert2(
                   6211: doc-assert3(
                   6212: doc-assert(
                   6213: doc-)
1.23      crook    6214: 
1.26      crook    6215: The variable @code{assert-level} specifies the highest assertions that
                   6216: are turned on. I.e., at the default @code{assert-level} of one,
                   6217: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   6218: @code{assert2(} and @code{assert3(} assertions are treated as comments.
                   6219: 
                   6220: The value of @code{assert-level} is evaluated at compile-time, not at
                   6221: run-time. Therefore you cannot turn assertions on or off at run-time;
                   6222: you have to set the @code{assert-level} appropriately before compiling a
                   6223: piece of code. You can compile different pieces of code at different
                   6224: @code{assert-level}s (e.g., a trusted library at level 1 and
                   6225: newly-written code at level 3).
1.23      crook    6226: 
1.26      crook    6227: doc-assert-level
1.23      crook    6228: 
1.26      crook    6229: If an assertion fails, a message compatible with Emacs' compilation mode
                   6230: is produced and the execution is aborted (currently with @code{ABORT"}.
                   6231: If there is interest, we will introduce a special throw code. But if you
                   6232: intend to @code{catch} a specific condition, using @code{throw} is
                   6233: probably more appropriate than an assertion).
1.23      crook    6234: 
1.26      crook    6235: Definitions in ANS Forth for these assertion words are provided
                   6236: in @file{compat/assert.fs}.
1.23      crook    6237: 
                   6238: 
1.26      crook    6239: @node Singlestep Debugger, , Assertions, Programming Tools
                   6240: @subsection Singlestep Debugger
                   6241: @cindex singlestep Debugger
                   6242: @cindex debugging Singlestep
                   6243: @cindex @code{dbg}
                   6244: @cindex @code{BREAK:}
                   6245: @cindex @code{BREAK"}
1.23      crook    6246: 
1.26      crook    6247: When you create a new word there's often the need to check whether it
                   6248: behaves correctly or not. You can do this by typing @code{dbg
                   6249: badword}. A debug session might look like this:
1.23      crook    6250: 
1.26      crook    6251: @example
                   6252: : badword 0 DO i . LOOP ;  ok
                   6253: 2 dbg badword 
                   6254: : badword  
                   6255: Scanning code...
1.23      crook    6256: 
1.26      crook    6257: Nesting debugger ready!
1.23      crook    6258: 
1.26      crook    6259: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   6260: 400D4740  8049F68 DO             -> [ 0 ] 
                   6261: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   6262: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   6263: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   6264: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   6265: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   6266: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   6267: 400D4758  804B384 ;              ->  ok
                   6268: @end example
1.23      crook    6269: 
1.26      crook    6270: Each line displayed is one step. You always have to hit return to
                   6271: execute the next word that is displayed. If you don't want to execute
                   6272: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   6273: an overview what keys are available:
1.23      crook    6274: 
1.26      crook    6275: @table @i
1.23      crook    6276: 
1.30      anton    6277: @item @key{RET}
1.26      crook    6278: Next; Execute the next word.
1.23      crook    6279: 
1.26      crook    6280: @item n
                   6281: Nest; Single step through next word.
1.5       anton    6282: 
1.26      crook    6283: @item u
                   6284: Unnest; Stop debugging and execute rest of word. If we got to this word
                   6285: with nest, continue debugging with the calling word.
1.5       anton    6286: 
1.26      crook    6287: @item d
                   6288: Done; Stop debugging and execute rest.
1.5       anton    6289: 
1.26      crook    6290: @item s
                   6291: Stop; Abort immediately.
1.5       anton    6292: 
1.26      crook    6293: @end table
1.5       anton    6294: 
1.26      crook    6295: Debugging large application with this mechanism is very difficult, because
                   6296: you have to nest very deeply into the program before the interesting part
                   6297: begins. This takes a lot of time. 
1.5       anton    6298: 
1.26      crook    6299: To do it more directly put a @code{BREAK:} command into your source code.
                   6300: When program execution reaches @code{BREAK:} the single step debugger is
                   6301: invoked and you have all the features described above.
1.23      crook    6302: 
1.26      crook    6303: If you have more than one part to debug it is useful to know where the
                   6304: program has stopped at the moment. You can do this by the 
                   6305: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   6306: string is typed out when the ``breakpoint'' is reached.
                   6307: 
                   6308: doc-dbg
                   6309: doc-BREAK:
                   6310: doc-BREAK"
                   6311: 
                   6312: 
                   6313: @c -------------------------------------------------------------
                   6314: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   6315: @section Assembler and Code Words
                   6316: @cindex assembler
                   6317: @cindex code words
1.5       anton    6318: 
1.26      crook    6319: Gforth provides some words for defining primitives (words written in
1.29      crook    6320: machine code), and for defining the machine-code equivalent of
1.26      crook    6321: @code{DOES>}-based defining words. However, the machine-independent
                   6322: nature of Gforth poses a few problems: First of all, Gforth runs on
                   6323: several architectures, so it can provide no standard assembler. What's
                   6324: worse is that the register allocation not only depends on the processor,
                   6325: but also on the @code{gcc} version and options used.
1.5       anton    6326: 
1.29      crook    6327: The words that Gforth offers encapsulate some system dependences (e.g.,
                   6328: the header structure), so a system-independent assembler may be used in
1.26      crook    6329: Gforth. If you do not have an assembler, you can compile machine code
1.29      crook    6330: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   6331: because these words emit stuff in @i{data} space; it works because
                   6332: Gforth has unified code/data spaces. Assembler isn't likely to be
                   6333: portable anyway.}.
1.5       anton    6334: 
1.26      crook    6335: doc-assembler
                   6336: doc-code
                   6337: doc-end-code
                   6338: doc-;code
                   6339: doc-flush-icache
1.5       anton    6340: 
1.26      crook    6341: If @code{flush-icache} does not work correctly, @code{code} words
                   6342: etc. will not work (reliably), either.
1.5       anton    6343: 
1.29      crook    6344: The typical usage of these @code{code} words can be shown most easily by
                   6345: analogy to the equivalent high-level defining words:
                   6346: 
                   6347: @example
                   6348: : foo                                        code foo
                   6349:    <high-level Forth words>                        <assembler>
                   6350: ;                                            end-code
                   6351: 
                   6352: : bar                                        : bar
                   6353:    <high-level Forth words>                     <high-level Forth words>
                   6354:    CREATE                                       CREATE
                   6355:       <high-level Forth words>                     <high-level Forth words>
                   6356:    DOES>                                        ;code
                   6357:       <high-level Forth words>                     <assembler>
                   6358: ;                                            end-code
                   6359: @end example
                   6360: 
1.26      crook    6361: @code{flush-icache} is always present. The other words are rarely used
                   6362: and reside in @code{code.fs}, which is usually not loaded. You can load
                   6363: it with @code{require code.fs}.
1.5       anton    6364: 
1.26      crook    6365: @cindex registers of the inner interpreter
                   6366: In the assembly code you will want to refer to the inner interpreter's
                   6367: registers (e.g., the data stack pointer) and you may want to use other
                   6368: registers for temporary storage. Unfortunately, the register allocation
                   6369: is installation-dependent.
1.5       anton    6370: 
1.26      crook    6371: The easiest solution is to use explicit register declarations
                   6372: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
                   6373: GNU C Manual}) for all of the inner interpreter's registers: You have to
                   6374: compile Gforth with @code{-DFORCE_REG} (configure option
                   6375: @code{--enable-force-reg}) and the appropriate declarations must be
                   6376: present in the @code{machine.h} file (see @code{mips.h} for an example;
                   6377: you can find a full list of all declarable register symbols with
                   6378: @code{grep register engine.c}). If you give explicit registers to all
                   6379: variables that are declared at the beginning of @code{engine()}, you
                   6380: should be able to use the other caller-saved registers for temporary
                   6381: storage. Alternatively, you can use the @code{gcc} option
                   6382: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
                   6383: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
                   6384: (however, this restriction on register allocation may slow Gforth
                   6385: significantly).
1.5       anton    6386: 
1.26      crook    6387: If this solution is not viable (e.g., because @code{gcc} does not allow
                   6388: you to explicitly declare all the registers you need), you have to find
                   6389: out by looking at the code where the inner interpreter's registers
                   6390: reside and which registers can be used for temporary storage. You can
                   6391: get an assembly listing of the engine's code with @code{make engine.s}.
1.5       anton    6392: 
1.26      crook    6393: In any case, it is good practice to abstract your assembly code from the
                   6394: actual register allocation. E.g., if the data stack pointer resides in
                   6395: register @code{$17}, create an alias for this register called @code{sp},
                   6396: and use that in your assembly code.
1.5       anton    6397: 
1.26      crook    6398: @cindex code words, portable
                   6399: Another option for implementing normal and defining words efficiently
                   6400: is to add the desired functionality to the source of Gforth. For normal
                   6401: words you just have to edit @file{primitives} (@pxref{Automatic
                   6402: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   6403: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   6404: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5       anton    6405: 
                   6406: 
1.26      crook    6407: @c -------------------------------------------------------------
                   6408: @node Threading Words, Locals, Assembler and Code Words, Words
                   6409: @section Threading Words
                   6410: @cindex threading words
1.5       anton    6411: 
1.26      crook    6412: @cindex code address
                   6413: These words provide access to code addresses and other threading stuff
                   6414: in Gforth (and, possibly, other interpretive Forths). It more or less
                   6415: abstracts away the differences between direct and indirect threading
                   6416: (and, for direct threading, the machine dependences). However, at
                   6417: present this wordset is still incomplete. It is also pretty low-level;
                   6418: some day it will hopefully be made unnecessary by an internals wordset
                   6419: that abstracts implementation details away completely.
1.5       anton    6420: 
1.26      crook    6421: doc-threading-method
                   6422: doc->code-address
                   6423: doc->does-code
                   6424: doc-code-address!
                   6425: doc-does-code!
                   6426: doc-does-handler!
                   6427: doc-/does-handler
1.5       anton    6428: 
1.26      crook    6429: The code addresses produced by various defining words are produced by
                   6430: the following words:
1.5       anton    6431: 
1.26      crook    6432: doc-docol:
                   6433: doc-docon:
                   6434: doc-dovar:
                   6435: doc-douser:
                   6436: doc-dodefer:
                   6437: doc-dofield:
1.5       anton    6438: 
1.26      crook    6439: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
                   6440: with @code{>does-code}. If the word was defined in that way, the value
                   6441: returned is non-zero and identifies the @code{DOES>} used by the
                   6442: defining word.
                   6443: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5       anton    6444: 
1.26      crook    6445: @c -------------------------------------------------------------
                   6446: @node Locals, Structures, Threading Words, Words
                   6447: @section Locals
                   6448: @cindex locals
1.5       anton    6449: 
1.26      crook    6450: Local variables can make Forth programming more enjoyable and Forth
                   6451: programs easier to read. Unfortunately, the locals of ANS Forth are
                   6452: laden with restrictions. Therefore, we provide not only the ANS Forth
                   6453: locals wordset, but also our own, more powerful locals wordset (we
                   6454: implemented the ANS Forth locals wordset through our locals wordset).
1.5       anton    6455: 
1.26      crook    6456: The ideas in this section have also been published in the paper
                   6457: @cite{Automatic Scoping of Local Variables} by M. Anton Ertl, presented
                   6458: at EuroForth '94; it is available at
                   6459: @*@url{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz}.
1.5       anton    6460: 
1.26      crook    6461: @menu
                   6462: * Gforth locals::               
                   6463: * ANS Forth locals::            
                   6464: @end menu
1.5       anton    6465: 
1.26      crook    6466: @node Gforth locals, ANS Forth locals, Locals, Locals
                   6467: @subsection Gforth locals
                   6468: @cindex Gforth locals
                   6469: @cindex locals, Gforth style
1.5       anton    6470: 
1.26      crook    6471: Locals can be defined with
1.5       anton    6472: 
                   6473: @example
1.26      crook    6474: @{ local1 local2 ... -- comment @}
                   6475: @end example
                   6476: or
                   6477: @example
                   6478: @{ local1 local2 ... @}
1.5       anton    6479: @end example
                   6480: 
1.26      crook    6481: E.g.,
1.5       anton    6482: @example
1.26      crook    6483: : max @{ n1 n2 -- n3 @}
                   6484:  n1 n2 > if
                   6485:    n1
                   6486:  else
                   6487:    n2
                   6488:  endif ;
1.5       anton    6489: @end example
                   6490: 
1.26      crook    6491: The similarity of locals definitions with stack comments is intended. A
                   6492: locals definition often replaces the stack comment of a word. The order
                   6493: of the locals corresponds to the order in a stack comment and everything
                   6494: after the @code{--} is really a comment.
1.5       anton    6495: 
1.26      crook    6496: This similarity has one disadvantage: It is too easy to confuse locals
                   6497: declarations with stack comments, causing bugs and making them hard to
                   6498: find. However, this problem can be avoided by appropriate coding
                   6499: conventions: Do not use both notations in the same program. If you do,
                   6500: they should be distinguished using additional means, e.g. by position.
                   6501: 
                   6502: @cindex types of locals
                   6503: @cindex locals types
                   6504: The name of the local may be preceded by a type specifier, e.g.,
                   6505: @code{F:} for a floating point value:
                   6506: 
                   6507: @example
                   6508: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   6509: \ complex multiplication
                   6510:  Ar Br f* Ai Bi f* f-
                   6511:  Ar Bi f* Ai Br f* f+ ;
                   6512: @end example
                   6513: 
                   6514: @cindex flavours of locals
                   6515: @cindex locals flavours
                   6516: @cindex value-flavoured locals
                   6517: @cindex variable-flavoured locals
                   6518: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   6519: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   6520: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   6521: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   6522: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   6523: produces its address (which becomes invalid when the variable's scope is
                   6524: left). E.g., the standard word @code{emit} can be defined in terms of
                   6525: @code{type} like this:
1.5       anton    6526: 
                   6527: @example
1.26      crook    6528: : emit @{ C^ char* -- @}
                   6529:     char* 1 type ;
1.5       anton    6530: @end example
                   6531: 
1.26      crook    6532: @cindex default type of locals
                   6533: @cindex locals, default type
                   6534: A local without type specifier is a @code{W:} local. Both flavours of
                   6535: locals are initialized with values from the data or FP stack.
1.5       anton    6536: 
1.26      crook    6537: Currently there is no way to define locals with user-defined data
                   6538: structures, but we are working on it.
1.5       anton    6539: 
1.26      crook    6540: Gforth allows defining locals everywhere in a colon definition. This
                   6541: poses the following questions:
1.5       anton    6542: 
1.26      crook    6543: @menu
                   6544: * Where are locals visible by name?::  
                   6545: * How long do locals live?::    
                   6546: * Programming Style::           
                   6547: * Implementation::              
                   6548: @end menu
1.5       anton    6549: 
1.26      crook    6550: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   6551: @subsubsection Where are locals visible by name?
                   6552: @cindex locals visibility
                   6553: @cindex visibility of locals
                   6554: @cindex scope of locals
1.5       anton    6555: 
1.26      crook    6556: Basically, the answer is that locals are visible where you would expect
                   6557: it in block-structured languages, and sometimes a little longer. If you
                   6558: want to restrict the scope of a local, enclose its definition in
                   6559: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    6560: 
1.26      crook    6561: doc-scope
                   6562: doc-endscope
1.5       anton    6563: 
1.26      crook    6564: These words behave like control structure words, so you can use them
                   6565: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   6566: arbitrary ways.
1.5       anton    6567: 
1.26      crook    6568: If you want a more exact answer to the visibility question, here's the
                   6569: basic principle: A local is visible in all places that can only be
                   6570: reached through the definition of the local@footnote{In compiler
                   6571: construction terminology, all places dominated by the definition of the
                   6572: local.}. In other words, it is not visible in places that can be reached
                   6573: without going through the definition of the local. E.g., locals defined
                   6574: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   6575: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   6576: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5       anton    6577: 
1.26      crook    6578: The reasoning behind this solution is: We want to have the locals
                   6579: visible as long as it is meaningful. The user can always make the
                   6580: visibility shorter by using explicit scoping. In a place that can
                   6581: only be reached through the definition of a local, the meaning of a
                   6582: local name is clear. In other places it is not: How is the local
                   6583: initialized at the control flow path that does not contain the
                   6584: definition? Which local is meant, if the same name is defined twice in
                   6585: two independent control flow paths?
1.5       anton    6586: 
1.26      crook    6587: This should be enough detail for nearly all users, so you can skip the
                   6588: rest of this section. If you really must know all the gory details and
                   6589: options, read on.
1.5       anton    6590: 
1.26      crook    6591: In order to implement this rule, the compiler has to know which places
                   6592: are unreachable. It knows this automatically after @code{AHEAD},
                   6593: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   6594: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   6595: compiler that the control flow never reaches that place. If
                   6596: @code{UNREACHABLE} is not used where it could, the only consequence is
                   6597: that the visibility of some locals is more limited than the rule above
                   6598: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   6599: lie to the compiler), buggy code will be produced.
1.5       anton    6600: 
1.26      crook    6601: doc-unreachable
1.5       anton    6602: 
1.26      crook    6603: Another problem with this rule is that at @code{BEGIN}, the compiler
                   6604: does not know which locals will be visible on the incoming
                   6605: back-edge. All problems discussed in the following are due to this
                   6606: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   6607: loops as examples; the discussion also applies to @code{?DO} and other
                   6608: loops). Perhaps the most insidious example is:
1.5       anton    6609: @example
1.26      crook    6610: AHEAD
                   6611: BEGIN
                   6612:   x
                   6613: [ 1 CS-ROLL ] THEN
                   6614:   @{ x @}
                   6615:   ...
                   6616: UNTIL
                   6617: @end example
1.5       anton    6618: 
1.26      crook    6619: This should be legal according to the visibility rule. The use of
                   6620: @code{x} can only be reached through the definition; but that appears
                   6621: textually below the use.
1.5       anton    6622: 
1.26      crook    6623: From this example it is clear that the visibility rules cannot be fully
                   6624: implemented without major headaches. Our implementation treats common
                   6625: cases as advertised and the exceptions are treated in a safe way: The
                   6626: compiler makes a reasonable guess about the locals visible after a
                   6627: @code{BEGIN}; if it is too pessimistic, the
                   6628: user will get a spurious error about the local not being defined; if the
                   6629: compiler is too optimistic, it will notice this later and issue a
                   6630: warning. In the case above the compiler would complain about @code{x}
                   6631: being undefined at its use. You can see from the obscure examples in
                   6632: this section that it takes quite unusual control structures to get the
                   6633: compiler into trouble, and even then it will often do fine.
1.5       anton    6634: 
1.26      crook    6635: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   6636: is that all locals visible before the @code{BEGIN} will also be
                   6637: visible after the @code{BEGIN}. This guess is valid for all loops that
                   6638: are entered only through the @code{BEGIN}, in particular, for normal
                   6639: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   6640: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   6641: compiler. When the branch to the @code{BEGIN} is finally generated by
                   6642: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   6643: warns the user if it was too optimistic:
                   6644: @example
                   6645: IF
                   6646:   @{ x @}
                   6647: BEGIN
                   6648:   \ x ? 
                   6649: [ 1 cs-roll ] THEN
                   6650:   ...
                   6651: UNTIL
1.5       anton    6652: @end example
                   6653: 
1.26      crook    6654: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   6655: optimistically assumes that it lives until the @code{THEN}. It notices
                   6656: this difference when it compiles the @code{UNTIL} and issues a
                   6657: warning. The user can avoid the warning, and make sure that @code{x}
                   6658: is not used in the wrong area by using explicit scoping:
                   6659: @example
                   6660: IF
                   6661:   SCOPE
                   6662:   @{ x @}
                   6663:   ENDSCOPE
                   6664: BEGIN
                   6665: [ 1 cs-roll ] THEN
                   6666:   ...
                   6667: UNTIL
                   6668: @end example
1.5       anton    6669: 
1.26      crook    6670: Since the guess is optimistic, there will be no spurious error messages
                   6671: about undefined locals.
1.5       anton    6672: 
1.26      crook    6673: If the @code{BEGIN} is not reachable from above (e.g., after
                   6674: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   6675: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   6676: defined later. Therefore, the compiler assumes that no locals are
                   6677: visible after the @code{BEGIN}. However, the user can use
                   6678: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   6679: visible at the BEGIN as at the point where the top control-flow stack
                   6680: item was created.
1.5       anton    6681: 
1.26      crook    6682: doc-assume-live
1.5       anton    6683: 
1.26      crook    6684: E.g.,
1.5       anton    6685: @example
1.26      crook    6686: @{ x @}
                   6687: AHEAD
                   6688: ASSUME-LIVE
                   6689: BEGIN
                   6690:   x
                   6691: [ 1 CS-ROLL ] THEN
                   6692:   ...
                   6693: UNTIL
1.5       anton    6694: @end example
                   6695: 
1.26      crook    6696: Other cases where the locals are defined before the @code{BEGIN} can be
                   6697: handled by inserting an appropriate @code{CS-ROLL} before the
                   6698: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   6699: behind the @code{ASSUME-LIVE}).
1.5       anton    6700: 
1.26      crook    6701: Cases where locals are defined after the @code{BEGIN} (but should be
                   6702: visible immediately after the @code{BEGIN}) can only be handled by
                   6703: rearranging the loop. E.g., the ``most insidious'' example above can be
                   6704: arranged into:
1.5       anton    6705: @example
1.26      crook    6706: BEGIN
                   6707:   @{ x @}
                   6708:   ... 0=
                   6709: WHILE
                   6710:   x
                   6711: REPEAT
1.5       anton    6712: @end example
                   6713: 
1.26      crook    6714: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
                   6715: @subsubsection How long do locals live?
                   6716: @cindex locals lifetime
                   6717: @cindex lifetime of locals
1.5       anton    6718: 
1.26      crook    6719: The right answer for the lifetime question would be: A local lives at
                   6720: least as long as it can be accessed. For a value-flavoured local this
                   6721: means: until the end of its visibility. However, a variable-flavoured
                   6722: local could be accessed through its address far beyond its visibility
                   6723: scope. Ultimately, this would mean that such locals would have to be
                   6724: garbage collected. Since this entails un-Forth-like implementation
                   6725: complexities, I adopted the same cowardly solution as some other
                   6726: languages (e.g., C): The local lives only as long as it is visible;
                   6727: afterwards its address is invalid (and programs that access it
                   6728: afterwards are erroneous).
1.5       anton    6729: 
1.26      crook    6730: @node Programming Style, Implementation, How long do locals live?, Gforth locals
                   6731: @subsubsection Programming Style
                   6732: @cindex locals programming style
                   6733: @cindex programming style, locals
1.5       anton    6734: 
1.26      crook    6735: The freedom to define locals anywhere has the potential to change
                   6736: programming styles dramatically. In particular, the need to use the
                   6737: return stack for intermediate storage vanishes. Moreover, all stack
                   6738: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   6739: determined arguments) can be eliminated: If the stack items are in the
                   6740: wrong order, just write a locals definition for all of them; then
                   6741: write the items in the order you want.
1.5       anton    6742: 
1.26      crook    6743: This seems a little far-fetched and eliminating stack manipulations is
                   6744: unlikely to become a conscious programming objective. Still, the number
                   6745: of stack manipulations will be reduced dramatically if local variables
                   6746: are used liberally (e.g., compare @code{max} in @ref{Gforth locals} with
                   6747: a traditional implementation of @code{max}).
1.5       anton    6748: 
1.26      crook    6749: This shows one potential benefit of locals: making Forth programs more
                   6750: readable. Of course, this benefit will only be realized if the
                   6751: programmers continue to honour the principle of factoring instead of
                   6752: using the added latitude to make the words longer.
1.5       anton    6753: 
1.26      crook    6754: @cindex single-assignment style for locals
                   6755: Using @code{TO} can and should be avoided.  Without @code{TO},
                   6756: every value-flavoured local has only a single assignment and many
                   6757: advantages of functional languages apply to Forth. I.e., programs are
                   6758: easier to analyse, to optimize and to read: It is clear from the
                   6759: definition what the local stands for, it does not turn into something
                   6760: different later.
1.5       anton    6761: 
1.26      crook    6762: E.g., a definition using @code{TO} might look like this:
1.5       anton    6763: @example
1.26      crook    6764: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   6765:  u1 u2 min 0
                   6766:  ?do
                   6767:    addr1 c@@ addr2 c@@ -
                   6768:    ?dup-if
                   6769:      unloop exit
                   6770:    then
                   6771:    addr1 char+ TO addr1
                   6772:    addr2 char+ TO addr2
                   6773:  loop
                   6774:  u1 u2 - ;
1.5       anton    6775: @end example
1.26      crook    6776: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   6777: every loop iteration. @code{strcmp} is a typical example of the
                   6778: readability problems of using @code{TO}. When you start reading
                   6779: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   6780: string. Only near the end of the loop you realize that it is something
                   6781: else.
1.5       anton    6782: 
1.26      crook    6783: This can be avoided by defining two locals at the start of the loop that
                   6784: are initialized with the right value for the current iteration.
1.5       anton    6785: @example
1.26      crook    6786: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   6787:  addr1 addr2
                   6788:  u1 u2 min 0 
                   6789:  ?do @{ s1 s2 @}
                   6790:    s1 c@@ s2 c@@ -
                   6791:    ?dup-if
                   6792:      unloop exit
                   6793:    then
                   6794:    s1 char+ s2 char+
                   6795:  loop
                   6796:  2drop
                   6797:  u1 u2 - ;
1.5       anton    6798: @end example
1.26      crook    6799: Here it is clear from the start that @code{s1} has a different value
                   6800: in every loop iteration.
1.5       anton    6801: 
1.26      crook    6802: @node Implementation,  , Programming Style, Gforth locals
                   6803: @subsubsection Implementation
                   6804: @cindex locals implementation
                   6805: @cindex implementation of locals
1.5       anton    6806: 
1.26      crook    6807: @cindex locals stack
                   6808: Gforth uses an extra locals stack. The most compelling reason for
                   6809: this is that the return stack is not float-aligned; using an extra stack
                   6810: also eliminates the problems and restrictions of using the return stack
                   6811: as locals stack. Like the other stacks, the locals stack grows toward
                   6812: lower addresses. A few primitives allow an efficient implementation:
1.5       anton    6813: 
1.26      crook    6814: doc-@local#
                   6815: doc-f@local#
                   6816: doc-laddr#
                   6817: doc-lp+!#
                   6818: doc-lp!
                   6819: doc->l
                   6820: doc-f>l
1.5       anton    6821: 
1.26      crook    6822: In addition to these primitives, some specializations of these
                   6823: primitives for commonly occurring inline arguments are provided for
                   6824: efficiency reasons, e.g., @code{@@local0} as specialization of
                   6825: @code{@@local#} for the inline argument 0. The following compiling words
                   6826: compile the right specialized version, or the general version, as
                   6827: appropriate:
1.6       pazsan   6828: 
1.26      crook    6829: doc-compile-@local
                   6830: doc-compile-f@local
                   6831: doc-compile-lp+!
1.12      anton    6832: 
1.26      crook    6833: Combinations of conditional branches and @code{lp+!#} like
                   6834: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   6835: is taken) are provided for efficiency and correctness in loops.
1.6       pazsan   6836: 
1.26      crook    6837: A special area in the dictionary space is reserved for keeping the
                   6838: local variable names. @code{@{} switches the dictionary pointer to this
                   6839: area and @code{@}} switches it back and generates the locals
                   6840: initializing code. @code{W:} etc.@ are normal defining words. This
                   6841: special area is cleared at the start of every colon definition.
1.6       pazsan   6842: 
1.26      crook    6843: @cindex word list for defining locals
                   6844: A special feature of Gforth's dictionary is used to implement the
                   6845: definition of locals without type specifiers: every word list (aka
                   6846: vocabulary) has its own methods for searching
                   6847: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   6848: with a special search method: When it is searched for a word, it
                   6849: actually creates that word using @code{W:}. @code{@{} changes the search
                   6850: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   6851: and then the word list for defining locals without type specifiers.
1.12      anton    6852: 
1.26      crook    6853: The lifetime rules support a stack discipline within a colon
                   6854: definition: The lifetime of a local is either nested with other locals
                   6855: lifetimes or it does not overlap them.
1.6       pazsan   6856: 
1.26      crook    6857: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   6858: pointer manipulation is generated. Between control structure words
                   6859: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   6860: is the simplest of the other three control flow words. It has to
                   6861: restore the locals stack depth of the corresponding @code{BEGIN}
                   6862: before branching. The code looks like this:
                   6863: @format
                   6864: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   6865: @code{branch} <begin>
                   6866: @end format
1.6       pazsan   6867: 
1.26      crook    6868: @code{UNTIL} is a little more complicated: If it branches back, it
                   6869: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   6870: the locals stack must not be changed. The compiler generates the
                   6871: following code:
                   6872: @format
                   6873: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   6874: @end format
                   6875: The locals stack pointer is only adjusted if the branch is taken.
1.6       pazsan   6876: 
1.26      crook    6877: @code{THEN} can produce somewhat inefficient code:
                   6878: @format
                   6879: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   6880: <orig target>:
                   6881: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   6882: @end format
                   6883: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29      crook    6884: level at the @i{orig} point to the level after the @code{THEN}. The
1.26      crook    6885: first @code{lp+!#} adjusts the locals stack pointer from the current
                   6886: level to the level at the orig point, so the complete effect is an
                   6887: adjustment from the current level to the right level after the
                   6888: @code{THEN}.
1.6       pazsan   6889: 
1.26      crook    6890: @cindex locals information on the control-flow stack
                   6891: @cindex control-flow stack items, locals information
                   6892: In a conventional Forth implementation a dest control-flow stack entry
                   6893: is just the target address and an orig entry is just the address to be
                   6894: patched. Our locals implementation adds a word list to every orig or dest
                   6895: item. It is the list of locals visible (or assumed visible) at the point
                   6896: described by the entry. Our implementation also adds a tag to identify
                   6897: the kind of entry, in particular to differentiate between live and dead
                   6898: (reachable and unreachable) orig entries.
1.6       pazsan   6899: 
1.26      crook    6900: A few unusual operations have to be performed on locals word lists:
1.6       pazsan   6901: 
1.26      crook    6902: doc-common-list
                   6903: doc-sub-list?
                   6904: doc-list-size
1.6       pazsan   6905: 
1.26      crook    6906: Several features of our locals word list implementation make these
                   6907: operations easy to implement: The locals word lists are organised as
                   6908: linked lists; the tails of these lists are shared, if the lists
                   6909: contain some of the same locals; and the address of a name is greater
                   6910: than the address of the names behind it in the list.
1.6       pazsan   6911: 
1.26      crook    6912: Another important implementation detail is the variable
                   6913: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   6914: determine if they can be reached directly or only through the branch
                   6915: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   6916: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   6917: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6       pazsan   6918: 
1.26      crook    6919: Counted loops are similar to other loops in most respects, but
                   6920: @code{LEAVE} requires special attention: It performs basically the same
                   6921: service as @code{AHEAD}, but it does not create a control-flow stack
                   6922: entry. Therefore the information has to be stored elsewhere;
                   6923: traditionally, the information was stored in the target fields of the
                   6924: branches created by the @code{LEAVE}s, by organizing these fields into a
                   6925: linked list. Unfortunately, this clever trick does not provide enough
                   6926: space for storing our extended control flow information. Therefore, we
                   6927: introduce another stack, the leave stack. It contains the control-flow
                   6928: stack entries for all unresolved @code{LEAVE}s.
1.6       pazsan   6929: 
1.26      crook    6930: Local names are kept until the end of the colon definition, even if
                   6931: they are no longer visible in any control-flow path. In a few cases
                   6932: this may lead to increased space needs for the locals name area, but
                   6933: usually less than reclaiming this space would cost in code size.
1.6       pazsan   6934: 
                   6935: 
1.26      crook    6936: @node ANS Forth locals,  , Gforth locals, Locals
                   6937: @subsection ANS Forth locals
                   6938: @cindex locals, ANS Forth style
1.6       pazsan   6939: 
1.26      crook    6940: The ANS Forth locals wordset does not define a syntax for locals, but
                   6941: words that make it possible to define various syntaxes. One of the
                   6942: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   6943: wordset, i.e.:
1.6       pazsan   6944: 
                   6945: @example
1.26      crook    6946: @{ local1 local2 ... -- comment @}
1.6       pazsan   6947: @end example
1.23      crook    6948: @noindent
1.26      crook    6949: or
1.6       pazsan   6950: @example
1.26      crook    6951: @{ local1 local2 ... @}
1.6       pazsan   6952: @end example
                   6953: 
1.26      crook    6954: The order of the locals corresponds to the order in a stack comment. The
                   6955: restrictions are:
1.6       pazsan   6956: 
                   6957: @itemize @bullet
                   6958: @item
1.26      crook    6959: Locals can only be cell-sized values (no type specifiers are allowed).
1.6       pazsan   6960: @item
1.26      crook    6961: Locals can be defined only outside control structures.
1.6       pazsan   6962: @item
1.26      crook    6963: Locals can interfere with explicit usage of the return stack. For the
                   6964: exact (and long) rules, see the standard. If you don't use return stack
                   6965: accessing words in a definition using locals, you will be all right. The
                   6966: purpose of this rule is to make locals implementation on the return
                   6967: stack easier.
1.6       pazsan   6968: @item
1.26      crook    6969: The whole definition must be in one line.
                   6970: @end itemize
1.6       pazsan   6971: 
1.26      crook    6972: Locals defined in this way behave like @code{VALUE}s (@xref{Simple
                   6973: Defining Words}). I.e., they are initialized from the stack. Using their
                   6974: name produces their value. Their value can be changed using @code{TO}.
1.6       pazsan   6975: 
1.26      crook    6976: Since this syntax is supported by Gforth directly, you need not do
                   6977: anything to use it. If you want to port a program using this syntax to
                   6978: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   6979: syntax on the other system.
1.6       pazsan   6980: 
1.26      crook    6981: Note that a syntax shown in the standard, section A.13 looks
                   6982: similar, but is quite different in having the order of locals
                   6983: reversed. Beware!
1.6       pazsan   6984: 
1.26      crook    6985: The ANS Forth locals wordset itself consists of a word:
1.6       pazsan   6986: 
1.26      crook    6987: doc-(local)
1.6       pazsan   6988: 
1.26      crook    6989: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
                   6990: awful that we strongly recommend not to use it. We have implemented this
                   6991: syntax to make porting to Gforth easy, but do not document it here. The
                   6992: problem with this syntax is that the locals are defined in an order
                   6993: reversed with respect to the standard stack comment notation, making
                   6994: programs harder to read, and easier to misread and miswrite. The only
                   6995: merit of this syntax is that it is easy to implement using the ANS Forth
                   6996: locals wordset.
1.7       pazsan   6997: 
                   6998: 
1.26      crook    6999: @c ----------------------------------------------------------
                   7000: @node Structures, Object-oriented Forth, Locals, Words
                   7001: @section  Structures
                   7002: @cindex structures
                   7003: @cindex records
1.7       pazsan   7004: 
1.26      crook    7005: This section presents the structure package that comes with Gforth. A
                   7006: version of the package implemented in ANS Forth is available in
                   7007: @file{compat/struct.fs}. This package was inspired by a posting on
                   7008: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   7009: possibly John Hayes). A version of this section has been published in
                   7010: ???. Marcel Hendrix provided helpful comments.
1.7       pazsan   7011: 
1.26      crook    7012: @menu
                   7013: * Why explicit structure support?::  
                   7014: * Structure Usage::             
                   7015: * Structure Naming Convention::  
                   7016: * Structure Implementation::    
                   7017: * Structure Glossary::          
                   7018: @end menu
1.7       pazsan   7019: 
1.26      crook    7020: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   7021: @subsection Why explicit structure support?
1.7       pazsan   7022: 
1.26      crook    7023: @cindex address arithmetic for structures
                   7024: @cindex structures using address arithmetic
                   7025: If we want to use a structure containing several fields, we could simply
                   7026: reserve memory for it, and access the fields using address arithmetic
1.32      anton    7027: (@pxref{Address arithmetic}). As an example, consider a structure with
1.26      crook    7028: the following fields
1.7       pazsan   7029: 
1.26      crook    7030: @table @code
                   7031: @item a
                   7032: is a float
                   7033: @item b
                   7034: is a cell
                   7035: @item c
                   7036: is a float
                   7037: @end table
1.7       pazsan   7038: 
1.26      crook    7039: Given the (float-aligned) base address of the structure we get the
                   7040: address of the field
1.13      pazsan   7041: 
1.26      crook    7042: @table @code
                   7043: @item a
                   7044: without doing anything further.
                   7045: @item b
                   7046: with @code{float+}
                   7047: @item c
                   7048: with @code{float+ cell+ faligned}
                   7049: @end table
1.13      pazsan   7050: 
1.26      crook    7051: It is easy to see that this can become quite tiring. 
1.13      pazsan   7052: 
1.26      crook    7053: Moreover, it is not very readable, because seeing a
                   7054: @code{cell+} tells us neither which kind of structure is
                   7055: accessed nor what field is accessed; we have to somehow infer the kind
                   7056: of structure, and then look up in the documentation, which field of
                   7057: that structure corresponds to that offset.
1.13      pazsan   7058: 
1.26      crook    7059: Finally, this kind of address arithmetic also causes maintenance
                   7060: troubles: If you add or delete a field somewhere in the middle of the
                   7061: structure, you have to find and change all computations for the fields
                   7062: afterwards.
1.13      pazsan   7063: 
1.26      crook    7064: So, instead of using @code{cell+} and friends directly, how
                   7065: about storing the offsets in constants:
1.13      pazsan   7066: 
                   7067: @example
1.26      crook    7068: 0 constant a-offset
                   7069: 0 float+ constant b-offset
                   7070: 0 float+ cell+ faligned c-offset
1.13      pazsan   7071: @end example
                   7072: 
1.26      crook    7073: Now we can get the address of field @code{x} with @code{x-offset
                   7074: +}. This is much better in all respects. Of course, you still
                   7075: have to change all later offset definitions if you add a field. You can
                   7076: fix this by declaring the offsets in the following way:
1.13      pazsan   7077: 
                   7078: @example
1.26      crook    7079: 0 constant a-offset
                   7080: a-offset float+ constant b-offset
                   7081: b-offset cell+ faligned constant c-offset
1.13      pazsan   7082: @end example
                   7083: 
1.26      crook    7084: Since we always use the offsets with @code{+}, we could use a defining
                   7085: word @code{cfield} that includes the @code{+} in the action of the
                   7086: defined word:
1.8       pazsan   7087: 
                   7088: @example
1.26      crook    7089: : cfield ( n "name" -- )
                   7090:     create ,
                   7091: does> ( name execution: addr1 -- addr2 )
                   7092:     @@ + ;
1.13      pazsan   7093: 
1.26      crook    7094: 0 cfield a
                   7095: 0 a float+ cfield b
                   7096: 0 b cell+ faligned cfield c
1.13      pazsan   7097: @end example
                   7098: 
1.26      crook    7099: Instead of @code{x-offset +}, we now simply write @code{x}.
                   7100: 
                   7101: The structure field words now can be used quite nicely. However,
                   7102: their definition is still a bit cumbersome: We have to repeat the
                   7103: name, the information about size and alignment is distributed before
                   7104: and after the field definitions etc.  The structure package presented
                   7105: here addresses these problems.
                   7106: 
                   7107: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   7108: @subsection Structure Usage
                   7109: @cindex structure usage
1.13      pazsan   7110: 
1.26      crook    7111: @cindex @code{field} usage
                   7112: @cindex @code{struct} usage
                   7113: @cindex @code{end-struct} usage
                   7114: You can define a structure for a (data-less) linked list with:
1.13      pazsan   7115: @example
1.26      crook    7116: struct
                   7117:     cell% field list-next
                   7118: end-struct list%
1.13      pazsan   7119: @end example
                   7120: 
1.26      crook    7121: With the address of the list node on the stack, you can compute the
                   7122: address of the field that contains the address of the next node with
                   7123: @code{list-next}. E.g., you can determine the length of a list
                   7124: with:
1.13      pazsan   7125: 
                   7126: @example
1.26      crook    7127: : list-length ( list -- n )
                   7128: \ "list" is a pointer to the first element of a linked list
                   7129: \ "n" is the length of the list
                   7130:     0 BEGIN ( list1 n1 )
                   7131:         over
                   7132:     WHILE ( list1 n1 )
                   7133:         1+ swap list-next @@ swap
                   7134:     REPEAT
                   7135:     nip ;
1.13      pazsan   7136: @end example
                   7137: 
1.26      crook    7138: You can reserve memory for a list node in the dictionary with
                   7139: @code{list% %allot}, which leaves the address of the list node on the
                   7140: stack. For the equivalent allocation on the heap you can use @code{list%
                   7141: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   7142: use @code{list% %allocate}). You can get the the size of a list
                   7143: node with @code{list% %size} and its alignment with @code{list%
                   7144: %alignment}.
1.13      pazsan   7145: 
1.26      crook    7146: Note that in ANS Forth the body of a @code{create}d word is
                   7147: @code{aligned} but not necessarily @code{faligned};
                   7148: therefore, if you do a:
1.13      pazsan   7149: @example
1.26      crook    7150: create @emph{name} foo% %allot
1.8       pazsan   7151: @end example
                   7152: 
1.26      crook    7153: @noindent
                   7154: then the memory alloted for @code{foo%} is
                   7155: guaranteed to start at the body of @code{@emph{name}} only if
                   7156: @code{foo%} contains only character, cell and double fields.
1.20      pazsan   7157: 
1.26      crook    7158: @cindex strcutures containing structures
                   7159: You can include a structure @code{foo%} as a field of
                   7160: another structure, like this:
1.20      pazsan   7161: @example
1.26      crook    7162: struct
                   7163: ...
                   7164:     foo% field ...
                   7165: ...
                   7166: end-struct ...
1.20      pazsan   7167: @end example
                   7168: 
1.26      crook    7169: @cindex structure extension
                   7170: @cindex extended records
                   7171: Instead of starting with an empty structure, you can extend an
                   7172: existing structure. E.g., a plain linked list without data, as defined
                   7173: above, is hardly useful; You can extend it to a linked list of integers,
                   7174: like this:@footnote{This feature is also known as @emph{extended
                   7175: records}. It is the main innovation in the Oberon language; in other
                   7176: words, adding this feature to Modula-2 led Wirth to create a new
                   7177: language, write a new compiler etc.  Adding this feature to Forth just
                   7178: required a few lines of code.}
1.20      pazsan   7179: 
                   7180: @example
1.26      crook    7181: list%
                   7182:     cell% field intlist-int
                   7183: end-struct intlist%
1.20      pazsan   7184: @end example
                   7185: 
1.26      crook    7186: @code{intlist%} is a structure with two fields:
                   7187: @code{list-next} and @code{intlist-int}.
1.20      pazsan   7188: 
1.26      crook    7189: @cindex structures containing arrays
                   7190: You can specify an array type containing @emph{n} elements of
                   7191: type @code{foo%} like this:
1.20      pazsan   7192: 
                   7193: @example
1.26      crook    7194: foo% @emph{n} *
1.20      pazsan   7195: @end example
                   7196: 
1.26      crook    7197: You can use this array type in any place where you can use a normal
                   7198: type, e.g., when defining a @code{field}, or with
                   7199: @code{%allot}.
1.20      pazsan   7200: 
1.26      crook    7201: @cindex first field optimization
                   7202: The first field is at the base address of a structure and the word
                   7203: for this field (e.g., @code{list-next}) actually does not change
                   7204: the address on the stack. You may be tempted to leave it away in the
                   7205: interest of run-time and space efficiency. This is not necessary,
                   7206: because the structure package optimizes this case and compiling such
                   7207: words does not generate any code. So, in the interest of readability
                   7208: and maintainability you should include the word for the field when
                   7209: accessing the field.
1.20      pazsan   7210: 
1.26      crook    7211: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   7212: @subsection Structure Naming Convention
                   7213: @cindex structure naming convention
1.20      pazsan   7214: 
1.26      crook    7215: The field names that come to (my) mind are often quite generic, and,
                   7216: if used, would cause frequent name clashes. E.g., many structures
                   7217: probably contain a @code{counter} field. The structure names
                   7218: that come to (my) mind are often also the logical choice for the names
                   7219: of words that create such a structure.
1.20      pazsan   7220: 
1.26      crook    7221: Therefore, I have adopted the following naming conventions: 
1.20      pazsan   7222: 
1.26      crook    7223: @itemize @bullet
                   7224: @cindex field naming convention
                   7225: @item
                   7226: The names of fields are of the form
                   7227: @code{@emph{struct}-@emph{field}}, where
                   7228: @code{@emph{struct}} is the basic name of the structure, and
                   7229: @code{@emph{field}} is the basic name of the field. You can
                   7230: think of field words as converting the (address of the)
                   7231: structure into the (address of the) field.
1.20      pazsan   7232: 
1.26      crook    7233: @cindex structure naming convention
                   7234: @item
                   7235: The names of structures are of the form
                   7236: @code{@emph{struct}%}, where
                   7237: @code{@emph{struct}} is the basic name of the structure.
                   7238: @end itemize
1.20      pazsan   7239: 
1.26      crook    7240: This naming convention does not work that well for fields of extended
                   7241: structures; e.g., the integer list structure has a field
                   7242: @code{intlist-int}, but has @code{list-next}, not
                   7243: @code{intlist-next}.
1.20      pazsan   7244: 
1.26      crook    7245: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   7246: @subsection Structure Implementation
                   7247: @cindex structure implementation
                   7248: @cindex implementation of structures
1.20      pazsan   7249: 
1.26      crook    7250: The central idea in the implementation is to pass the data about the
                   7251: structure being built on the stack, not in some global
                   7252: variable. Everything else falls into place naturally once this design
                   7253: decision is made.
1.20      pazsan   7254: 
1.26      crook    7255: The type description on the stack is of the form @emph{align
                   7256: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   7257: very simple.
1.20      pazsan   7258: 
1.26      crook    7259: @code{field} is a defining word that uses @code{Create}
                   7260: and @code{DOES>}. The body of the field contains the offset
                   7261: of the field, and the normal @code{DOES>} action is simply:
1.20      pazsan   7262: 
                   7263: @example
1.26      crook    7264: @ +
1.20      pazsan   7265: @end example
                   7266: 
1.23      crook    7267: @noindent
1.26      crook    7268: i.e., add the offset to the address, giving the stack effect
1.29      crook    7269: @i{addr1 -- addr2} for a field.
1.20      pazsan   7270: 
1.26      crook    7271: @cindex first field optimization, implementation
                   7272: This simple structure is slightly complicated by the optimization
                   7273: for fields with offset 0, which requires a different
                   7274: @code{DOES>}-part (because we cannot rely on there being
                   7275: something on the stack if such a field is invoked during
                   7276: compilation). Therefore, we put the different @code{DOES>}-parts
                   7277: in separate words, and decide which one to invoke based on the
                   7278: offset. For a zero offset, the field is basically a noop; it is
                   7279: immediate, and therefore no code is generated when it is compiled.
1.20      pazsan   7280: 
1.26      crook    7281: @node Structure Glossary,  , Structure Implementation, Structures
                   7282: @subsection Structure Glossary
                   7283: @cindex structure glossary
1.20      pazsan   7284: 
1.26      crook    7285: doc-%align
                   7286: doc-%alignment
                   7287: doc-%alloc
                   7288: doc-%allocate
                   7289: doc-%allot
                   7290: doc-cell%
                   7291: doc-char%
                   7292: doc-dfloat%
                   7293: doc-double%
                   7294: doc-end-struct
                   7295: doc-field
                   7296: doc-float%
                   7297: doc-naligned
                   7298: doc-sfloat%
                   7299: doc-%size
                   7300: doc-struct
1.23      crook    7301: 
1.26      crook    7302: @c -------------------------------------------------------------
                   7303: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
                   7304: @section Object-oriented Forth
1.20      pazsan   7305: 
1.26      crook    7306: Gforth comes with three packages for object-oriented programming:
                   7307: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   7308: is preloaded, so you have to @code{include} them before use. The most
                   7309: important differences between these packages (and others) are discussed
                   7310: in @ref{Comparison with other object models}. All packages are written
                   7311: in ANS Forth and can be used with any other ANS Forth.
1.20      pazsan   7312: 
1.26      crook    7313: @menu
                   7314: * Why object-oriented programming?::
                   7315: * Object-Oriented Terminology::
                   7316: * Objects::
                   7317: * OOF::
                   7318: * Mini-OOF::
                   7319: * Comparison with other object models::  
                   7320: @end menu
1.20      pazsan   7321: 
1.23      crook    7322: 
1.26      crook    7323: @node Why object-oriented programming?, Object-Oriented Terminology, , Object-oriented Forth
                   7324: @subsubsection Why object-oriented programming?
                   7325: @cindex object-oriented programming motivation
                   7326: @cindex motivation for object-oriented programming
1.23      crook    7327: 
1.26      crook    7328: Often we have to deal with several data structures (@emph{objects}),
                   7329: that have to be treated similarly in some respects, but differently in
                   7330: others. Graphical objects are the textbook example: circles, triangles,
                   7331: dinosaurs, icons, and others, and we may want to add more during program
                   7332: development. We want to apply some operations to any graphical object,
                   7333: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   7334: has to do something different for every kind of object.
                   7335: @comment TODO add some other operations eg perimeter, area
                   7336: @comment and tie in to concrete examples later..
1.23      crook    7337: 
1.26      crook    7338: We could implement @code{draw} as a big @code{CASE}
                   7339: control structure that executes the appropriate code depending on the
                   7340: kind of object to be drawn. This would be not be very elegant, and,
                   7341: moreover, we would have to change @code{draw} every time we add
                   7342: a new kind of graphical object (say, a spaceship).
1.23      crook    7343: 
1.26      crook    7344: What we would rather do is: When defining spaceships, we would tell
                   7345: the system: ``Here's how you @code{draw} a spaceship; you figure
                   7346: out the rest''.
1.23      crook    7347: 
1.26      crook    7348: This is the problem that all systems solve that (rightfully) call
                   7349: themselves object-oriented; the object-oriented packages presented here
                   7350: solve this problem (and not much else).
                   7351: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23      crook    7352: 
1.26      crook    7353: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   7354: @subsubsection Object-Oriented Terminology
                   7355: @cindex object-oriented terminology
                   7356: @cindex terminology for object-oriented programming
1.23      crook    7357: 
1.26      crook    7358: This section is mainly for reference, so you don't have to understand
                   7359: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   7360: short:
1.23      crook    7361: 
1.26      crook    7362: @table @emph
                   7363: @cindex class
                   7364: @item class
                   7365: a data structure definition with some extras.
1.23      crook    7366: 
1.26      crook    7367: @cindex object
                   7368: @item object
                   7369: an instance of the data structure described by the class definition.
1.23      crook    7370: 
1.26      crook    7371: @cindex instance variables
                   7372: @item instance variables
                   7373: fields of the data structure.
1.23      crook    7374: 
1.26      crook    7375: @cindex selector
                   7376: @cindex method selector
                   7377: @cindex virtual function
                   7378: @item selector
                   7379: (or @emph{method selector}) a word (e.g.,
                   7380: @code{draw}) that performs an operation on a variety of data
                   7381: structures (classes). A selector describes @emph{what} operation to
                   7382: perform. In C++ terminology: a (pure) virtual function.
1.23      crook    7383: 
1.26      crook    7384: @cindex method
                   7385: @item method
                   7386: the concrete definition that performs the operation
                   7387: described by the selector for a specific class. A method specifies
                   7388: @emph{how} the operation is performed for a specific class.
1.23      crook    7389: 
1.26      crook    7390: @cindex selector invocation
                   7391: @cindex message send
                   7392: @cindex invoking a selector
                   7393: @item selector invocation
                   7394: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   7395: is used for determining which method is used. In Smalltalk terminology:
                   7396: a message (consisting of the selector and the other arguments) is sent
                   7397: to the object.
1.1       anton    7398: 
1.26      crook    7399: @cindex receiving object
                   7400: @item receiving object
                   7401: the object used for determining the method executed by a selector
                   7402: invocation. In the @file{objects.fs} model, it is the object that is on
                   7403: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   7404: the Smalltalk @emph{message} terminology.)
1.1       anton    7405: 
1.26      crook    7406: @cindex child class
                   7407: @cindex parent class
                   7408: @cindex inheritance
                   7409: @item child class
                   7410: a class that has (@emph{inherits}) all properties (instance variables,
                   7411: selectors, methods) from a @emph{parent class}. In Smalltalk
                   7412: terminology: The subclass inherits from the superclass. In C++
                   7413: terminology: The derived class inherits from the base class.
1.1       anton    7414: 
1.26      crook    7415: @end table
1.21      crook    7416: 
1.26      crook    7417: @c If you wonder about the message sending terminology, it comes from
                   7418: @c a time when each object had it's own task and objects communicated via
                   7419: @c message passing; eventually the Smalltalk developers realized that
                   7420: @c they can do most things through simple (indirect) calls. They kept the
                   7421: @c terminology.
1.1       anton    7422: 
                   7423: 
1.26      crook    7424: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   7425: @subsection The @file{objects.fs} model
                   7426: @cindex objects
                   7427: @cindex object-oriented programming
1.1       anton    7428: 
1.26      crook    7429: @cindex @file{objects.fs}
                   7430: @cindex @file{oof.fs}
1.1       anton    7431: 
1.37      anton    7432: This section describes the @file{objects.fs} package. This material also
                   7433: has been published in @cite{Yet Another Forth Objects Package} by Anton
                   7434: Ertl and appeared in Forth Dimensions 19(2), pages 37--43
                   7435: (@url{http://www.complang.tuwien.ac.at/forth/objects/objects.html}).
1.26      crook    7436: @c McKewan's and Zsoter's packages
1.1       anton    7437: 
1.26      crook    7438: This section assumes that you have read @ref{Structures}.
1.1       anton    7439: 
1.26      crook    7440: The techniques on which this model is based have been used to implement
                   7441: the parser generator, Gray, and have also been used in Gforth for
                   7442: implementing the various flavours of word lists (hashed or not,
                   7443: case-sensitive or not, special-purpose word lists for locals etc.).
1.1       anton    7444: 
                   7445: 
1.26      crook    7446: @menu
                   7447: * Properties of the Objects model::  
                   7448: * Basic Objects Usage::         
1.37      anton    7449: * The Objects base class::      
1.26      crook    7450: * Creating objects::            
                   7451: * Object-Oriented Programming Style::  
                   7452: * Class Binding::               
                   7453: * Method conveniences::         
                   7454: * Classes and Scoping::         
1.37      anton    7455: * Dividing classes::            
1.26      crook    7456: * Object Interfaces::           
                   7457: * Objects Implementation::      
                   7458: * Objects Glossary::            
                   7459: @end menu
1.1       anton    7460: 
1.26      crook    7461: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
                   7462: and Bernd Paysan helped me with the related works section.
1.1       anton    7463: 
1.26      crook    7464: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   7465: @subsubsection Properties of the @file{objects.fs} model
                   7466: @cindex @file{objects.fs} properties
1.1       anton    7467: 
1.26      crook    7468: @itemize @bullet
                   7469: @item
                   7470: It is straightforward to pass objects on the stack. Passing
                   7471: selectors on the stack is a little less convenient, but possible.
1.1       anton    7472: 
1.26      crook    7473: @item
                   7474: Objects are just data structures in memory, and are referenced by their
                   7475: address. You can create words for objects with normal defining words
                   7476: like @code{constant}. Likewise, there is no difference between instance
                   7477: variables that contain objects and those that contain other data.
1.1       anton    7478: 
1.26      crook    7479: @item
                   7480: Late binding is efficient and easy to use.
1.21      crook    7481: 
1.26      crook    7482: @item
                   7483: It avoids parsing, and thus avoids problems with state-smartness
                   7484: and reduced extensibility; for convenience there are a few parsing
                   7485: words, but they have non-parsing counterparts. There are also a few
                   7486: defining words that parse. This is hard to avoid, because all standard
                   7487: defining words parse (except @code{:noname}); however, such
                   7488: words are not as bad as many other parsing words, because they are not
                   7489: state-smart.
1.21      crook    7490: 
1.26      crook    7491: @item
                   7492: It does not try to incorporate everything. It does a few things and does
                   7493: them well (IMO). In particular, this model was not designed to support
                   7494: information hiding (although it has features that may help); you can use
                   7495: a separate package for achieving this.
1.21      crook    7496: 
1.26      crook    7497: @item
                   7498: It is layered; you don't have to learn and use all features to use this
                   7499: model. Only a few features are necessary (@xref{Basic Objects Usage},
                   7500: @xref{The Objects base class}, @xref{Creating objects}.), the others
                   7501: are optional and independent of each other.
1.21      crook    7502: 
1.26      crook    7503: @item
                   7504: An implementation in ANS Forth is available.
1.21      crook    7505: 
1.26      crook    7506: @end itemize
1.21      crook    7507: 
                   7508: 
1.26      crook    7509: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   7510: @subsubsection Basic @file{objects.fs} Usage
                   7511: @cindex basic objects usage
                   7512: @cindex objects, basic usage
1.21      crook    7513: 
1.26      crook    7514: You can define a class for graphical objects like this:
1.21      crook    7515: 
1.26      crook    7516: @cindex @code{class} usage
                   7517: @cindex @code{end-class} usage
                   7518: @cindex @code{selector} usage
                   7519: @example
                   7520: object class \ "object" is the parent class
                   7521:   selector draw ( x y graphical -- )
                   7522: end-class graphical
                   7523: @end example
1.21      crook    7524: 
1.26      crook    7525: This code defines a class @code{graphical} with an
                   7526: operation @code{draw}.  We can perform the operation
                   7527: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    7528: 
1.26      crook    7529: @example
                   7530: 100 100 t-rex draw
                   7531: @end example
1.21      crook    7532: 
1.26      crook    7533: @noindent
                   7534: where @code{t-rex} is a word (say, a constant) that produces a
                   7535: graphical object.
1.21      crook    7536: 
1.29      crook    7537: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26      crook    7538: @comment a concrete example
1.21      crook    7539: 
1.26      crook    7540: @cindex abstract class
                   7541: How do we create a graphical object? With the present definitions,
                   7542: we cannot create a useful graphical object. The class
                   7543: @code{graphical} describes graphical objects in general, but not
                   7544: any concrete graphical object type (C++ users would call it an
                   7545: @emph{abstract class}); e.g., there is no method for the selector
                   7546: @code{draw} in the class @code{graphical}.
1.21      crook    7547: 
1.26      crook    7548: For concrete graphical objects, we define child classes of the
                   7549: class @code{graphical}, e.g.:
1.21      crook    7550: 
1.26      crook    7551: @cindex @code{overrides} usage
                   7552: @cindex @code{field} usage in class definition
                   7553: @example
                   7554: graphical class \ "graphical" is the parent class
                   7555:   cell% field circle-radius
1.21      crook    7556: 
1.26      crook    7557: :noname ( x y circle -- )
                   7558:   circle-radius @@ draw-circle ;
                   7559: overrides draw
1.21      crook    7560: 
1.26      crook    7561: :noname ( n-radius circle -- )
                   7562:   circle-radius ! ;
                   7563: overrides construct
1.21      crook    7564: 
1.26      crook    7565: end-class circle
1.21      crook    7566: @end example
                   7567: 
1.26      crook    7568: Here we define a class @code{circle} as a child of @code{graphical},
                   7569: with field @code{circle-radius} (which behaves just like a field
                   7570: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   7571: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   7572: defined in @code{object}, the parent class of @code{graphical}).
1.21      crook    7573: 
1.26      crook    7574: Now we can create a circle on the heap (i.e.,
                   7575: @code{allocate}d memory) with:
1.21      crook    7576: 
1.26      crook    7577: @cindex @code{heap-new} usage
1.21      crook    7578: @example
1.26      crook    7579: 50 circle heap-new constant my-circle
                   7580: @end example
1.21      crook    7581: 
1.26      crook    7582: @noindent
                   7583: @code{heap-new} invokes @code{construct}, thus
                   7584: initializing the field @code{circle-radius} with 50. We can draw
                   7585: this new circle at (100,100) with:
1.21      crook    7586: 
1.26      crook    7587: @example
                   7588: 100 100 my-circle draw
1.21      crook    7589: @end example
                   7590: 
1.26      crook    7591: @cindex selector invocation, restrictions
                   7592: @cindex class definition, restrictions
                   7593: Note: You can only invoke a selector if the object on the TOS
                   7594: (the receiving object) belongs to the class where the selector was
                   7595: defined or one of its descendents; e.g., you can invoke
                   7596: @code{draw} only for objects belonging to @code{graphical}
                   7597: or its descendents (e.g., @code{circle}).  Immediately before
                   7598: @code{end-class}, the search order has to be the same as
                   7599: immediately after @code{class}.
1.21      crook    7600: 
1.26      crook    7601: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   7602: @subsubsection The @file{object.fs} base class
                   7603: @cindex @code{object} class
1.21      crook    7604: 
1.26      crook    7605: When you define a class, you have to specify a parent class.  So how do
                   7606: you start defining classes? There is one class available from the start:
                   7607: @code{object}. It is ancestor for all classes and so is the
                   7608: only class that has no parent. It has two selectors: @code{construct}
                   7609: and @code{print}.
1.21      crook    7610: 
1.26      crook    7611: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   7612: @subsubsection Creating objects
                   7613: @cindex creating objects
                   7614: @cindex object creation
                   7615: @cindex object allocation options
1.21      crook    7616: 
1.26      crook    7617: @cindex @code{heap-new} discussion
                   7618: @cindex @code{dict-new} discussion
                   7619: @cindex @code{construct} discussion
                   7620: You can create and initialize an object of a class on the heap with
                   7621: @code{heap-new} ( ... class -- object ) and in the dictionary
                   7622: (allocation with @code{allot}) with @code{dict-new} (
                   7623: ... class -- object ). Both words invoke @code{construct}, which
                   7624: consumes the stack items indicated by "..." above.
1.21      crook    7625: 
1.26      crook    7626: @cindex @code{init-object} discussion
                   7627: @cindex @code{class-inst-size} discussion
                   7628: If you want to allocate memory for an object yourself, you can get its
                   7629: alignment and size with @code{class-inst-size 2@@} ( class --
                   7630: align size ). Once you have memory for an object, you can initialize
                   7631: it with @code{init-object} ( ... class object -- );
                   7632: @code{construct} does only a part of the necessary work.
1.21      crook    7633: 
1.26      crook    7634: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   7635: @subsubsection Object-Oriented Programming Style
                   7636: @cindex object-oriented programming style
1.21      crook    7637: 
1.26      crook    7638: This section is not exhaustive.
1.1       anton    7639: 
1.26      crook    7640: @cindex stack effects of selectors
                   7641: @cindex selectors and stack effects
                   7642: In general, it is a good idea to ensure that all methods for the
                   7643: same selector have the same stack effect: when you invoke a selector,
                   7644: you often have no idea which method will be invoked, so, unless all
                   7645: methods have the same stack effect, you will not know the stack effect
                   7646: of the selector invocation.
1.21      crook    7647: 
1.26      crook    7648: One exception to this rule is methods for the selector
                   7649: @code{construct}. We know which method is invoked, because we
                   7650: specify the class to be constructed at the same place. Actually, I
                   7651: defined @code{construct} as a selector only to give the users a
                   7652: convenient way to specify initialization. The way it is used, a
                   7653: mechanism different from selector invocation would be more natural
                   7654: (but probably would take more code and more space to explain).
1.21      crook    7655: 
1.26      crook    7656: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   7657: @subsubsection Class Binding
                   7658: @cindex class binding
                   7659: @cindex early binding
1.21      crook    7660: 
1.26      crook    7661: @cindex late binding
                   7662: Normal selector invocations determine the method at run-time depending
                   7663: on the class of the receiving object. This run-time selection is called
1.29      crook    7664: @i{late binding}.
1.21      crook    7665: 
1.26      crook    7666: Sometimes it's preferable to invoke a different method. For example,
                   7667: you might want to use the simple method for @code{print}ing
                   7668: @code{object}s instead of the possibly long-winded @code{print} method
                   7669: of the receiver class. You can achieve this by replacing the invocation
                   7670: of @code{print} with:
1.21      crook    7671: 
1.26      crook    7672: @cindex @code{[bind]} usage
                   7673: @example
                   7674: [bind] object print
1.21      crook    7675: @end example
                   7676: 
1.26      crook    7677: @noindent
                   7678: in compiled code or:
1.21      crook    7679: 
1.26      crook    7680: @cindex @code{bind} usage
1.21      crook    7681: @example
1.26      crook    7682: bind object print
1.21      crook    7683: @end example
                   7684: 
1.26      crook    7685: @cindex class binding, alternative to
                   7686: @noindent
                   7687: in interpreted code. Alternatively, you can define the method with a
                   7688: name (e.g., @code{print-object}), and then invoke it through the
                   7689: name. Class binding is just a (often more convenient) way to achieve
                   7690: the same effect; it avoids name clutter and allows you to invoke
                   7691: methods directly without naming them first.
                   7692: 
                   7693: @cindex superclass binding
                   7694: @cindex parent class binding
                   7695: A frequent use of class binding is this: When we define a method
                   7696: for a selector, we often want the method to do what the selector does
                   7697: in the parent class, and a little more. There is a special word for
                   7698: this purpose: @code{[parent]}; @code{[parent]
                   7699: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   7700: selector}}, where @code{@emph{parent}} is the parent
                   7701: class of the current class. E.g., a method definition might look like:
1.21      crook    7702: 
1.26      crook    7703: @cindex @code{[parent]} usage
1.21      crook    7704: @example
1.26      crook    7705: :noname
                   7706:   dup [parent] foo \ do parent's foo on the receiving object
                   7707:   ... \ do some more
                   7708: ; overrides foo
1.21      crook    7709: @end example
                   7710: 
1.26      crook    7711: @cindex class binding as optimization
                   7712: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   7713: March 1997), Andrew McKewan presents class binding as an optimization
                   7714: technique. I recommend not using it for this purpose unless you are in
                   7715: an emergency. Late binding is pretty fast with this model anyway, so the
                   7716: benefit of using class binding is small; the cost of using class binding
                   7717: where it is not appropriate is reduced maintainability.
1.21      crook    7718: 
1.26      crook    7719: While we are at programming style questions: You should bind
                   7720: selectors only to ancestor classes of the receiving object. E.g., say,
                   7721: you know that the receiving object is of class @code{foo} or its
                   7722: descendents; then you should bind only to @code{foo} and its
                   7723: ancestors.
1.21      crook    7724: 
1.26      crook    7725: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   7726: @subsubsection Method conveniences
                   7727: @cindex method conveniences
1.1       anton    7728: 
1.26      crook    7729: In a method you usually access the receiving object pretty often.  If
                   7730: you define the method as a plain colon definition (e.g., with
                   7731: @code{:noname}), you may have to do a lot of stack
                   7732: gymnastics. To avoid this, you can define the method with @code{m:
                   7733: ... ;m}. E.g., you could define the method for
                   7734: @code{draw}ing a @code{circle} with
1.20      pazsan   7735: 
1.26      crook    7736: @cindex @code{this} usage
                   7737: @cindex @code{m:} usage
                   7738: @cindex @code{;m} usage
                   7739: @example
                   7740: m: ( x y circle -- )
                   7741:   ( x y ) this circle-radius @@ draw-circle ;m
                   7742: @end example
1.20      pazsan   7743: 
1.26      crook    7744: @cindex @code{exit} in @code{m: ... ;m}
                   7745: @cindex @code{exitm} discussion
                   7746: @cindex @code{catch} in @code{m: ... ;m}
                   7747: When this method is executed, the receiver object is removed from the
                   7748: stack; you can access it with @code{this} (admittedly, in this
                   7749: example the use of @code{m: ... ;m} offers no advantage). Note
                   7750: that I specify the stack effect for the whole method (i.e. including
                   7751: the receiver object), not just for the code between @code{m:}
                   7752: and @code{;m}. You cannot use @code{exit} in
                   7753: @code{m:...;m}; instead, use
                   7754: @code{exitm}.@footnote{Moreover, for any word that calls
                   7755: @code{catch} and was defined before loading
                   7756: @code{objects.fs}, you have to redefine it like I redefined
                   7757: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20      pazsan   7758: 
1.26      crook    7759: @cindex @code{inst-var} usage
                   7760: You will frequently use sequences of the form @code{this
                   7761: @emph{field}} (in the example above: @code{this
                   7762: circle-radius}). If you use the field only in this way, you can
                   7763: define it with @code{inst-var} and eliminate the
                   7764: @code{this} before the field name. E.g., the @code{circle}
                   7765: class above could also be defined with:
1.20      pazsan   7766: 
1.26      crook    7767: @example
                   7768: graphical class
                   7769:   cell% inst-var radius
1.20      pazsan   7770: 
1.26      crook    7771: m: ( x y circle -- )
                   7772:   radius @@ draw-circle ;m
                   7773: overrides draw
1.20      pazsan   7774: 
1.26      crook    7775: m: ( n-radius circle -- )
                   7776:   radius ! ;m
                   7777: overrides construct
1.12      anton    7778: 
1.26      crook    7779: end-class circle
                   7780: @end example
1.12      anton    7781: 
1.26      crook    7782: @code{radius} can only be used in @code{circle} and its
                   7783: descendent classes and inside @code{m:...;m}.
1.12      anton    7784: 
1.26      crook    7785: @cindex @code{inst-value} usage
                   7786: You can also define fields with @code{inst-value}, which is
                   7787: to @code{inst-var} what @code{value} is to
                   7788: @code{variable}.  You can change the value of such a field with
                   7789: @code{[to-inst]}.  E.g., we could also define the class
                   7790: @code{circle} like this:
1.12      anton    7791: 
1.26      crook    7792: @example
                   7793: graphical class
                   7794:   inst-value radius
1.12      anton    7795: 
1.26      crook    7796: m: ( x y circle -- )
                   7797:   radius draw-circle ;m
                   7798: overrides draw
1.12      anton    7799: 
1.26      crook    7800: m: ( n-radius circle -- )
                   7801:   [to-inst] radius ;m
                   7802: overrides construct
1.21      crook    7803: 
1.26      crook    7804: end-class circle
1.12      anton    7805: @end example
                   7806: 
1.38      anton    7807: Finally, you can define named methods with @code{:m}.  One use of this
                   7808: feature is the definition of words that occur only in one class and are
                   7809: not intended to be overridden, but which still need method context
                   7810: (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   7811: would be bound frequently, if defined anonymously.
                   7812: 
1.12      anton    7813: 
1.37      anton    7814: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
1.26      crook    7815: @subsubsection Classes and Scoping
                   7816: @cindex classes and scoping
                   7817: @cindex scoping and classes
1.12      anton    7818: 
1.26      crook    7819: Inheritance is frequent, unlike structure extension. This exacerbates
                   7820: the problem with the field name convention (@pxref{Structure Naming
                   7821: Convention}): One always has to remember in which class the field was
                   7822: originally defined; changing a part of the class structure would require
                   7823: changes for renaming in otherwise unaffected code.
1.12      anton    7824: 
1.26      crook    7825: @cindex @code{inst-var} visibility
                   7826: @cindex @code{inst-value} visibility
                   7827: To solve this problem, I added a scoping mechanism (which was not in my
                   7828: original charter): A field defined with @code{inst-var} (or
                   7829: @code{inst-value}) is visible only in the class where it is defined and in
                   7830: the descendent classes of this class.  Using such fields only makes
                   7831: sense in @code{m:}-defined methods in these classes anyway.
1.12      anton    7832: 
1.26      crook    7833: This scoping mechanism allows us to use the unadorned field name,
                   7834: because name clashes with unrelated words become much less likely.
1.12      anton    7835: 
1.26      crook    7836: @cindex @code{protected} discussion
                   7837: @cindex @code{private} discussion
                   7838: Once we have this mechanism, we can also use it for controlling the
                   7839: visibility of other words: All words defined after
                   7840: @code{protected} are visible only in the current class and its
                   7841: descendents. @code{public} restores the compilation
                   7842: (i.e. @code{current}) word list that was in effect before. If you
                   7843: have several @code{protected}s without an intervening
                   7844: @code{public} or @code{set-current}, @code{public}
                   7845: will restore the compilation word list in effect before the first of
                   7846: these @code{protected}s.
1.12      anton    7847: 
1.37      anton    7848: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   7849: @subsubsection Dividing classes
                   7850: @cindex Dividing classes
                   7851: @cindex @code{methods}...@code{end-methods}
                   7852: 
                   7853: You may want to do the definition of methods separate from the
                   7854: definition of the class, its selectors, fields, and instance variables,
                   7855: i.e., separate the implementation from the definition.  You can do this
                   7856: in the following way:
                   7857: 
                   7858: @example
                   7859: graphical class
                   7860:   inst-value radius
                   7861: end-class circle
                   7862: 
                   7863: ... \ do some other stuff
                   7864: 
                   7865: circle methods \ now we are ready
                   7866: 
                   7867: m: ( x y circle -- )
                   7868:   radius draw-circle ;m
                   7869: overrides draw
                   7870: 
                   7871: m: ( n-radius circle -- )
                   7872:   [to-inst] radius ;m
                   7873: overrides construct
                   7874: 
                   7875: end-methods
                   7876: @end example
                   7877: 
                   7878: You can use several @code{methods}...@code{end-methods} sections.  The
                   7879: only things you can do to the class in these sections are: defining
                   7880: methods, and overriding the class's selectors.  You must not define new
                   7881: selectors or fields.
                   7882: 
                   7883: Note that you often have to override a selector before using it.  In
                   7884: particular, you usually have to override @code{construct} with a new
                   7885: method before you can invoke @code{heap-new} and friends.  E.g., you
                   7886: must not create a circle before the @code{overrides construct} sequence
                   7887: in the example above.
                   7888: 
                   7889: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
1.26      crook    7890: @subsubsection Object Interfaces
                   7891: @cindex object interfaces
                   7892: @cindex interfaces for objects
1.12      anton    7893: 
1.26      crook    7894: In this model you can only call selectors defined in the class of the
                   7895: receiving objects or in one of its ancestors. If you call a selector
                   7896: with a receiving object that is not in one of these classes, the
                   7897: result is undefined; if you are lucky, the program crashes
                   7898: immediately.
1.12      anton    7899: 
1.26      crook    7900: @cindex selectors common to hardly-related classes
                   7901: Now consider the case when you want to have a selector (or several)
                   7902: available in two classes: You would have to add the selector to a
                   7903: common ancestor class, in the worst case to @code{object}. You
                   7904: may not want to do this, e.g., because someone else is responsible for
                   7905: this ancestor class.
1.12      anton    7906: 
1.26      crook    7907: The solution for this problem is interfaces. An interface is a
                   7908: collection of selectors. If a class implements an interface, the
                   7909: selectors become available to the class and its descendents. A class
                   7910: can implement an unlimited number of interfaces. For the problem
                   7911: discussed above, we would define an interface for the selector(s), and
                   7912: both classes would implement the interface.
1.12      anton    7913: 
1.26      crook    7914: As an example, consider an interface @code{storage} for
                   7915: writing objects to disk and getting them back, and a class
                   7916: @code{foo} that implements it. The code would look like this:
1.12      anton    7917: 
1.26      crook    7918: @cindex @code{interface} usage
                   7919: @cindex @code{end-interface} usage
                   7920: @cindex @code{implementation} usage
                   7921: @example
                   7922: interface
                   7923:   selector write ( file object -- )
                   7924:   selector read1 ( file object -- )
                   7925: end-interface storage
1.12      anton    7926: 
1.26      crook    7927: bar class
                   7928:   storage implementation
1.12      anton    7929: 
1.26      crook    7930: ... overrides write
1.37      anton    7931: ... overrides read1
1.26      crook    7932: ...
                   7933: end-class foo
1.12      anton    7934: @end example
                   7935: 
1.26      crook    7936: @noindent
1.29      crook    7937: (I would add a word @code{read} @i{( file -- object )} that uses
1.26      crook    7938: @code{read1} internally, but that's beyond the point illustrated
                   7939: here.)
1.12      anton    7940: 
1.26      crook    7941: Note that you cannot use @code{protected} in an interface; and
                   7942: of course you cannot define fields.
1.12      anton    7943: 
1.26      crook    7944: In the Neon model, all selectors are available for all classes;
                   7945: therefore it does not need interfaces. The price you pay in this model
                   7946: is slower late binding, and therefore, added complexity to avoid late
                   7947: binding.
1.12      anton    7948: 
1.26      crook    7949: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   7950: @subsubsection @file{objects.fs} Implementation
                   7951: @cindex @file{objects.fs} implementation
1.12      anton    7952: 
1.26      crook    7953: @cindex @code{object-map} discussion
                   7954: An object is a piece of memory, like one of the data structures
                   7955: described with @code{struct...end-struct}. It has a field
                   7956: @code{object-map} that points to the method map for the object's
                   7957: class.
1.12      anton    7958: 
1.26      crook    7959: @cindex method map
                   7960: @cindex virtual function table
                   7961: The @emph{method map}@footnote{This is Self terminology; in C++
                   7962: terminology: virtual function table.} is an array that contains the
1.29      crook    7963: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26      crook    7964: selector contains an offset into a method map.
1.12      anton    7965: 
1.26      crook    7966: @cindex @code{selector} implementation, class
                   7967: @code{selector} is a defining word that uses
                   7968: @code{CREATE} and @code{DOES>}. The body of the
                   7969: selector contains the offset; the @code{does>} action for a
                   7970: class selector is, basically:
1.21      crook    7971: 
1.26      crook    7972: @example
                   7973: ( object addr ) @@ over object-map @@ + @@ execute
                   7974: @end example
1.12      anton    7975: 
1.26      crook    7976: Since @code{object-map} is the first field of the object, it
                   7977: does not generate any code. As you can see, calling a selector has a
                   7978: small, constant cost.
1.12      anton    7979: 
1.26      crook    7980: @cindex @code{current-interface} discussion
                   7981: @cindex class implementation and representation
                   7982: A class is basically a @code{struct} combined with a method
                   7983: map. During the class definition the alignment and size of the class
                   7984: are passed on the stack, just as with @code{struct}s, so
                   7985: @code{field} can also be used for defining class
                   7986: fields. However, passing more items on the stack would be
                   7987: inconvenient, so @code{class} builds a data structure in memory,
                   7988: which is accessed through the variable
                   7989: @code{current-interface}. After its definition is complete, the
                   7990: class is represented on the stack by a pointer (e.g., as parameter for
                   7991: a child class definition).
1.1       anton    7992: 
1.26      crook    7993: A new class starts off with the alignment and size of its parent,
                   7994: and a copy of the parent's method map. Defining new fields extends the
                   7995: size and alignment; likewise, defining new selectors extends the
1.29      crook    7996: method map. @code{overrides} just stores a new @i{xt} in the method
1.26      crook    7997: map at the offset given by the selector.
1.20      pazsan   7998: 
1.26      crook    7999: @cindex class binding, implementation
1.29      crook    8000: Class binding just gets the @i{xt} at the offset given by the selector
1.26      crook    8001: from the class's method map and @code{compile,}s (in the case of
                   8002: @code{[bind]}) it.
1.21      crook    8003: 
1.26      crook    8004: @cindex @code{this} implementation
                   8005: @cindex @code{catch} and @code{this}
                   8006: @cindex @code{this} and @code{catch}
                   8007: I implemented @code{this} as a @code{value}. At the
                   8008: start of an @code{m:...;m} method the old @code{this} is
                   8009: stored to the return stack and restored at the end; and the object on
                   8010: the TOS is stored @code{TO this}. This technique has one
                   8011: disadvantage: If the user does not leave the method via
                   8012: @code{;m}, but via @code{throw} or @code{exit},
                   8013: @code{this} is not restored (and @code{exit} may
                   8014: crash). To deal with the @code{throw} problem, I have redefined
                   8015: @code{catch} to save and restore @code{this}; the same
                   8016: should be done with any word that can catch an exception. As for
                   8017: @code{exit}, I simply forbid it (as a replacement, there is
                   8018: @code{exitm}).
1.21      crook    8019: 
1.26      crook    8020: @cindex @code{inst-var} implementation
                   8021: @code{inst-var} is just the same as @code{field}, with
                   8022: a different @code{DOES>} action:
                   8023: @example
                   8024: @@ this +
                   8025: @end example
                   8026: Similar for @code{inst-value}.
1.21      crook    8027: 
1.26      crook    8028: @cindex class scoping implementation
                   8029: Each class also has a word list that contains the words defined with
                   8030: @code{inst-var} and @code{inst-value}, and its protected
                   8031: words. It also has a pointer to its parent. @code{class} pushes
                   8032: the word lists of the class and all its ancestors onto the search order stack,
                   8033: and @code{end-class} drops them.
1.21      crook    8034: 
1.26      crook    8035: @cindex interface implementation
                   8036: An interface is like a class without fields, parent and protected
                   8037: words; i.e., it just has a method map. If a class implements an
                   8038: interface, its method map contains a pointer to the method map of the
                   8039: interface. The positive offsets in the map are reserved for class
                   8040: methods, therefore interface map pointers have negative
                   8041: offsets. Interfaces have offsets that are unique throughout the
                   8042: system, unlike class selectors, whose offsets are only unique for the
                   8043: classes where the selector is available (invokable).
1.21      crook    8044: 
1.26      crook    8045: This structure means that interface selectors have to perform one
                   8046: indirection more than class selectors to find their method. Their body
                   8047: contains the interface map pointer offset in the class method map, and
                   8048: the method offset in the interface method map. The
                   8049: @code{does>} action for an interface selector is, basically:
1.21      crook    8050: 
                   8051: @example
1.26      crook    8052: ( object selector-body )
                   8053: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   8054: swap object-map @@ + @@ ( object selector-body map )
                   8055: swap selector-offset @@ + @@ execute
1.21      crook    8056: @end example
                   8057: 
1.26      crook    8058: where @code{object-map} and @code{selector-offset} are
                   8059: first fields and generate no code.
                   8060: 
                   8061: As a concrete example, consider the following code:
1.21      crook    8062: 
1.26      crook    8063: @example
                   8064: interface
                   8065:   selector if1sel1
                   8066:   selector if1sel2
                   8067: end-interface if1
1.21      crook    8068: 
1.26      crook    8069: object class
                   8070:   if1 implementation
                   8071:   selector cl1sel1
                   8072:   cell% inst-var cl1iv1
1.21      crook    8073: 
1.26      crook    8074: ' m1 overrides construct
                   8075: ' m2 overrides if1sel1
                   8076: ' m3 overrides if1sel2
                   8077: ' m4 overrides cl1sel2
                   8078: end-class cl1
1.21      crook    8079: 
1.26      crook    8080: create obj1 object dict-new drop
                   8081: create obj2 cl1    dict-new drop
                   8082: @end example
1.21      crook    8083: 
1.26      crook    8084: The data structure created by this code (including the data structure
                   8085: for @code{object}) is shown in the <a
                   8086: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29      crook    8087: @comment TODO add this diagram..
1.21      crook    8088: 
1.26      crook    8089: @node Objects Glossary,  , Objects Implementation, Objects
                   8090: @subsubsection @file{objects.fs} Glossary
                   8091: @cindex @file{objects.fs} Glossary
1.21      crook    8092: 
1.26      crook    8093: doc---objects-bind
                   8094: doc---objects-<bind>
                   8095: doc---objects-bind'
                   8096: doc---objects-[bind]
                   8097: doc---objects-class
                   8098: doc---objects-class->map
                   8099: doc---objects-class-inst-size
                   8100: doc---objects-class-override!
                   8101: doc---objects-construct
                   8102: doc---objects-current'
                   8103: doc---objects-[current]
                   8104: doc---objects-current-interface
                   8105: doc---objects-dict-new
                   8106: doc---objects-drop-order
                   8107: doc---objects-end-class
                   8108: doc---objects-end-class-noname
                   8109: doc---objects-end-interface
                   8110: doc---objects-end-interface-noname
1.37      anton    8111: doc---objects-end-methods
1.26      crook    8112: doc---objects-exitm
                   8113: doc---objects-heap-new
                   8114: doc---objects-implementation
                   8115: doc---objects-init-object
                   8116: doc---objects-inst-value
                   8117: doc---objects-inst-var
                   8118: doc---objects-interface
1.38      anton    8119: doc---objects-m:
                   8120: doc---objects-:m
1.26      crook    8121: doc---objects-;m
                   8122: doc---objects-method
1.37      anton    8123: doc---objects-methods
1.26      crook    8124: doc---objects-object
                   8125: doc---objects-overrides
                   8126: doc---objects-[parent]
                   8127: doc---objects-print
                   8128: doc---objects-protected
                   8129: doc---objects-public
                   8130: doc---objects-push-order
                   8131: doc---objects-selector
                   8132: doc---objects-this
                   8133: doc---objects-<to-inst>
                   8134: doc---objects-[to-inst]
                   8135: doc---objects-to-this
                   8136: doc---objects-xt-new
1.21      crook    8137: 
1.26      crook    8138: @c -------------------------------------------------------------
                   8139: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   8140: @subsection The @file{oof.fs} model
                   8141: @cindex oof
                   8142: @cindex object-oriented programming
1.21      crook    8143: 
1.26      crook    8144: @cindex @file{objects.fs}
                   8145: @cindex @file{oof.fs}
1.21      crook    8146: 
1.26      crook    8147: This section describes the @file{oof.fs} package.
1.21      crook    8148: 
1.26      crook    8149: The package described in this section has been used in bigFORTH since 1991, and
                   8150: used for two large applications: a chromatographic system used to
                   8151: create new medicaments, and a graphic user interface library (MINOS).
1.21      crook    8152: 
1.26      crook    8153: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   8154: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   8155: 10(2), 1994.
1.21      crook    8156: 
1.26      crook    8157: @menu
                   8158: * Properties of the OOF model::
                   8159: * Basic OOF Usage::
                   8160: * The OOF base class::
                   8161: * Class Declaration::
                   8162: * Class Implementation::
                   8163: @end menu
1.21      crook    8164: 
1.26      crook    8165: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   8166: @subsubsection Properties of the @file{oof.fs} model
                   8167: @cindex @file{oof.fs} properties
1.21      crook    8168: 
1.26      crook    8169: @itemize @bullet
                   8170: @item
                   8171: This model combines object oriented programming with information
                   8172: hiding. It helps you writing large application, where scoping is
                   8173: necessary, because it provides class-oriented scoping.
1.21      crook    8174: 
1.26      crook    8175: @item
                   8176: Named objects, object pointers, and object arrays can be created,
                   8177: selector invocation uses the ``object selector'' syntax. Selector invocation
                   8178: to objects and/or selectors on the stack is a bit less convenient, but
                   8179: possible.
1.21      crook    8180: 
1.26      crook    8181: @item
                   8182: Selector invocation and instance variable usage of the active object is
                   8183: straightforward, since both make use of the active object.
1.21      crook    8184: 
1.26      crook    8185: @item
                   8186: Late binding is efficient and easy to use.
1.21      crook    8187: 
1.26      crook    8188: @item
                   8189: State-smart objects parse selectors. However, extensibility is provided
                   8190: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21      crook    8191: 
                   8192: @item
1.26      crook    8193: An implementation in ANS Forth is available.
                   8194: 
1.21      crook    8195: @end itemize
                   8196: 
                   8197: 
1.26      crook    8198: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   8199: @subsubsection Basic @file{oof.fs} Usage
                   8200: @cindex @file{oof.fs} usage
                   8201: 
                   8202: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21      crook    8203: 
1.26      crook    8204: You can define a class for graphical objects like this:
1.21      crook    8205: 
1.26      crook    8206: @cindex @code{class} usage
                   8207: @cindex @code{class;} usage
                   8208: @cindex @code{method} usage
                   8209: @example
                   8210: object class graphical \ "object" is the parent class
                   8211:   method draw ( x y graphical -- )
                   8212: class;
                   8213: @end example
1.21      crook    8214: 
1.26      crook    8215: This code defines a class @code{graphical} with an
                   8216: operation @code{draw}.  We can perform the operation
                   8217: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    8218: 
1.26      crook    8219: @example
                   8220: 100 100 t-rex draw
                   8221: @end example
1.21      crook    8222: 
1.26      crook    8223: @noindent
                   8224: where @code{t-rex} is an object or object pointer, created with e.g.
                   8225: @code{graphical : t-rex}.
1.21      crook    8226: 
1.26      crook    8227: @cindex abstract class
                   8228: How do we create a graphical object? With the present definitions,
                   8229: we cannot create a useful graphical object. The class
                   8230: @code{graphical} describes graphical objects in general, but not
                   8231: any concrete graphical object type (C++ users would call it an
                   8232: @emph{abstract class}); e.g., there is no method for the selector
                   8233: @code{draw} in the class @code{graphical}.
1.21      crook    8234: 
1.26      crook    8235: For concrete graphical objects, we define child classes of the
                   8236: class @code{graphical}, e.g.:
1.21      crook    8237: 
                   8238: @example
1.26      crook    8239: graphical class circle \ "graphical" is the parent class
                   8240:   cell var circle-radius
                   8241: how:
                   8242:   : draw ( x y -- )
                   8243:     circle-radius @@ draw-circle ;
                   8244: 
                   8245:   : init ( n-radius -- (
                   8246:     circle-radius ! ;
                   8247: class;
                   8248: @end example
                   8249: 
                   8250: Here we define a class @code{circle} as a child of @code{graphical},
                   8251: with a field @code{circle-radius}; it defines new methods for the
                   8252: selectors @code{draw} and @code{init} (@code{init} is defined in
                   8253: @code{object}, the parent class of @code{graphical}).
1.21      crook    8254: 
1.26      crook    8255: Now we can create a circle in the dictionary with:
1.21      crook    8256: 
1.26      crook    8257: @example
                   8258: 50 circle : my-circle
1.21      crook    8259: @end example
                   8260: 
1.26      crook    8261: @noindent
                   8262: @code{:} invokes @code{init}, thus initializing the field
                   8263: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   8264: with:
1.21      crook    8265: 
                   8266: @example
1.26      crook    8267: 100 100 my-circle draw
1.21      crook    8268: @end example
                   8269: 
1.26      crook    8270: @cindex selector invocation, restrictions
                   8271: @cindex class definition, restrictions
                   8272: Note: You can only invoke a selector if the receiving object belongs to
                   8273: the class where the selector was defined or one of its descendents;
                   8274: e.g., you can invoke @code{draw} only for objects belonging to
                   8275: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   8276: mechanism will check if you try to invoke a selector that is not
                   8277: defined in this class hierarchy, so you'll get an error at compilation
                   8278: time.
                   8279: 
                   8280: 
                   8281: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   8282: @subsubsection The @file{oof.fs} base class
                   8283: @cindex @file{oof.fs} base class
                   8284: 
                   8285: When you define a class, you have to specify a parent class.  So how do
                   8286: you start defining classes? There is one class available from the start:
                   8287: @code{object}. You have to use it as ancestor for all classes. It is the
                   8288: only class that has no parent. Classes are also objects, except that
                   8289: they don't have instance variables; class manipulation such as
                   8290: inheritance or changing definitions of a class is handled through
                   8291: selectors of the class @code{object}.
                   8292: 
                   8293: @code{object} provides a number of selectors:
                   8294: 
1.21      crook    8295: @itemize @bullet
                   8296: @item
1.26      crook    8297: @code{class} for subclassing, @code{definitions} to add definitions
                   8298: later on, and @code{class?} to get type informations (is the class a
                   8299: subclass of the class passed on the stack?).
                   8300: doc---object-class
                   8301: doc---object-definitions
                   8302: doc---object-class?
                   8303: 
1.21      crook    8304: @item
1.26      crook    8305: @code{init} and @code{dispose} as constructor and destructor of the
                   8306: object. @code{init} is invocated after the object's memory is allocated,
                   8307: while @code{dispose} also handles deallocation. Thus if you redefine
                   8308: @code{dispose}, you have to call the parent's dispose with @code{super
                   8309: dispose}, too.
                   8310: doc---object-init
                   8311: doc---object-dispose
                   8312: 
1.21      crook    8313: @item
1.26      crook    8314: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   8315: @code{[]} to create named and unnamed objects and object arrays or
                   8316: object pointers.
                   8317: doc---object-new
                   8318: doc---object-new[]
                   8319: doc---object-:
                   8320: doc---object-ptr
                   8321: doc---object-asptr
                   8322: doc---object-[]
1.21      crook    8323: 
1.26      crook    8324: @item
                   8325: @code{::} and @code{super} for explicit scoping. You should use explicit
                   8326: scoping only for super classes or classes with the same set of instance
                   8327: variables. Explicitly-scoped selectors use early binding.
                   8328: doc---object-::
                   8329: doc---object-super
1.21      crook    8330: 
1.26      crook    8331: @item
                   8332: @code{self} to get the address of the object
                   8333: doc---object-self
1.21      crook    8334: 
                   8335: @item
1.26      crook    8336: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   8337: pointers and instance defers.
                   8338: doc---object-bind
                   8339: doc---object-bound
                   8340: doc---object-link
                   8341: doc---object-is
                   8342: 
1.21      crook    8343: @item
1.26      crook    8344: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   8345: form the stack, and @code{postpone} to generate selector invocation code.
                   8346: doc---object-'
                   8347: doc---object-postpone
                   8348: 
1.21      crook    8349: @item
1.26      crook    8350: @code{with} and @code{endwith} to select the active object from the
                   8351: stack, and enable its scope. Using @code{with} and @code{endwith}
                   8352: also allows you to create code using selector @code{postpone} without being
                   8353: trapped by the state-smart objects.
                   8354: doc---object-with
                   8355: doc---object-endwith
                   8356: 
1.21      crook    8357: @end itemize
                   8358: 
1.26      crook    8359: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   8360: @subsubsection Class Declaration
                   8361: @cindex class declaration
                   8362: 
                   8363: @itemize @bullet
                   8364: @item
                   8365: Instance variables
                   8366: doc---oof-var
1.21      crook    8367: 
1.26      crook    8368: @item
                   8369: Object pointers
                   8370: doc---oof-ptr
                   8371: doc---oof-asptr
1.21      crook    8372: 
1.26      crook    8373: @item
                   8374: Instance defers
                   8375: doc---oof-defer
1.21      crook    8376: 
1.26      crook    8377: @item
                   8378: Method selectors
                   8379: doc---oof-early
                   8380: doc---oof-method
1.21      crook    8381: 
1.26      crook    8382: @item
                   8383: Class-wide variables
                   8384: doc---oof-static
1.21      crook    8385: 
1.26      crook    8386: @item
                   8387: End declaration
                   8388: doc---oof-how:
                   8389: doc---oof-class;
1.21      crook    8390: 
1.26      crook    8391: @end itemize
1.21      crook    8392: 
1.26      crook    8393: @c -------------------------------------------------------------
                   8394: @node Class Implementation,  , Class Declaration, OOF
                   8395: @subsubsection Class Implementation
                   8396: @cindex class implementation
1.21      crook    8397: 
1.26      crook    8398: @c -------------------------------------------------------------
                   8399: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   8400: @subsection The @file{mini-oof.fs} model
                   8401: @cindex mini-oof
1.1       anton    8402: 
1.26      crook    8403: Gforth's third object oriented Forth package is a 12-liner. It uses a
                   8404: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
                   8405: and reduces to the bare minimum of features. This is based on a posting
                   8406: of Bernd Paysan in comp.arch.
1.1       anton    8407: 
                   8408: @menu
1.26      crook    8409: * Basic Mini-OOF Usage::
                   8410: * Mini-OOF Example::
                   8411: * Mini-OOF Implementation::
1.1       anton    8412: @end menu
                   8413: 
1.26      crook    8414: @c -------------------------------------------------------------
                   8415: @node Basic Mini-OOF Usage, Mini-OOF Example, , Mini-OOF
                   8416: @subsubsection Basic @file{mini-oof.fs} Usage
                   8417: @cindex mini-oof usage
1.1       anton    8418: 
1.28      crook    8419: There is a base class (@code{class}, which allocates one cell for the
                   8420: object pointer) plus seven other words: to define a method, a variable,
                   8421: a class; to end a class, to resolve binding, to allocate an object and
                   8422: to compile a class method.
1.26      crook    8423: @comment TODO better description of the last one
1.1       anton    8424: 
1.26      crook    8425: doc-object
                   8426: doc-method
                   8427: doc-var
                   8428: doc-class
                   8429: doc-end-class
                   8430: doc-defines
                   8431: doc-new
                   8432: doc-::
1.1       anton    8433: 
1.21      crook    8434: 
1.26      crook    8435: @c -------------------------------------------------------------
                   8436: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   8437: @subsubsection Mini-OOF Example
                   8438: @cindex mini-oof example
1.21      crook    8439: 
1.26      crook    8440: A short example shows how to use this package. This example, in slightly
                   8441: extended form, is supplied as @file{moof-exm.fs}
1.29      crook    8442: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21      crook    8443: 
1.26      crook    8444: @example
                   8445: object class
                   8446:   method init
                   8447:   method draw
                   8448: end-class graphical
                   8449: @end example
1.21      crook    8450: 
1.26      crook    8451: This code defines a class @code{graphical} with an
                   8452: operation @code{draw}.  We can perform the operation
                   8453: @code{draw} on any @code{graphical} object, e.g.:
1.1       anton    8454: 
1.26      crook    8455: @example
                   8456: 100 100 t-rex draw
                   8457: @end example
1.1       anton    8458: 
1.26      crook    8459: where @code{t-rex} is an object or object pointer, created with e.g.
                   8460: @code{graphical new Constant t-rex}.
1.1       anton    8461: 
1.26      crook    8462: For concrete graphical objects, we define child classes of the
                   8463: class @code{graphical}, e.g.:
1.21      crook    8464: 
                   8465: @example
1.26      crook    8466: graphical class
                   8467:   cell var circle-radius
                   8468: end-class circle \ "graphical" is the parent class
1.21      crook    8469: 
1.26      crook    8470: :noname ( x y -- )
                   8471:   circle-radius @@ draw-circle ; circle defines draw
                   8472: :noname ( r -- )
                   8473:   circle-radius ! ; circle defines init
1.21      crook    8474: @end example
                   8475: 
1.26      crook    8476: There is no implicit init method, so we have to define one. The creation
                   8477: code of the object now has to call init explicitely.
1.21      crook    8478: 
1.26      crook    8479: @example
                   8480: circle new Constant my-circle
                   8481: 50 my-circle init
                   8482: @end example
1.21      crook    8483: 
1.26      crook    8484: It is also possible to add a function to create named objects with
                   8485: automatic call of @code{init}, given that all objects have @code{init}
                   8486: on the same place:
1.1       anton    8487: 
                   8488: @example
1.26      crook    8489: : new: ( .. o "name" -- )
                   8490:     new dup Constant init ;
                   8491: 80 circle new: large-circle
1.1       anton    8492: @end example
                   8493: 
1.26      crook    8494: We can draw this new circle at (100,100) with:
1.1       anton    8495: 
                   8496: @example
1.26      crook    8497: 100 100 my-circle draw
1.1       anton    8498: @end example
                   8499: 
1.26      crook    8500: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
                   8501: @subsubsection @file{mini-oof.fs} Implementation
1.1       anton    8502: 
1.26      crook    8503: Object-oriented systems with late binding typically use a
                   8504: ``vtable''-approach: the first variable in each object is a pointer to a
                   8505: table, which contains the methods as function pointers. The vtable
                   8506: may also contain other information.
1.1       anton    8507: 
1.26      crook    8508: So first, let's declare methods:
1.1       anton    8509: 
1.26      crook    8510: @example
                   8511: : method ( m v -- m' v ) Create  over , swap cell+ swap
                   8512:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
                   8513: @end example
1.1       anton    8514: 
1.26      crook    8515: During method declaration, the number of methods and instance
                   8516: variables is on the stack (in address units). @code{method} creates
                   8517: one method and increments the method number. To execute a method, it
                   8518: takes the object, fetches the vtable pointer, adds the offset, and
1.29      crook    8519: executes the @i{xt} stored there. Each method takes the object it is
1.26      crook    8520: invoked from as top of stack parameter. The method itself should
                   8521: consume that object.
1.1       anton    8522: 
1.26      crook    8523: Now, we also have to declare instance variables
1.21      crook    8524: 
1.26      crook    8525: @example
                   8526: : var ( m v size -- m v' ) Create  over , +
                   8527:   DOES> ( o -- addr ) @ + ;
                   8528: @end example
1.21      crook    8529: 
1.26      crook    8530: As before, a word is created with the current offset. Instance
                   8531: variables can have different sizes (cells, floats, doubles, chars), so
                   8532: all we do is take the size and add it to the offset. If your machine
                   8533: has alignment restrictions, put the proper @code{aligned} or
                   8534: @code{faligned} before the variable, to adjust the variable
                   8535: offset. That's why it is on the top of stack.
1.2       jwilke   8536: 
1.26      crook    8537: We need a starting point (the base object) and some syntactic sugar:
1.21      crook    8538: 
1.26      crook    8539: @example
                   8540: Create object  1 cells , 2 cells ,
                   8541: : class ( class -- class methods vars ) dup 2@ ;
                   8542: @end example
1.21      crook    8543: 
1.26      crook    8544: For inheritance, the vtable of the parent object has to be
                   8545: copied when a new, derived class is declared. This gives all the
                   8546: methods of the parent class, which can be overridden, though.
1.21      crook    8547: 
1.2       jwilke   8548: @example
1.26      crook    8549: : end-class  ( class methods vars -- )
                   8550:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   8551:   cell+ dup cell+ r> rot @ 2 cells /string move ;
                   8552: @end example
                   8553: 
                   8554: The first line creates the vtable, initialized with
                   8555: @code{noop}s. The second line is the inheritance mechanism, it
                   8556: copies the xts from the parent vtable.
1.2       jwilke   8557: 
1.26      crook    8558: We still have no way to define new methods, let's do that now:
1.2       jwilke   8559: 
1.26      crook    8560: @example
                   8561: : defines ( xt class -- ) ' >body @ + ! ;
1.2       jwilke   8562: @end example
                   8563: 
1.26      crook    8564: To allocate a new object, we need a word, too:
1.2       jwilke   8565: 
1.26      crook    8566: @example
                   8567: : new ( class -- o )  here over @ allot swap over ! ;
                   8568: @end example
1.2       jwilke   8569: 
1.26      crook    8570: Sometimes derived classes want to access the method of the
                   8571: parent object. There are two ways to achieve this with Mini-OOF:
                   8572: first, you could use named words, and second, you could look up the
                   8573: vtable of the parent object.
1.2       jwilke   8574: 
1.26      crook    8575: @example
                   8576: : :: ( class "name" -- ) ' >body @ + @ compile, ;
                   8577: @end example
1.2       jwilke   8578: 
                   8579: 
1.26      crook    8580: Nothing can be more confusing than a good example, so here is
                   8581: one. First let's declare a text object (called
                   8582: @code{button}), that stores text and position:
1.2       jwilke   8583: 
1.26      crook    8584: @example
                   8585: object class
                   8586:   cell var text
                   8587:   cell var len
                   8588:   cell var x
                   8589:   cell var y
                   8590:   method init
                   8591:   method draw
                   8592: end-class button
                   8593: @end example
1.2       jwilke   8594: 
1.26      crook    8595: @noindent
                   8596: Now, implement the two methods, @code{draw} and @code{init}:
1.2       jwilke   8597: 
1.26      crook    8598: @example
                   8599: :noname ( o -- )
                   8600:  >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
                   8601:  button defines draw
                   8602: :noname ( addr u o -- )
                   8603:  >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
                   8604:  button defines init
                   8605: @end example
1.2       jwilke   8606: 
1.26      crook    8607: @noindent
                   8608: To demonstrate inheritance, we define a class @code{bold-button}, with no
                   8609: new data and no new methods:
1.2       jwilke   8610: 
1.26      crook    8611: @example
                   8612: button class
                   8613: end-class bold-button
1.1       anton    8614: 
1.26      crook    8615: : bold   27 emit ." [1m" ;
                   8616: : normal 27 emit ." [0m" ;
                   8617: @end example
1.1       anton    8618: 
1.26      crook    8619: @noindent
                   8620: The class @code{bold-button} has a different draw method to
                   8621: @code{button}, but the new method is defined in terms of the draw method
                   8622: for @code{button}:
1.1       anton    8623: 
1.26      crook    8624: @example
                   8625: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   8626: @end example
1.1       anton    8627: 
1.26      crook    8628: @noindent
                   8629: Finally, create two objects and apply methods:
1.1       anton    8630: 
1.26      crook    8631: @example
                   8632: button new Constant foo
                   8633: s" thin foo" foo init
                   8634: page
                   8635: foo draw
                   8636: bold-button new Constant bar
                   8637: s" fat bar" bar init
                   8638: 1 bar y !
                   8639: bar draw
                   8640: @end example
1.1       anton    8641: 
                   8642: 
1.26      crook    8643: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
                   8644: @subsubsection Comparison with other object models
                   8645: @cindex comparison of object models
                   8646: @cindex object models, comparison
1.1       anton    8647: 
1.26      crook    8648: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   8649: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   8650: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   8651: relation of the object models described here to two well-known and two
                   8652: closely-related (by the use of method maps) models.
1.1       anton    8653: 
1.26      crook    8654: @cindex Neon model
                   8655: The most popular model currently seems to be the Neon model (see
                   8656: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   8657: 1997) by Andrew McKewan) but this model has a number of limitations
                   8658: @footnote{A longer version of this critique can be
                   8659: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   8660: Dimensions, May 1997) by Anton Ertl.}:
1.1       anton    8661: 
1.26      crook    8662: @itemize @bullet
                   8663: @item
                   8664: It uses a @code{@emph{selector
                   8665: object}} syntax, which makes it unnatural to pass objects on the
                   8666: stack.
1.1       anton    8667: 
1.26      crook    8668: @item
                   8669: It requires that the selector parses the input stream (at
                   8670: compile time); this leads to reduced extensibility and to bugs that are+
                   8671: hard to find.
1.1       anton    8672: 
1.26      crook    8673: @item
                   8674: It allows using every selector to every object;
                   8675: this eliminates the need for classes, but makes it harder to create
                   8676: efficient implementations. 
                   8677: @end itemize
1.1       anton    8678: 
1.26      crook    8679: @cindex Pountain's object-oriented model
                   8680: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   8681: Press, London, 1987) by Dick Pountain. However, it is not really about
                   8682: object-oriented programming, because it hardly deals with late
                   8683: binding. Instead, it focuses on features like information hiding and
                   8684: overloading that are characteristic of modular languages like Ada (83).
1.1       anton    8685: 
1.26      crook    8686: @cindex Zsoter's object-oriented model
                   8687: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1) 1996, pages 31-35)
                   8688: Andras Zsoter describes a model that makes heavy use of an active object
                   8689: (like @code{this} in @file{objects.fs}): The active object is not only
                   8690: used for accessing all fields, but also specifies the receiving object
                   8691: of every selector invocation; you have to change the active object
                   8692: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   8693: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   8694: the method entry point is unnecessary with the Zsoter's model, because
                   8695: the receiving object is the active object already. On the other hand, the explicit
                   8696: change is absolutely necessary in that model, because otherwise no one
                   8697: could ever change the active object. An ANS Forth implementation of this
                   8698: model is available at @url{http://www.forth.org/fig/oopf.html}.
1.1       anton    8699: 
1.26      crook    8700: @cindex @file{oof.fs}, differences to other models
                   8701: The @file{oof.fs} model combines information hiding and overloading
                   8702: resolution (by keeping names in various word lists) with object-oriented
                   8703: programming. It sets the active object implicitly on method entry, but
                   8704: also allows explicit changing (with @code{>o...o>} or with
                   8705: @code{with...endwith}). It uses parsing and state-smart objects and
                   8706: classes for resolving overloading and for early binding: the object or
                   8707: class parses the selector and determines the method from this. If the
                   8708: selector is not parsed by an object or class, it performs a call to the
                   8709: selector for the active object (late binding), like Zsoter's model.
                   8710: Fields are always accessed through the active object. The big
                   8711: disadvantage of this model is the parsing and the state-smartness, which
                   8712: reduces extensibility and increases the opportunities for subtle bugs;
                   8713: essentially, you are only safe if you never tick or @code{postpone} an
                   8714: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1       anton    8715: 
1.26      crook    8716: @cindex @file{mini-oof.fs}, differences to other models
                   8717: The @file{mini-oof.fs} model is quite similar to a very stripped-down version of
                   8718: the @file{objects.fs} model, but syntactically it is a mixture of the @file{objects.fs} and
                   8719: @file{oof.fs} models.
1.1       anton    8720: 
1.26      crook    8721: @c -------------------------------------------------------------
                   8722: @node Passing Commands to the OS, Miscellaneous Words, Object-oriented Forth, Words
1.21      crook    8723: @section Passing Commands to the Operating System
                   8724: @cindex operating system - passing commands
                   8725: @cindex shell commands
                   8726: 
                   8727: Gforth allows you to pass an arbitrary string to the host operating
                   8728: system shell (if such a thing exists) for execution.
                   8729: 
                   8730: doc-sh
                   8731: doc-system
                   8732: doc-$?
1.23      crook    8733: doc-getenv
1.21      crook    8734: 
1.26      crook    8735: @c -------------------------------------------------------------
1.21      crook    8736: @node Miscellaneous Words,  , Passing Commands to the OS, Words
                   8737: @section Miscellaneous Words
                   8738: @cindex miscellaneous words
                   8739: 
1.29      crook    8740: @comment TODO find homes for these
                   8741: 
1.26      crook    8742: These section lists the ANS Forth words that are not documented
1.21      crook    8743: elsewhere in this manual. Ultimately, they all need proper homes.
                   8744: 
                   8745: doc-ms
                   8746: doc-time&date
1.27      crook    8747: 
1.21      crook    8748: doc-[compile]
                   8749: 
1.26      crook    8750: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    8751: (@pxref{ANS conformance}):
1.21      crook    8752: 
                   8753: @code{EDITOR} 
                   8754: @code{EKEY} 
                   8755: @code{EKEY>CHAR} 
                   8756: @code{EKEY?} 
                   8757: @code{EMIT?} 
                   8758: @code{FORGET} 
                   8759: 
1.24      anton    8760: @c ******************************************************************
                   8761: @node Error messages, Tools, Words, Top
                   8762: @chapter Error messages
                   8763: @cindex error messages
                   8764: @cindex backtrace
                   8765: 
                   8766: A typical Gforth error message looks like this:
                   8767: 
                   8768: @example
                   8769: in file included from :-1
                   8770: in file included from ./yyy.fs:1
                   8771: ./xxx.fs:4: Invalid memory address
                   8772: bar
                   8773: ^^^
1.25      anton    8774: $400E664C @@
                   8775: $400E6664 foo
1.24      anton    8776: @end example
                   8777: 
                   8778: The message identifying the error is @code{Invalid memory address}.  The
                   8779: error happened when text-interpreting line 4 of the file
                   8780: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   8781: word on the line where the error happened, is pointed out (with
                   8782: @code{^^^}).
                   8783: 
                   8784: The file containing the error was included in line 1 of @file{./yyy.fs},
                   8785: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   8786: @file{yyy.fs} as command-line parameter to Gforth).
                   8787: 
                   8788: At the end of the error message you find a return stack dump that can be
                   8789: interpreted as a backtrace (possibly empty). On top you find the top of
                   8790: the return stack when the @code{throw} happened, and at the bottom you
                   8791: find the return stack entry just above the return stack of the topmost
                   8792: text interpreter.
                   8793: 
                   8794: To the right of most return stack entries you see a guess for the word
                   8795: that pushed that return stack entry as its return address. This gives a
                   8796: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   8797: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   8798: address} exception).
                   8799: 
                   8800: Note that the backtrace is not perfect: We don't know which return stack
                   8801: entries are return addresses (so we may get false positives); and in
                   8802: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   8803: address the word that pushed the return address, so for some return
                   8804: addresses you see no names in the return stack dump.
1.25      anton    8805: 
                   8806: @cindex @code{catch} and backtraces
                   8807: The return stack dump represents the return stack at the time when a
                   8808: specific @code{throw} was executed.  In programs that make use of
                   8809: @code{catch}, it is not necessarily clear which @code{throw} should be
                   8810: used for the return stack dump (e.g., consider one @code{throw} that
                   8811: indicates an error, which is caught, and during recovery another error
                   8812: happens; which @code{throw} should be used for the stack dump).  Gforth
                   8813: presents the return stack dump for the first @code{throw} after the last
                   8814: executed (not returned-to) @code{catch}; this works well in the usual
                   8815: case.
                   8816: 
                   8817: @cindex @code{gforth-fast} and backtraces
                   8818: @cindex @code{gforth-fast}, difference from @code{gforth}
                   8819: @cindex backtraces with @code{gforth-fast}
                   8820: @cindex return stack dump with @code{gforth-fast}
                   8821: @code{gforth} is able to do a return stack dump for throws generated
                   8822: from primitives (e.g., invalid memory address, stack empty etc.);
                   8823: @code{gforth-fast} is only able to do a return stack dump from a
                   8824: directly called @code{throw} (including @code{abort} etc.).  This is the
1.30      anton    8825: only difference (apart from a speed factor of between 1.15 (K6-2) and
                   8826: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}.  Given an
                   8827: exception caused by a primitive in @code{gforth-fast}, you will
                   8828: typically see no return stack dump at all; however, if the exception is
                   8829: caught by @code{catch} (e.g., for restoring some state), and then
                   8830: @code{throw}n again, the return stack dump will be for the first such
                   8831: @code{throw}.
1.2       jwilke   8832: 
1.5       anton    8833: @c ******************************************************************
1.24      anton    8834: @node Tools, ANS conformance, Error messages, Top
1.1       anton    8835: @chapter Tools
                   8836: 
                   8837: @menu
                   8838: * ANS Report::                  Report the words used, sorted by wordset.
                   8839: @end menu
                   8840: 
                   8841: See also @ref{Emacs and Gforth}.
                   8842: 
                   8843: @node ANS Report,  , Tools, Tools
                   8844: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   8845: @cindex @file{ans-report.fs}
                   8846: @cindex report the words used in your program
                   8847: @cindex words used in your program
                   8848: 
                   8849: If you want to label a Forth program as ANS Forth Program, you must
                   8850: document which wordsets the program uses; for extension wordsets, it is
                   8851: helpful to list the words the program requires from these wordsets
                   8852: (because Forth systems are allowed to provide only some words of them).
                   8853: 
                   8854: The @file{ans-report.fs} tool makes it easy for you to determine which
                   8855: words from which wordset and which non-ANS words your application
                   8856: uses. You simply have to include @file{ans-report.fs} before loading the
                   8857: program you want to check. After loading your program, you can get the
                   8858: report with @code{print-ans-report}. A typical use is to run this as
                   8859: batch job like this:
                   8860: @example
                   8861: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   8862: @end example
                   8863: 
                   8864: The output looks like this (for @file{compat/control.fs}):
                   8865: @example
                   8866: The program uses the following words
                   8867: from CORE :
                   8868: : POSTPONE THEN ; immediate ?dup IF 0= 
                   8869: from BLOCK-EXT :
                   8870: \ 
                   8871: from FILE :
                   8872: ( 
                   8873: @end example
                   8874: 
                   8875: @subsection Caveats
                   8876: 
                   8877: Note that @file{ans-report.fs} just checks which words are used, not whether
                   8878: they are used in an ANS Forth conforming way!
                   8879: 
                   8880: Some words are defined in several wordsets in the
                   8881: standard. @file{ans-report.fs} reports them for only one of the
                   8882: wordsets, and not necessarily the one you expect. It depends on usage
                   8883: which wordset is the right one to specify. E.g., if you only use the
                   8884: compilation semantics of @code{S"}, it is a Core word; if you also use
                   8885: its interpretation semantics, it is a File word.
                   8886: 
                   8887: @c ******************************************************************
                   8888: @node ANS conformance, Model, Tools, Top
                   8889: @chapter ANS conformance
                   8890: @cindex ANS conformance of Gforth
                   8891: 
                   8892: To the best of our knowledge, Gforth is an
                   8893: 
                   8894: ANS Forth System
                   8895: @itemize @bullet
                   8896: @item providing the Core Extensions word set
                   8897: @item providing the Block word set
                   8898: @item providing the Block Extensions word set
                   8899: @item providing the Double-Number word set
                   8900: @item providing the Double-Number Extensions word set
                   8901: @item providing the Exception word set
                   8902: @item providing the Exception Extensions word set
                   8903: @item providing the Facility word set
                   8904: @item providing @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
                   8905: @item providing the File Access word set
                   8906: @item providing the File Access Extensions word set
                   8907: @item providing the Floating-Point word set
                   8908: @item providing the Floating-Point Extensions word set
                   8909: @item providing the Locals word set
                   8910: @item providing the Locals Extensions word set
                   8911: @item providing the Memory-Allocation word set
                   8912: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   8913: @item providing the Programming-Tools word set
                   8914: @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
                   8915: @item providing the Search-Order word set
                   8916: @item providing the Search-Order Extensions word set
                   8917: @item providing the String word set
                   8918: @item providing the String Extensions word set (another easy one)
                   8919: @end itemize
                   8920: 
                   8921: @cindex system documentation
                   8922: In addition, ANS Forth systems are required to document certain
                   8923: implementation choices. This chapter tries to meet these
                   8924: requirements. In many cases it gives a way to ask the system for the
                   8925: information instead of providing the information directly, in
                   8926: particular, if the information depends on the processor, the operating
                   8927: system or the installation options chosen, or if they are likely to
                   8928: change during the maintenance of Gforth.
                   8929: 
                   8930: @comment The framework for the rest has been taken from pfe.
                   8931: 
                   8932: @menu
                   8933: * The Core Words::              
                   8934: * The optional Block word set::  
                   8935: * The optional Double Number word set::  
                   8936: * The optional Exception word set::  
                   8937: * The optional Facility word set::  
                   8938: * The optional File-Access word set::  
                   8939: * The optional Floating-Point word set::  
                   8940: * The optional Locals word set::  
                   8941: * The optional Memory-Allocation word set::  
                   8942: * The optional Programming-Tools word set::  
                   8943: * The optional Search-Order word set::  
                   8944: @end menu
                   8945: 
                   8946: 
                   8947: @c =====================================================================
                   8948: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   8949: @comment  node-name,  next,  previous,  up
                   8950: @section The Core Words
                   8951: @c =====================================================================
                   8952: @cindex core words, system documentation
                   8953: @cindex system documentation, core words
                   8954: 
                   8955: @menu
                   8956: * core-idef::                   Implementation Defined Options                   
                   8957: * core-ambcond::                Ambiguous Conditions                
                   8958: * core-other::                  Other System Documentation                  
                   8959: @end menu
                   8960: 
                   8961: @c ---------------------------------------------------------------------
                   8962: @node core-idef, core-ambcond, The Core Words, The Core Words
                   8963: @subsection Implementation Defined Options
                   8964: @c ---------------------------------------------------------------------
                   8965: @cindex core words, implementation-defined options
                   8966: @cindex implementation-defined options, core words
                   8967: 
                   8968: 
                   8969: @table @i
                   8970: @item (Cell) aligned addresses:
                   8971: @cindex cell-aligned addresses
                   8972: @cindex aligned addresses
                   8973: processor-dependent. Gforth's alignment words perform natural alignment
                   8974: (e.g., an address aligned for a datum of size 8 is divisible by
                   8975: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   8976: 
                   8977: @item @code{EMIT} and non-graphic characters:
                   8978: @cindex @code{EMIT} and non-graphic characters
                   8979: @cindex non-graphic characters and @code{EMIT}
                   8980: The character is output using the C library function (actually, macro)
                   8981: @code{putc}.
                   8982: 
                   8983: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   8984: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   8985: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   8986: @cindex @code{ACCEPT}, editing
                   8987: @cindex @code{EXPECT}, editing
                   8988: This is modeled on the GNU readline library (@pxref{Readline
                   8989: Interaction, , Command Line Editing, readline, The GNU Readline
                   8990: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   8991: producing a full word completion every time you type it (instead of
1.28      crook    8992: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    8993: 
                   8994: @item character set:
                   8995: @cindex character set
                   8996: The character set of your computer and display device. Gforth is
                   8997: 8-bit-clean (but some other component in your system may make trouble).
                   8998: 
                   8999: @item Character-aligned address requirements:
                   9000: @cindex character-aligned address requirements
                   9001: installation-dependent. Currently a character is represented by a C
                   9002: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   9003: (Comments on that requested).
                   9004: 
                   9005: @item character-set extensions and matching of names:
                   9006: @cindex character-set extensions and matching of names
1.26      crook    9007: @cindex case-sensitivity for name lookup
                   9008: @cindex name lookup, case-sensitivity
                   9009: @cindex locale and case-sensitivity
1.21      crook    9010: Any character except the ASCII NUL character can be used in a
1.1       anton    9011: name. Matching is case-insensitive (except in @code{TABLE}s). The
                   9012: matching is performed using the C function @code{strncasecmp}, whose
                   9013: function is probably influenced by the locale. E.g., the @code{C} locale
                   9014: does not know about accents and umlauts, so they are matched
                   9015: case-sensitively in that locale. For portability reasons it is best to
                   9016: write programs such that they work in the @code{C} locale. Then one can
                   9017: use libraries written by a Polish programmer (who might use words
                   9018: containing ISO Latin-2 encoded characters) and by a French programmer
                   9019: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   9020: funny results for some of the words (which ones, depends on the font you
                   9021: are using)). Also, the locale you prefer may not be available in other
                   9022: operating systems. Hopefully, Unicode will solve these problems one day.
                   9023: 
                   9024: @item conditions under which control characters match a space delimiter:
                   9025: @cindex space delimiters
                   9026: @cindex control characters as delimiters
                   9027: If @code{WORD} is called with the space character as a delimiter, all
                   9028: white-space characters (as identified by the C macro @code{isspace()})
                   9029: are delimiters. @code{PARSE}, on the other hand, treats space like other
                   9030: delimiters. @code{PARSE-WORD} treats space like @code{WORD}, but behaves
                   9031: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
                   9032: interpreter (aka text interpreter) by default, treats all white-space
                   9033: characters as delimiters.
                   9034: 
1.26      crook    9035: @item format of the control-flow stack:
                   9036: @cindex control-flow stack, format
                   9037: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    9038: stack item in cells is given by the constant @code{cs-item-size}. At the
                   9039: time of this writing, an item consists of a (pointer to a) locals list
                   9040: (third), an address in the code (second), and a tag for identifying the
                   9041: item (TOS). The following tags are used: @code{defstart},
                   9042: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   9043: @code{scopestart}.
                   9044: 
                   9045: @item conversion of digits > 35
                   9046: @cindex digits > 35
                   9047: The characters @code{[\]^_'} are the digits with the decimal value
                   9048: 36@minus{}41. There is no way to input many of the larger digits.
                   9049: 
                   9050: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   9051: @cindex @code{EXPECT}, display after end of input
                   9052: @cindex @code{ACCEPT}, display after end of input
                   9053: The cursor is moved to the end of the entered string. If the input is
                   9054: terminated using the @kbd{Return} key, a space is typed.
                   9055: 
                   9056: @item exception abort sequence of @code{ABORT"}:
                   9057: @cindex exception abort sequence of @code{ABORT"}
                   9058: @cindex @code{ABORT"}, exception abort sequence
                   9059: The error string is stored into the variable @code{"error} and a
                   9060: @code{-2 throw} is performed.
                   9061: 
                   9062: @item input line terminator:
                   9063: @cindex input line terminator
                   9064: @cindex line terminator on input
1.26      crook    9065: @cindex newline character on input
1.1       anton    9066: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   9067: lines. One of these characters is typically produced when you type the
                   9068: @kbd{Enter} or @kbd{Return} key.
                   9069: 
                   9070: @item maximum size of a counted string:
                   9071: @cindex maximum size of a counted string
                   9072: @cindex counted string, maximum size
                   9073: @code{s" /counted-string" environment? drop .}. Currently 255 characters
                   9074: on all ports, but this may change.
                   9075: 
                   9076: @item maximum size of a parsed string:
                   9077: @cindex maximum size of a parsed string
                   9078: @cindex parsed string, maximum size
                   9079: Given by the constant @code{/line}. Currently 255 characters.
                   9080: 
                   9081: @item maximum size of a definition name, in characters:
                   9082: @cindex maximum size of a definition name, in characters
                   9083: @cindex name, maximum length
                   9084: 31
                   9085: 
                   9086: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   9087: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   9088: @cindex @code{ENVIRONMENT?} string length, maximum
                   9089: 31
                   9090: 
                   9091: @item method of selecting the user input device:
                   9092: @cindex user input device, method of selecting
                   9093: The user input device is the standard input. There is currently no way to
                   9094: change it from within Gforth. However, the input can typically be
                   9095: redirected in the command line that starts Gforth.
                   9096: 
                   9097: @item method of selecting the user output device:
                   9098: @cindex user output device, method of selecting
                   9099: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    9100: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   9101: output when the user output device is a terminal, otherwise the output
                   9102: is buffered.
1.1       anton    9103: 
                   9104: @item methods of dictionary compilation:
                   9105: What are we expected to document here?
                   9106: 
                   9107: @item number of bits in one address unit:
                   9108: @cindex number of bits in one address unit
                   9109: @cindex address unit, size in bits
                   9110: @code{s" address-units-bits" environment? drop .}. 8 in all current
                   9111: ports.
                   9112: 
                   9113: @item number representation and arithmetic:
                   9114: @cindex number representation and arithmetic
                   9115: Processor-dependent. Binary two's complement on all current ports.
                   9116: 
                   9117: @item ranges for integer types:
                   9118: @cindex ranges for integer types
                   9119: @cindex integer types, ranges
                   9120: Installation-dependent. Make environmental queries for @code{MAX-N},
                   9121: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   9122: unsigned (and positive) types is 0. The lower bound for signed types on
                   9123: two's complement and one's complement machines machines can be computed
                   9124: by adding 1 to the upper bound.
                   9125: 
                   9126: @item read-only data space regions:
                   9127: @cindex read-only data space regions
                   9128: @cindex data-space, read-only regions
                   9129: The whole Forth data space is writable.
                   9130: 
                   9131: @item size of buffer at @code{WORD}:
                   9132: @cindex size of buffer at @code{WORD}
                   9133: @cindex @code{WORD} buffer size
                   9134: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   9135: shared with the pictured numeric output string. If overwriting
                   9136: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   9137: space, although only as much can be sensibly used as fits in a counted
                   9138: string.
                   9139: 
                   9140: @item size of one cell in address units:
                   9141: @cindex cell size
                   9142: @code{1 cells .}.
                   9143: 
                   9144: @item size of one character in address units:
                   9145: @cindex char size
                   9146: @code{1 chars .}. 1 on all current ports.
                   9147: 
                   9148: @item size of the keyboard terminal buffer:
                   9149: @cindex size of the keyboard terminal buffer
                   9150: @cindex terminal buffer, size
                   9151: Varies. You can determine the size at a specific time using @code{lp@@
                   9152: tib - .}. It is shared with the locals stack and TIBs of files that
                   9153: include the current file. You can change the amount of space for TIBs
                   9154: and locals stack at Gforth startup with the command line option
                   9155: @code{-l}.
                   9156: 
                   9157: @item size of the pictured numeric output buffer:
                   9158: @cindex size of the pictured numeric output buffer
                   9159: @cindex pictured numeric output buffer, size
                   9160: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   9161: shared with @code{WORD}.
                   9162: 
                   9163: @item size of the scratch area returned by @code{PAD}:
                   9164: @cindex size of the scratch area returned by @code{PAD}
                   9165: @cindex @code{PAD} size
                   9166: The remainder of dictionary space. @code{unused pad here - - .}.
                   9167: 
                   9168: @item system case-sensitivity characteristics:
                   9169: @cindex case-sensitivity characteristics
1.26      crook    9170: Dictionary searches are case-insensitive (except in
1.1       anton    9171: @code{TABLE}s). However, as explained above under @i{character-set
                   9172: extensions}, the matching for non-ASCII characters is determined by the
                   9173: locale you are using. In the default @code{C} locale all non-ASCII
                   9174: characters are matched case-sensitively.
                   9175: 
                   9176: @item system prompt:
                   9177: @cindex system prompt
                   9178: @cindex prompt
                   9179: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   9180: 
                   9181: @item division rounding:
                   9182: @cindex division rounding
                   9183: installation dependent. @code{s" floored" environment? drop .}. We leave
                   9184: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
                   9185: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
                   9186: 
                   9187: @item values of @code{STATE} when true:
                   9188: @cindex @code{STATE} values
                   9189: -1.
                   9190: 
                   9191: @item values returned after arithmetic overflow:
                   9192: On two's complement machines, arithmetic is performed modulo
                   9193: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   9194: arithmetic (with appropriate mapping for signed types). Division by zero
                   9195: typically results in a @code{-55 throw} (Floating-point unidentified
                   9196: fault), although a @code{-10 throw} (divide by zero) would be more
                   9197: appropriate.
                   9198: 
                   9199: @item whether the current definition can be found after @t{DOES>}:
                   9200: @cindex @t{DOES>}, visibility of current definition
                   9201: No.
                   9202: 
                   9203: @end table
                   9204: 
                   9205: @c ---------------------------------------------------------------------
                   9206: @node core-ambcond, core-other, core-idef, The Core Words
                   9207: @subsection Ambiguous conditions
                   9208: @c ---------------------------------------------------------------------
                   9209: @cindex core words, ambiguous conditions
                   9210: @cindex ambiguous conditions, core words
                   9211: 
                   9212: @table @i
                   9213: 
                   9214: @item a name is neither a word nor a number:
                   9215: @cindex name not found
1.26      crook    9216: @cindex undefined word
1.1       anton    9217: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
                   9218: preserves the data and FP stack, so you don't lose more work than
                   9219: necessary.
                   9220: 
                   9221: @item a definition name exceeds the maximum length allowed:
1.26      crook    9222: @cindex word name too long
1.1       anton    9223: @code{-19 throw} (Word name too long)
                   9224: 
                   9225: @item addressing a region not inside the various data spaces of the forth system:
                   9226: @cindex Invalid memory address
1.32      anton    9227: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    9228: typically readable. Accessing other addresses gives results dependent on
                   9229: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   9230: address).
                   9231: 
                   9232: @item argument type incompatible with parameter:
1.26      crook    9233: @cindex argument type mismatch
1.1       anton    9234: This is usually not caught. Some words perform checks, e.g., the control
                   9235: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   9236: mismatch).
                   9237: 
                   9238: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   9239: @cindex Interpreting a compile-only word, for @code{'} etc.
                   9240: @cindex execution token of words with undefined execution semantics
                   9241: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   9242: get an execution token for @code{compile-only-error} (which performs a
                   9243: @code{-14 throw} when executed).
                   9244: 
                   9245: @item dividing by zero:
                   9246: @cindex dividing by zero
                   9247: @cindex floating point unidentified fault, integer division
1.24      anton    9248: On better platforms, this produces a @code{-10 throw} (Division by
                   9249: zero); on other systems, this typically results in a @code{-55 throw}
                   9250: (Floating-point unidentified fault).
1.1       anton    9251: 
                   9252: @item insufficient data stack or return stack space:
                   9253: @cindex insufficient data stack or return stack space
                   9254: @cindex stack overflow
1.26      crook    9255: @cindex address alignment exception, stack overflow
1.1       anton    9256: @cindex Invalid memory address, stack overflow
                   9257: Depending on the operating system, the installation, and the invocation
                   9258: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    9259: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   9260: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   9261: throw} (Invalid memory address) (depending on the platform and how you
                   9262: achieved the overflow) as soon as the overflow happens. If it is not
                   9263: checked, overflows typically result in mysterious illegal memory
                   9264: accesses, producing @code{-9 throw} (Invalid memory address) or
                   9265: @code{-23 throw} (Address alignment exception); they might also destroy
                   9266: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   9267: various errors in these words.
1.1       anton    9268: 
                   9269: @item insufficient space for loop control parameters:
                   9270: @cindex insufficient space for loop control parameters
                   9271: like other return stack overflows.
                   9272: 
                   9273: @item insufficient space in the dictionary:
                   9274: @cindex insufficient space in the dictionary
                   9275: @cindex dictionary overflow
1.12      anton    9276: If you try to allot (either directly with @code{allot}, or indirectly
                   9277: with @code{,}, @code{create} etc.) more memory than available in the
                   9278: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   9279: to access memory beyond the end of the dictionary, the results are
                   9280: similar to stack overflows.
1.1       anton    9281: 
                   9282: @item interpreting a word with undefined interpretation semantics:
                   9283: @cindex interpreting a word with undefined interpretation semantics
                   9284: @cindex Interpreting a compile-only word
                   9285: For some words, we have defined interpretation semantics. For the
                   9286: others: @code{-14 throw} (Interpreting a compile-only word).
                   9287: 
                   9288: @item modifying the contents of the input buffer or a string literal:
                   9289: @cindex modifying the contents of the input buffer or a string literal
                   9290: These are located in writable memory and can be modified.
                   9291: 
                   9292: @item overflow of the pictured numeric output string:
                   9293: @cindex overflow of the pictured numeric output string
                   9294: @cindex pictured numeric output string, overflow
1.24      anton    9295: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    9296: 
                   9297: @item parsed string overflow:
                   9298: @cindex parsed string overflow
                   9299: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   9300: 
                   9301: @item producing a result out of range:
                   9302: @cindex result out of range
                   9303: On two's complement machines, arithmetic is performed modulo
                   9304: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   9305: arithmetic (with appropriate mapping for signed types). Division by zero
1.24      anton    9306: typically results in a @code{-10 throw} (divide by zero) or @code{-55
                   9307: throw} (floating point unidentified fault). @code{convert} and
                   9308: @code{>number} currently overflow silently.
1.1       anton    9309: 
                   9310: @item reading from an empty data or return stack:
                   9311: @cindex stack empty
                   9312: @cindex stack underflow
1.24      anton    9313: @cindex return stack underflow
1.1       anton    9314: The data stack is checked by the outer (aka text) interpreter after
                   9315: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   9316: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    9317: depending on operating system, installation, and invocation. If they are
                   9318: caught by a check, they typically result in @code{-4 throw} (Stack
                   9319: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   9320: (Invalid memory address), depending on the platform and which stack
                   9321: underflows and by how much. Note that even if the system uses checking
                   9322: (through the MMU), your program may have to underflow by a significant
                   9323: number of stack items to trigger the reaction (the reason for this is
                   9324: that the MMU, and therefore the checking, works with a page-size
                   9325: granularity).  If there is no checking, the symptoms resulting from an
                   9326: underflow are similar to those from an overflow.  Unbalanced return
                   9327: stack errors result in a variaty of symptoms, including @code{-9 throw}
                   9328: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   9329: throw}).
1.1       anton    9330: 
                   9331: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   9332: @cindex unexpected end of the input buffer
                   9333: @cindex zero-length string as a name
                   9334: @cindex Attempt to use zero-length string as a name
                   9335: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   9336: use zero-length string as a name). Words like @code{'} probably will not
                   9337: find what they search. Note that it is possible to create zero-length
                   9338: names with @code{nextname} (should it not?).
                   9339: 
                   9340: @item @code{>IN} greater than input buffer:
                   9341: @cindex @code{>IN} greater than input buffer
                   9342: The next invocation of a parsing word returns a string with length 0.
                   9343: 
                   9344: @item @code{RECURSE} appears after @code{DOES>}:
                   9345: @cindex @code{RECURSE} appears after @code{DOES>}
                   9346: Compiles a recursive call to the defining word, not to the defined word.
                   9347: 
                   9348: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   9349: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    9350: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    9351: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   9352: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   9353: the end of the file was reached), its source-id may be
                   9354: reused. Therefore, restoring an input source specification referencing a
                   9355: closed file may lead to unpredictable results instead of a @code{-12
                   9356: THROW}.
                   9357: 
                   9358: In the future, Gforth may be able to restore input source specifications
                   9359: from other than the current input source.
                   9360: 
                   9361: @item data space containing definitions gets de-allocated:
                   9362: @cindex data space containing definitions gets de-allocated
                   9363: Deallocation with @code{allot} is not checked. This typically results in
                   9364: memory access faults or execution of illegal instructions.
                   9365: 
                   9366: @item data space read/write with incorrect alignment:
                   9367: @cindex data space read/write with incorrect alignment
                   9368: @cindex alignment faults
1.26      crook    9369: @cindex address alignment exception
1.1       anton    9370: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    9371: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    9372: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   9373: (Invalid memory address). There are reportedly some processors with
1.12      anton    9374: alignment restrictions that do not report violations.
1.1       anton    9375: 
                   9376: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   9377: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   9378: Like other alignment errors.
                   9379: 
                   9380: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   9381: Like other stack underflows.
                   9382: 
                   9383: @item loop control parameters not available:
                   9384: @cindex loop control parameters not available
                   9385: Not checked. The counted loop words simply assume that the top of return
                   9386: stack items are loop control parameters and behave accordingly.
                   9387: 
                   9388: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   9389: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   9390: @cindex last word was headerless
                   9391: @code{abort" last word was headerless"}.
                   9392: 
                   9393: @item name not defined by @code{VALUE} used by @code{TO}:
                   9394: @cindex name not defined by @code{VALUE} used by @code{TO}
                   9395: @cindex @code{TO} on non-@code{VALUE}s
                   9396: @cindex Invalid name argument, @code{TO}
                   9397: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   9398: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   9399: 
                   9400: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   9401: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    9402: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    9403: @code{-13 throw} (Undefined word)
                   9404: 
                   9405: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   9406: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   9407: Gforth behaves as if they were of the same type. I.e., you can predict
                   9408: the behaviour by interpreting all parameters as, e.g., signed.
                   9409: 
                   9410: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   9411: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   9412: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   9413: compilation semantics of @code{TO}.
                   9414: 
                   9415: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    9416: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    9417: @cindex @code{WORD}, string overflow
                   9418: Not checked. The string will be ok, but the count will, of course,
                   9419: contain only the least significant bits of the length.
                   9420: 
                   9421: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   9422: @cindex @code{LSHIFT}, large shift counts
                   9423: @cindex @code{RSHIFT}, large shift counts
                   9424: Processor-dependent. Typical behaviours are returning 0 and using only
                   9425: the low bits of the shift count.
                   9426: 
                   9427: @item word not defined via @code{CREATE}:
                   9428: @cindex @code{>BODY} of non-@code{CREATE}d words
                   9429: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   9430: 
                   9431: @cindex @code{DOES>} of non-@code{CREATE}d words
                   9432: @code{DOES>} changes the execution semantics of the last defined word no
                   9433: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   9434: @code{CREATE , DOES>}.
                   9435: 
                   9436: @item words improperly used outside @code{<#} and @code{#>}:
                   9437: Not checked. As usual, you can expect memory faults.
                   9438: 
                   9439: @end table
                   9440: 
                   9441: 
                   9442: @c ---------------------------------------------------------------------
                   9443: @node core-other,  , core-ambcond, The Core Words
                   9444: @subsection Other system documentation
                   9445: @c ---------------------------------------------------------------------
                   9446: @cindex other system documentation, core words
                   9447: @cindex core words, other system documentation
                   9448: 
                   9449: @table @i
                   9450: @item nonstandard words using @code{PAD}:
                   9451: @cindex @code{PAD} use by nonstandard words
                   9452: None.
                   9453: 
                   9454: @item operator's terminal facilities available:
                   9455: @cindex operator's terminal facilities available
                   9456: After processing the command line, Gforth goes into interactive mode,
                   9457: and you can give commands to Gforth interactively. The actual facilities
                   9458: available depend on how you invoke Gforth.
                   9459: 
                   9460: @item program data space available:
                   9461: @cindex program data space available
                   9462: @cindex data space available
                   9463: @code{UNUSED .} gives the remaining dictionary space. The total
                   9464: dictionary space can be specified with the @code{-m} switch
                   9465: (@pxref{Invoking Gforth}) when Gforth starts up.
                   9466: 
                   9467: @item return stack space available:
                   9468: @cindex return stack space available
                   9469: You can compute the total return stack space in cells with
                   9470: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   9471: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   9472: 
                   9473: @item stack space available:
                   9474: @cindex stack space available
                   9475: You can compute the total data stack space in cells with
                   9476: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   9477: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   9478: 
                   9479: @item system dictionary space required, in address units:
                   9480: @cindex system dictionary space required, in address units
                   9481: Type @code{here forthstart - .} after startup. At the time of this
                   9482: writing, this gives 80080 (bytes) on a 32-bit system.
                   9483: @end table
                   9484: 
                   9485: 
                   9486: @c =====================================================================
                   9487: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   9488: @section The optional Block word set
                   9489: @c =====================================================================
                   9490: @cindex system documentation, block words
                   9491: @cindex block words, system documentation
                   9492: 
                   9493: @menu
                   9494: * block-idef::                  Implementation Defined Options
                   9495: * block-ambcond::               Ambiguous Conditions               
                   9496: * block-other::                 Other System Documentation                 
                   9497: @end menu
                   9498: 
                   9499: 
                   9500: @c ---------------------------------------------------------------------
                   9501: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   9502: @subsection Implementation Defined Options
                   9503: @c ---------------------------------------------------------------------
                   9504: @cindex implementation-defined options, block words
                   9505: @cindex block words, implementation-defined options
                   9506: 
                   9507: @table @i
                   9508: @item the format for display by @code{LIST}:
                   9509: @cindex @code{LIST} display format
                   9510: First the screen number is displayed, then 16 lines of 64 characters,
                   9511: each line preceded by the line number.
                   9512: 
                   9513: @item the length of a line affected by @code{\}:
                   9514: @cindex length of a line affected by @code{\}
                   9515: @cindex @code{\}, line length in blocks
                   9516: 64 characters.
                   9517: @end table
                   9518: 
                   9519: 
                   9520: @c ---------------------------------------------------------------------
                   9521: @node block-ambcond, block-other, block-idef, The optional Block word set
                   9522: @subsection Ambiguous conditions
                   9523: @c ---------------------------------------------------------------------
                   9524: @cindex block words, ambiguous conditions
                   9525: @cindex ambiguous conditions, block words
                   9526: 
                   9527: @table @i
                   9528: @item correct block read was not possible:
                   9529: @cindex block read not possible
                   9530: Typically results in a @code{throw} of some OS-derived value (between
                   9531: -512 and -2048). If the blocks file was just not long enough, blanks are
                   9532: supplied for the missing portion.
                   9533: 
                   9534: @item I/O exception in block transfer:
                   9535: @cindex I/O exception in block transfer
                   9536: @cindex block transfer, I/O exception
                   9537: Typically results in a @code{throw} of some OS-derived value (between
                   9538: -512 and -2048).
                   9539: 
                   9540: @item invalid block number:
                   9541: @cindex invalid block number
                   9542: @cindex block number invalid
                   9543: @code{-35 throw} (Invalid block number)
                   9544: 
                   9545: @item a program directly alters the contents of @code{BLK}:
                   9546: @cindex @code{BLK}, altering @code{BLK}
                   9547: The input stream is switched to that other block, at the same
                   9548: position. If the storing to @code{BLK} happens when interpreting
                   9549: non-block input, the system will get quite confused when the block ends.
                   9550: 
                   9551: @item no current block buffer for @code{UPDATE}:
                   9552: @cindex @code{UPDATE}, no current block buffer
                   9553: @code{UPDATE} has no effect.
                   9554: 
                   9555: @end table
                   9556: 
                   9557: @c ---------------------------------------------------------------------
                   9558: @node block-other,  , block-ambcond, The optional Block word set
                   9559: @subsection Other system documentation
                   9560: @c ---------------------------------------------------------------------
                   9561: @cindex other system documentation, block words
                   9562: @cindex block words, other system documentation
                   9563: 
                   9564: @table @i
                   9565: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   9566: No restrictions (yet).
                   9567: 
                   9568: @item the number of blocks available for source and data:
                   9569: depends on your disk space.
                   9570: 
                   9571: @end table
                   9572: 
                   9573: 
                   9574: @c =====================================================================
                   9575: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   9576: @section The optional Double Number word set
                   9577: @c =====================================================================
                   9578: @cindex system documentation, double words
                   9579: @cindex double words, system documentation
                   9580: 
                   9581: @menu
                   9582: * double-ambcond::              Ambiguous Conditions              
                   9583: @end menu
                   9584: 
                   9585: 
                   9586: @c ---------------------------------------------------------------------
                   9587: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   9588: @subsection Ambiguous conditions
                   9589: @c ---------------------------------------------------------------------
                   9590: @cindex double words, ambiguous conditions
                   9591: @cindex ambiguous conditions, double words
                   9592: 
                   9593: @table @i
1.29      crook    9594: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   9595: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   9596: The least significant cell of @i{d} is produced.
1.1       anton    9597: 
                   9598: @end table
                   9599: 
                   9600: 
                   9601: @c =====================================================================
                   9602: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   9603: @section The optional Exception word set
                   9604: @c =====================================================================
                   9605: @cindex system documentation, exception words
                   9606: @cindex exception words, system documentation
                   9607: 
                   9608: @menu
                   9609: * exception-idef::              Implementation Defined Options              
                   9610: @end menu
                   9611: 
                   9612: 
                   9613: @c ---------------------------------------------------------------------
                   9614: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   9615: @subsection Implementation Defined Options
                   9616: @c ---------------------------------------------------------------------
                   9617: @cindex implementation-defined options, exception words
                   9618: @cindex exception words, implementation-defined options
                   9619: 
                   9620: @table @i
                   9621: @item @code{THROW}-codes used in the system:
                   9622: @cindex @code{THROW}-codes used in the system
                   9623: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    9624: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    9625: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   9626: allocation operations). The mapping from OS error numbers to throw codes
                   9627: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   9628: undefined OS errors produce a message with a strange number; e.g.,
                   9629: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   9630: @end table
                   9631: 
                   9632: @c =====================================================================
                   9633: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   9634: @section The optional Facility word set
                   9635: @c =====================================================================
                   9636: @cindex system documentation, facility words
                   9637: @cindex facility words, system documentation
                   9638: 
                   9639: @menu
                   9640: * facility-idef::               Implementation Defined Options               
                   9641: * facility-ambcond::            Ambiguous Conditions            
                   9642: @end menu
                   9643: 
                   9644: 
                   9645: @c ---------------------------------------------------------------------
                   9646: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   9647: @subsection Implementation Defined Options
                   9648: @c ---------------------------------------------------------------------
                   9649: @cindex implementation-defined options, facility words
                   9650: @cindex facility words, implementation-defined options
                   9651: 
                   9652: @table @i
                   9653: @item encoding of keyboard events (@code{EKEY}):
                   9654: @cindex keyboard events, encoding in @code{EKEY}
                   9655: @cindex @code{EKEY}, encoding of keyboard events
                   9656: Not yet implemented.
                   9657: 
                   9658: @item duration of a system clock tick:
                   9659: @cindex duration of a system clock tick
                   9660: @cindex clock tick duration
                   9661: System dependent. With respect to @code{MS}, the time is specified in
                   9662: microseconds. How well the OS and the hardware implement this, is
                   9663: another question.
                   9664: 
                   9665: @item repeatability to be expected from the execution of @code{MS}:
                   9666: @cindex repeatability to be expected from the execution of @code{MS}
                   9667: @cindex @code{MS}, repeatability to be expected
                   9668: System dependent. On Unix, a lot depends on load. If the system is
                   9669: lightly loaded, and the delay is short enough that Gforth does not get
                   9670: swapped out, the performance should be acceptable. Under MS-DOS and
                   9671: other single-tasking systems, it should be good.
                   9672: 
                   9673: @end table
                   9674: 
                   9675: 
                   9676: @c ---------------------------------------------------------------------
                   9677: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   9678: @subsection Ambiguous conditions
                   9679: @c ---------------------------------------------------------------------
                   9680: @cindex facility words, ambiguous conditions
                   9681: @cindex ambiguous conditions, facility words
                   9682: 
                   9683: @table @i
                   9684: @item @code{AT-XY} can't be performed on user output device:
                   9685: @cindex @code{AT-XY} can't be performed on user output device
                   9686: Largely terminal dependent. No range checks are done on the arguments.
                   9687: No errors are reported. You may see some garbage appearing, you may see
                   9688: simply nothing happen.
                   9689: 
                   9690: @end table
                   9691: 
                   9692: 
                   9693: @c =====================================================================
                   9694: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   9695: @section The optional File-Access word set
                   9696: @c =====================================================================
                   9697: @cindex system documentation, file words
                   9698: @cindex file words, system documentation
                   9699: 
                   9700: @menu
                   9701: * file-idef::                   Implementation Defined Options
                   9702: * file-ambcond::                Ambiguous Conditions                
                   9703: @end menu
                   9704: 
                   9705: @c ---------------------------------------------------------------------
                   9706: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   9707: @subsection Implementation Defined Options
                   9708: @c ---------------------------------------------------------------------
                   9709: @cindex implementation-defined options, file words
                   9710: @cindex file words, implementation-defined options
                   9711: 
                   9712: @table @i
                   9713: @item file access methods used:
                   9714: @cindex file access methods used
                   9715: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   9716: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   9717: @code{wb}): The file is cleared, if it exists, and created, if it does
                   9718: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   9719: @code{create-file} creates a file with 666 permissions modified by your
                   9720: umask.
                   9721: 
                   9722: @item file exceptions:
                   9723: @cindex file exceptions
                   9724: The file words do not raise exceptions (except, perhaps, memory access
                   9725: faults when you pass illegal addresses or file-ids).
                   9726: 
                   9727: @item file line terminator:
                   9728: @cindex file line terminator
                   9729: System-dependent. Gforth uses C's newline character as line
                   9730: terminator. What the actual character code(s) of this are is
                   9731: system-dependent.
                   9732: 
                   9733: @item file name format:
                   9734: @cindex file name format
                   9735: System dependent. Gforth just uses the file name format of your OS.
                   9736: 
                   9737: @item information returned by @code{FILE-STATUS}:
                   9738: @cindex @code{FILE-STATUS}, returned information
                   9739: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   9740: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   9741: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   9742: along with the returned mode.
                   9743: 
                   9744: @item input file state after an exception when including source:
                   9745: @cindex exception when including source
                   9746: All files that are left via the exception are closed.
                   9747: 
1.29      crook    9748: @item @i{ior} values and meaning:
                   9749: @cindex @i{ior} values and meaning
                   9750: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    9751: intended as throw codes. They typically are in the range
                   9752: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    9753: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    9754: 
                   9755: @item maximum depth of file input nesting:
                   9756: @cindex maximum depth of file input nesting
                   9757: @cindex file input nesting, maximum depth
                   9758: limited by the amount of return stack, locals/TIB stack, and the number
                   9759: of open files available. This should not give you troubles.
                   9760: 
                   9761: @item maximum size of input line:
                   9762: @cindex maximum size of input line
                   9763: @cindex input line size, maximum
                   9764: @code{/line}. Currently 255.
                   9765: 
                   9766: @item methods of mapping block ranges to files:
                   9767: @cindex mapping block ranges to files
                   9768: @cindex files containing blocks
                   9769: @cindex blocks in files
                   9770: By default, blocks are accessed in the file @file{blocks.fb} in the
                   9771: current working directory. The file can be switched with @code{USE}.
                   9772: 
                   9773: @item number of string buffers provided by @code{S"}:
                   9774: @cindex @code{S"}, number of string buffers
                   9775: 1
                   9776: 
                   9777: @item size of string buffer used by @code{S"}:
                   9778: @cindex @code{S"}, size of string buffer
                   9779: @code{/line}. currently 255.
                   9780: 
                   9781: @end table
                   9782: 
                   9783: @c ---------------------------------------------------------------------
                   9784: @node file-ambcond,  , file-idef, The optional File-Access word set
                   9785: @subsection Ambiguous conditions
                   9786: @c ---------------------------------------------------------------------
                   9787: @cindex file words, ambiguous conditions
                   9788: @cindex ambiguous conditions, file words
                   9789: 
                   9790: @table @i
                   9791: @item attempting to position a file outside its boundaries:
                   9792: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   9793: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   9794: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   9795: 
                   9796: @item attempting to read from file positions not yet written:
                   9797: @cindex reading from file positions not yet written
                   9798: End-of-file, i.e., zero characters are read and no error is reported.
                   9799: 
1.29      crook    9800: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   9801: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    9802: An appropriate exception may be thrown, but a memory fault or other
                   9803: problem is more probable.
                   9804: 
1.29      crook    9805: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   9806: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   9807: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   9808: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    9809: thrown.
                   9810: 
                   9811: @item named file cannot be opened (@code{INCLUDED}):
                   9812: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    9813: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    9814: 
                   9815: @item requesting an unmapped block number:
                   9816: @cindex unmapped block numbers
                   9817: There are no unmapped legal block numbers. On some operating systems,
                   9818: writing a block with a large number may overflow the file system and
                   9819: have an error message as consequence.
                   9820: 
                   9821: @item using @code{source-id} when @code{blk} is non-zero:
                   9822: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   9823: @code{source-id} performs its function. Typically it will give the id of
                   9824: the source which loaded the block. (Better ideas?)
                   9825: 
                   9826: @end table
                   9827: 
                   9828: 
                   9829: @c =====================================================================
                   9830: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   9831: @section The optional Floating-Point word set
                   9832: @c =====================================================================
                   9833: @cindex system documentation, floating-point words
                   9834: @cindex floating-point words, system documentation
                   9835: 
                   9836: @menu
                   9837: * floating-idef::               Implementation Defined Options
                   9838: * floating-ambcond::            Ambiguous Conditions            
                   9839: @end menu
                   9840: 
                   9841: 
                   9842: @c ---------------------------------------------------------------------
                   9843: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   9844: @subsection Implementation Defined Options
                   9845: @c ---------------------------------------------------------------------
                   9846: @cindex implementation-defined options, floating-point words
                   9847: @cindex floating-point words, implementation-defined options
                   9848: 
                   9849: @table @i
                   9850: @item format and range of floating point numbers:
                   9851: @cindex format and range of floating point numbers
                   9852: @cindex floating point numbers, format and range
                   9853: System-dependent; the @code{double} type of C.
                   9854: 
1.29      crook    9855: @item results of @code{REPRESENT} when @i{float} is out of range:
                   9856: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    9857: System dependent; @code{REPRESENT} is implemented using the C library
                   9858: function @code{ecvt()} and inherits its behaviour in this respect.
                   9859: 
                   9860: @item rounding or truncation of floating-point numbers:
                   9861: @cindex rounding of floating-point numbers
                   9862: @cindex truncation of floating-point numbers
                   9863: @cindex floating-point numbers, rounding or truncation
                   9864: System dependent; the rounding behaviour is inherited from the hosting C
                   9865: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   9866: nearest, and break ties by rounding to even (i.e., such that the last
                   9867: bit of the mantissa is 0).
                   9868: 
                   9869: @item size of floating-point stack:
                   9870: @cindex floating-point stack size
                   9871: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   9872: the floating-point stack (in floats). You can specify this on startup
                   9873: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   9874: 
                   9875: @item width of floating-point stack:
                   9876: @cindex floating-point stack width 
                   9877: @code{1 floats}.
                   9878: 
                   9879: @end table
                   9880: 
                   9881: 
                   9882: @c ---------------------------------------------------------------------
                   9883: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   9884: @subsection Ambiguous conditions
                   9885: @c ---------------------------------------------------------------------
                   9886: @cindex floating-point words, ambiguous conditions
                   9887: @cindex ambiguous conditions, floating-point words
                   9888: 
                   9889: @table @i
                   9890: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   9891: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   9892: System-dependent. Typically results in a @code{-23 THROW} like other
                   9893: alignment violations.
                   9894: 
                   9895: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   9896: @cindex @code{f@@} used with an address that is not float aligned
                   9897: @cindex @code{f!} used with an address that is not float aligned
                   9898: System-dependent. Typically results in a @code{-23 THROW} like other
                   9899: alignment violations.
                   9900: 
                   9901: @item floating-point result out of range:
                   9902: @cindex floating-point result out of range
                   9903: System-dependent. Can result in a @code{-55 THROW} (Floating-point
                   9904: unidentified fault), or can produce a special value representing, e.g.,
                   9905: Infinity.
                   9906: 
                   9907: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   9908: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   9909: System-dependent. Typically results in an alignment fault like other
                   9910: alignment violations.
                   9911: 
1.35      anton    9912: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   9913: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    9914: The floating-point number is converted into decimal nonetheless.
                   9915: 
                   9916: @item Both arguments are equal to zero (@code{FATAN2}):
                   9917: @cindex @code{FATAN2}, both arguments are equal to zero
                   9918: System-dependent. @code{FATAN2} is implemented using the C library
                   9919: function @code{atan2()}.
                   9920: 
1.29      crook    9921: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   9922: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   9923: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    9924: because of small errors and the tan will be a very large (or very small)
                   9925: but finite number.
                   9926: 
1.29      crook    9927: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   9928: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    9929: The result is rounded to the nearest float.
                   9930: 
                   9931: @item dividing by zero:
                   9932: @cindex dividing by zero, floating-point
                   9933: @cindex floating-point dividing by zero
                   9934: @cindex floating-point unidentified fault, FP divide-by-zero
                   9935: @code{-55 throw} (Floating-point unidentified fault)
                   9936: 
                   9937: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   9938: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   9939: System dependent. On IEEE-FP based systems the number is converted into
                   9940: an infinity.
                   9941: 
1.29      crook    9942: @item @i{float}<1 (@code{FACOSH}):
                   9943: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    9944: @cindex floating-point unidentified fault, @code{FACOSH}
                   9945: @code{-55 throw} (Floating-point unidentified fault)
                   9946: 
1.29      crook    9947: @item @i{float}=<-1 (@code{FLNP1}):
                   9948: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    9949: @cindex floating-point unidentified fault, @code{FLNP1}
                   9950: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    9951: negative infinity is typically produced for @i{float}=-1.
1.1       anton    9952: 
1.29      crook    9953: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   9954: @cindex @code{FLN}, @i{float}=<0
                   9955: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    9956: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
                   9957: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    9958: negative infinity is typically produced for @i{float}=0.
1.1       anton    9959: 
1.29      crook    9960: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   9961: @cindex @code{FASINH}, @i{float}<0
                   9962: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    9963: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
                   9964: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
                   9965: produces values for these inputs on my Linux box (Bug in the C library?)
                   9966: 
1.29      crook    9967: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   9968: @cindex @code{FACOS}, |@i{float}|>1
                   9969: @cindex @code{FASIN}, |@i{float}|>1
                   9970: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    9971: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
                   9972: @code{-55 throw} (Floating-point unidentified fault).
                   9973: 
1.29      crook    9974: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   9975: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    9976: @cindex floating-point unidentified fault, @code{F>D}
                   9977: @code{-55 throw} (Floating-point unidentified fault).
                   9978: 
                   9979: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   9980: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
                   9981: This does not happen.
                   9982: @end table
                   9983: 
                   9984: @c =====================================================================
                   9985: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   9986: @section The optional Locals word set
                   9987: @c =====================================================================
                   9988: @cindex system documentation, locals words
                   9989: @cindex locals words, system documentation
                   9990: 
                   9991: @menu
                   9992: * locals-idef::                 Implementation Defined Options                 
                   9993: * locals-ambcond::              Ambiguous Conditions              
                   9994: @end menu
                   9995: 
                   9996: 
                   9997: @c ---------------------------------------------------------------------
                   9998: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   9999: @subsection Implementation Defined Options
                   10000: @c ---------------------------------------------------------------------
                   10001: @cindex implementation-defined options, locals words
                   10002: @cindex locals words, implementation-defined options
                   10003: 
                   10004: @table @i
                   10005: @item maximum number of locals in a definition:
                   10006: @cindex maximum number of locals in a definition
                   10007: @cindex locals, maximum number in a definition
                   10008: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   10009: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   10010: characters. The number of locals in a definition is bounded by the size
                   10011: of locals-buffer, which contains the names of the locals.
                   10012: 
                   10013: @end table
                   10014: 
                   10015: 
                   10016: @c ---------------------------------------------------------------------
                   10017: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   10018: @subsection Ambiguous conditions
                   10019: @c ---------------------------------------------------------------------
                   10020: @cindex locals words, ambiguous conditions
                   10021: @cindex ambiguous conditions, locals words
                   10022: 
                   10023: @table @i
                   10024: @item executing a named local in interpretation state:
                   10025: @cindex local in interpretation state
                   10026: @cindex Interpreting a compile-only word, for a local
                   10027: Locals have no interpretation semantics. If you try to perform the
                   10028: interpretation semantics, you will get a @code{-14 throw} somewhere
                   10029: (Interpreting a compile-only word). If you perform the compilation
                   10030: semantics, the locals access will be compiled (irrespective of state).
                   10031: 
1.29      crook    10032: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    10033: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   10034: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   10035: @cindex Invalid name argument, @code{TO}
                   10036: @code{-32 throw} (Invalid name argument)
                   10037: 
                   10038: @end table
                   10039: 
                   10040: 
                   10041: @c =====================================================================
                   10042: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   10043: @section The optional Memory-Allocation word set
                   10044: @c =====================================================================
                   10045: @cindex system documentation, memory-allocation words
                   10046: @cindex memory-allocation words, system documentation
                   10047: 
                   10048: @menu
                   10049: * memory-idef::                 Implementation Defined Options                 
                   10050: @end menu
                   10051: 
                   10052: 
                   10053: @c ---------------------------------------------------------------------
                   10054: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   10055: @subsection Implementation Defined Options
                   10056: @c ---------------------------------------------------------------------
                   10057: @cindex implementation-defined options, memory-allocation words
                   10058: @cindex memory-allocation words, implementation-defined options
                   10059: 
                   10060: @table @i
1.29      crook    10061: @item values and meaning of @i{ior}:
                   10062: @cindex  @i{ior} values and meaning
                   10063: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    10064: intended as throw codes. They typically are in the range
                   10065: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    10066: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    10067: 
                   10068: @end table
                   10069: 
                   10070: @c =====================================================================
                   10071: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   10072: @section The optional Programming-Tools word set
                   10073: @c =====================================================================
                   10074: @cindex system documentation, programming-tools words
                   10075: @cindex programming-tools words, system documentation
                   10076: 
                   10077: @menu
                   10078: * programming-idef::            Implementation Defined Options            
                   10079: * programming-ambcond::         Ambiguous Conditions         
                   10080: @end menu
                   10081: 
                   10082: 
                   10083: @c ---------------------------------------------------------------------
                   10084: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   10085: @subsection Implementation Defined Options
                   10086: @c ---------------------------------------------------------------------
                   10087: @cindex implementation-defined options, programming-tools words
                   10088: @cindex programming-tools words, implementation-defined options
                   10089: 
                   10090: @table @i
                   10091: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   10092: @cindex @code{;CODE} ending sequence
                   10093: @cindex @code{CODE} ending sequence
                   10094: @code{END-CODE}
                   10095: 
                   10096: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   10097: @cindex @code{;CODE}, processing input
                   10098: @cindex @code{CODE}, processing input
                   10099: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   10100: the input is processed by the text interpreter, (starting) in interpret
                   10101: state.
                   10102: 
                   10103: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   10104: @cindex @code{ASSEMBLER}, search order capability
                   10105: The ANS Forth search order word set.
                   10106: 
                   10107: @item source and format of display by @code{SEE}:
                   10108: @cindex @code{SEE}, source and format of output
                   10109: The source for @code{see} is the intermediate code used by the inner
                   10110: interpreter.  The current @code{see} tries to output Forth source code
                   10111: as well as possible.
                   10112: 
                   10113: @end table
                   10114: 
                   10115: @c ---------------------------------------------------------------------
                   10116: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   10117: @subsection Ambiguous conditions
                   10118: @c ---------------------------------------------------------------------
                   10119: @cindex programming-tools words, ambiguous conditions
                   10120: @cindex ambiguous conditions, programming-tools words
                   10121: 
                   10122: @table @i
                   10123: 
1.21      crook    10124: @item deleting the compilation word list (@code{FORGET}):
                   10125: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    10126: Not implemented (yet).
                   10127: 
1.29      crook    10128: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   10129: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   10130: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    10131: @cindex control-flow stack underflow
                   10132: This typically results in an @code{abort"} with a descriptive error
                   10133: message (may change into a @code{-22 throw} (Control structure mismatch)
                   10134: in the future). You may also get a memory access error. If you are
                   10135: unlucky, this ambiguous condition is not caught.
                   10136: 
1.29      crook    10137: @item @i{name} can't be found (@code{FORGET}):
                   10138: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    10139: Not implemented (yet).
                   10140: 
1.29      crook    10141: @item @i{name} not defined via @code{CREATE}:
                   10142: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    10143: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   10144: the execution semantics of the last defined word no matter how it was
                   10145: defined.
                   10146: 
                   10147: @item @code{POSTPONE} applied to @code{[IF]}:
                   10148: @cindex @code{POSTPONE} applied to @code{[IF]}
                   10149: @cindex @code{[IF]} and @code{POSTPONE}
                   10150: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   10151: equivalent to @code{[IF]}.
                   10152: 
                   10153: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   10154: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   10155: Continue in the same state of conditional compilation in the next outer
                   10156: input source. Currently there is no warning to the user about this.
                   10157: 
                   10158: @item removing a needed definition (@code{FORGET}):
                   10159: @cindex @code{FORGET}, removing a needed definition
                   10160: Not implemented (yet).
                   10161: 
                   10162: @end table
                   10163: 
                   10164: 
                   10165: @c =====================================================================
                   10166: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   10167: @section The optional Search-Order word set
                   10168: @c =====================================================================
                   10169: @cindex system documentation, search-order words
                   10170: @cindex search-order words, system documentation
                   10171: 
                   10172: @menu
                   10173: * search-idef::                 Implementation Defined Options                 
                   10174: * search-ambcond::              Ambiguous Conditions              
                   10175: @end menu
                   10176: 
                   10177: 
                   10178: @c ---------------------------------------------------------------------
                   10179: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   10180: @subsection Implementation Defined Options
                   10181: @c ---------------------------------------------------------------------
                   10182: @cindex implementation-defined options, search-order words
                   10183: @cindex search-order words, implementation-defined options
                   10184: 
                   10185: @table @i
                   10186: @item maximum number of word lists in search order:
                   10187: @cindex maximum number of word lists in search order
                   10188: @cindex search order, maximum depth
                   10189: @code{s" wordlists" environment? drop .}. Currently 16.
                   10190: 
                   10191: @item minimum search order:
                   10192: @cindex minimum search order
                   10193: @cindex search order, minimum
                   10194: @code{root root}.
                   10195: 
                   10196: @end table
                   10197: 
                   10198: @c ---------------------------------------------------------------------
                   10199: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   10200: @subsection Ambiguous conditions
                   10201: @c ---------------------------------------------------------------------
                   10202: @cindex search-order words, ambiguous conditions
                   10203: @cindex ambiguous conditions, search-order words
                   10204: 
                   10205: @table @i
1.21      crook    10206: @item changing the compilation word list (during compilation):
                   10207: @cindex changing the compilation word list (during compilation)
                   10208: @cindex compilation word list, change before definition ends
                   10209: The word is entered into the word list that was the compilation word list
1.1       anton    10210: at the start of the definition. Any changes to the name field (e.g.,
                   10211: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
                   10212: are applied to the latest defined word (as reported by @code{last} or
1.21      crook    10213: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1       anton    10214: 
                   10215: @item search order empty (@code{previous}):
                   10216: @cindex @code{previous}, search order empty
1.26      crook    10217: @cindex vocstack empty, @code{previous}
1.1       anton    10218: @code{abort" Vocstack empty"}.
                   10219: 
                   10220: @item too many word lists in search order (@code{also}):
                   10221: @cindex @code{also}, too many word lists in search order
1.26      crook    10222: @cindex vocstack full, @code{also}
1.1       anton    10223: @code{abort" Vocstack full"}.
                   10224: 
                   10225: @end table
                   10226: 
                   10227: @c ***************************************************************
                   10228: @node Model, Integrating Gforth, ANS conformance, Top
                   10229: @chapter Model
                   10230: 
                   10231: This chapter has yet to be written. It will contain information, on
                   10232: which internal structures you can rely.
                   10233: 
                   10234: @c ***************************************************************
                   10235: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   10236: @chapter Integrating Gforth into C programs
                   10237: 
                   10238: This is not yet implemented.
                   10239: 
                   10240: Several people like to use Forth as scripting language for applications
                   10241: that are otherwise written in C, C++, or some other language.
                   10242: 
                   10243: The Forth system ATLAST provides facilities for embedding it into
                   10244: applications; unfortunately it has several disadvantages: most
                   10245: importantly, it is not based on ANS Forth, and it is apparently dead
                   10246: (i.e., not developed further and not supported). The facilities
1.21      crook    10247: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    10248: making the switch should not be hard.
                   10249: 
                   10250: We also tried to design the interface such that it can easily be
                   10251: implemented by other Forth systems, so that we may one day arrive at a
                   10252: standardized interface. Such a standard interface would allow you to
                   10253: replace the Forth system without having to rewrite C code.
                   10254: 
                   10255: You embed the Gforth interpreter by linking with the library
                   10256: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   10257: global symbols in this library that belong to the interface, have the
                   10258: prefix @code{forth_}. (Global symbols that are used internally have the
                   10259: prefix @code{gforth_}).
                   10260: 
                   10261: You can include the declarations of Forth types and the functions and
                   10262: variables of the interface with @code{#include <forth.h>}.
                   10263: 
                   10264: Types.
                   10265: 
                   10266: Variables.
                   10267: 
                   10268: Data and FP Stack pointer. Area sizes.
                   10269: 
                   10270: functions.
                   10271: 
                   10272: forth_init(imagefile)
                   10273: forth_evaluate(string) exceptions?
                   10274: forth_goto(address) (or forth_execute(xt)?)
                   10275: forth_continue() (a corountining mechanism)
                   10276: 
                   10277: Adding primitives.
                   10278: 
                   10279: No checking.
                   10280: 
                   10281: Signals?
                   10282: 
                   10283: Accessing the Stacks
                   10284: 
1.26      crook    10285: @c ******************************************************************
1.1       anton    10286: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   10287: @chapter Emacs and Gforth
                   10288: @cindex Emacs and Gforth
                   10289: 
                   10290: @cindex @file{gforth.el}
                   10291: @cindex @file{forth.el}
                   10292: @cindex Rydqvist, Goran
                   10293: @cindex comment editing commands
                   10294: @cindex @code{\}, editing with Emacs
                   10295: @cindex debug tracer editing commands
                   10296: @cindex @code{~~}, removal with Emacs
                   10297: @cindex Forth mode in Emacs
                   10298: Gforth comes with @file{gforth.el}, an improved version of
                   10299: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    10300: improvements are:
                   10301: 
                   10302: @itemize @bullet
                   10303: @item
                   10304: A better (but still not perfect) handling of indentation.
                   10305: @item
                   10306: Comment paragraph filling (@kbd{M-q})
                   10307: @item
                   10308: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   10309: @item
                   10310: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
                   10311: @end itemize
                   10312: 
                   10313: I left the stuff I do not use alone, even though some of it only makes
                   10314: sense for TILE. To get a description of these features, enter Forth mode
                   10315: and type @kbd{C-h m}.
1.1       anton    10316: 
                   10317: @cindex source location of error or debugging output in Emacs
                   10318: @cindex error output, finding the source location in Emacs
                   10319: @cindex debugging output, finding the source location in Emacs
                   10320: In addition, Gforth supports Emacs quite well: The source code locations
                   10321: given in error messages, debugging output (from @code{~~}) and failed
                   10322: assertion messages are in the right format for Emacs' compilation mode
                   10323: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   10324: Manual}) so the source location corresponding to an error or other
                   10325: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   10326: @kbd{C-c C-c} for the error under the cursor).
                   10327: 
                   10328: @cindex @file{TAGS} file
                   10329: @cindex @file{etags.fs}
                   10330: @cindex viewing the source of a word in Emacs
1.26      crook    10331: Also, if you @code{include} @file{etags.fs}, a new @file{TAGS} file will
                   10332: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    10333: contains the definitions of all words defined afterwards. You can then
                   10334: find the source for a word using @kbd{M-.}. Note that emacs can use
                   10335: several tags files at the same time (e.g., one for the Gforth sources
                   10336: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   10337: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   10338: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
                   10339: @file{/usr/local/share/gforth/0.2.0/TAGS}).
                   10340: 
                   10341: @cindex @file{.emacs}
                   10342: To get all these benefits, add the following lines to your @file{.emacs}
                   10343: file:
                   10344: 
                   10345: @example
                   10346: (autoload 'forth-mode "gforth.el")
                   10347: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
                   10348: @end example
                   10349: 
1.26      crook    10350: @c ******************************************************************
1.1       anton    10351: @node Image Files, Engine, Emacs and Gforth, Top
                   10352: @chapter Image Files
1.26      crook    10353: @cindex image file
                   10354: @cindex @file{.fi} files
1.1       anton    10355: @cindex precompiled Forth code
                   10356: @cindex dictionary in persistent form
                   10357: @cindex persistent form of dictionary
                   10358: 
                   10359: An image file is a file containing an image of the Forth dictionary,
                   10360: i.e., compiled Forth code and data residing in the dictionary.  By
                   10361: convention, we use the extension @code{.fi} for image files.
                   10362: 
                   10363: @menu
1.18      anton    10364: * Image Licensing Issues::      Distribution terms for images.
                   10365: * Image File Background::       Why have image files?
1.29      crook    10366: * Non-Relocatable Image Files::   don't always work.
1.18      anton    10367: * Data-Relocatable Image Files::  are better.
1.29      crook    10368: * Fully Relocatable Image Files:: better yet.
1.18      anton    10369: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    10370: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    10371: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    10372: @end menu
                   10373: 
1.18      anton    10374: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   10375: @section Image Licensing Issues
                   10376: @cindex license for images
                   10377: @cindex image license
                   10378: 
                   10379: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   10380: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   10381: original image; i.e., according to copyright law it is a derived work of
                   10382: the original image.
                   10383: 
                   10384: Since Gforth is distributed under the GNU GPL, the newly created image
                   10385: falls under the GNU GPL, too. In particular, this means that if you
                   10386: distribute the image, you have to make all of the sources for the image
                   10387: available, including those you wrote.  For details see @ref{License, ,
                   10388: GNU General Public License (Section 3)}.
                   10389: 
                   10390: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   10391: contains only code compiled from the sources you gave it; if none of
                   10392: these sources is under the GPL, the terms discussed above do not apply
                   10393: to the image. However, if your image needs an engine (a gforth binary)
                   10394: that is under the GPL, you should make sure that you distribute both in
                   10395: a way that is at most a @emph{mere aggregation}, if you don't want the
                   10396: terms of the GPL to apply to the image.
                   10397: 
                   10398: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    10399: @section Image File Background
                   10400: @cindex image file background
                   10401: 
                   10402: Our Forth system consists not only of primitives, but also of
                   10403: definitions written in Forth. Since the Forth compiler itself belongs to
                   10404: those definitions, it is not possible to start the system with the
                   10405: primitives and the Forth source alone. Therefore we provide the Forth
1.26      crook    10406: code as an image file in nearly executable form. When Gforth starts up,
                   10407: a C routine loads the image file into memory, optionally relocates the
                   10408: addresses, then sets up the memory (stacks etc.) according to
                   10409: information in the image file, and (finally) starts executing Forth
                   10410: code.
1.1       anton    10411: 
                   10412: The image file variants represent different compromises between the
                   10413: goals of making it easy to generate image files and making them
                   10414: portable.
                   10415: 
                   10416: @cindex relocation at run-time
1.26      crook    10417: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    10418: run-time. This avoids many of the complications discussed below (image
                   10419: files are data relocatable without further ado), but costs performance
                   10420: (one addition per memory access).
                   10421: 
                   10422: @cindex relocation at load-time
1.26      crook    10423: By contrast, the Gforth loader performs relocation at image load time. The
                   10424: loader also has to replace tokens that represent primitive calls with the
1.1       anton    10425: appropriate code-field addresses (or code addresses in the case of
                   10426: direct threading).
                   10427: 
                   10428: There are three kinds of image files, with different degrees of
                   10429: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   10430: image files.
                   10431: 
                   10432: @cindex image file loader
                   10433: @cindex relocating loader
                   10434: @cindex loader for image files
                   10435: These image file variants have several restrictions in common; they are
                   10436: caused by the design of the image file loader:
                   10437: 
                   10438: @itemize @bullet
                   10439: @item
                   10440: There is only one segment; in particular, this means, that an image file
                   10441: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    10442: them). The contents of the stacks are not represented, either.
1.1       anton    10443: 
                   10444: @item
                   10445: The only kinds of relocation supported are: adding the same offset to
                   10446: all cells that represent data addresses; and replacing special tokens
                   10447: with code addresses or with pieces of machine code.
                   10448: 
                   10449: If any complex computations involving addresses are performed, the
                   10450: results cannot be represented in the image file. Several applications that
                   10451: use such computations come to mind:
                   10452: @itemize @minus
                   10453: @item
                   10454: Hashing addresses (or data structures which contain addresses) for table
                   10455: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   10456: purpose, you will have no problem, because the hash tables are
                   10457: recomputed automatically when the system is started. If you use your own
                   10458: hash tables, you will have to do something similar.
                   10459: 
                   10460: @item
                   10461: There's a cute implementation of doubly-linked lists that uses
                   10462: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   10463: in the image file, and restore the doubly-linked representation on
                   10464: startup.@footnote{In my opinion, though, you should think thrice before
                   10465: using a doubly-linked list (whatever implementation).}
                   10466: 
                   10467: @item
                   10468: The code addresses of run-time routines like @code{docol:} cannot be
                   10469: represented in the image file (because their tokens would be replaced by
                   10470: machine code in direct threaded implementations). As a workaround,
                   10471: compute these addresses at run-time with @code{>code-address} from the
                   10472: executions tokens of appropriate words (see the definitions of
                   10473: @code{docol:} and friends in @file{kernel.fs}).
                   10474: 
                   10475: @item
                   10476: On many architectures addresses are represented in machine code in some
                   10477: shifted or mangled form. You cannot put @code{CODE} words that contain
                   10478: absolute addresses in this form in a relocatable image file. Workarounds
                   10479: are representing the address in some relative form (e.g., relative to
                   10480: the CFA, which is present in some register), or loading the address from
                   10481: a place where it is stored in a non-mangled form.
                   10482: @end itemize
                   10483: @end itemize
                   10484: 
                   10485: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   10486: @section Non-Relocatable Image Files
                   10487: @cindex non-relocatable image files
1.26      crook    10488: @cindex image file, non-relocatable
1.1       anton    10489: 
                   10490: These files are simple memory dumps of the dictionary. They are specific
                   10491: to the executable (i.e., @file{gforth} file) they were created
                   10492: with. What's worse, they are specific to the place on which the
                   10493: dictionary resided when the image was created. Now, there is no
                   10494: guarantee that the dictionary will reside at the same place the next
                   10495: time you start Gforth, so there's no guarantee that a non-relocatable
                   10496: image will work the next time (Gforth will complain instead of crashing,
                   10497: though).
                   10498: 
                   10499: You can create a non-relocatable image file with
                   10500: 
                   10501: doc-savesystem
                   10502: 
                   10503: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   10504: @section Data-Relocatable Image Files
                   10505: @cindex data-relocatable image files
1.26      crook    10506: @cindex image file, data-relocatable
1.1       anton    10507: 
                   10508: These files contain relocatable data addresses, but fixed code addresses
                   10509: (instead of tokens). They are specific to the executable (i.e.,
                   10510: @file{gforth} file) they were created with. For direct threading on some
                   10511: architectures (e.g., the i386), data-relocatable images do not work. You
                   10512: get a data-relocatable image, if you use @file{gforthmi} with a
                   10513: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   10514: Relocatable Image Files}).
                   10515: 
                   10516: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   10517: @section Fully Relocatable Image Files
                   10518: @cindex fully relocatable image files
1.26      crook    10519: @cindex image file, fully relocatable
1.1       anton    10520: 
                   10521: @cindex @file{kern*.fi}, relocatability
                   10522: @cindex @file{gforth.fi}, relocatability
                   10523: These image files have relocatable data addresses, and tokens for code
                   10524: addresses. They can be used with different binaries (e.g., with and
                   10525: without debugging) on the same machine, and even across machines with
                   10526: the same data formats (byte order, cell size, floating point
                   10527: format). However, they are usually specific to the version of Gforth
                   10528: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   10529: are fully relocatable.
                   10530: 
                   10531: There are two ways to create a fully relocatable image file:
                   10532: 
                   10533: @menu
1.29      crook    10534: * gforthmi::                    The normal way
1.1       anton    10535: * cross.fs::                    The hard way
                   10536: @end menu
                   10537: 
                   10538: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   10539: @subsection @file{gforthmi}
                   10540: @cindex @file{comp-i.fs}
                   10541: @cindex @file{gforthmi}
                   10542: 
                   10543: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    10544: image @i{file} that contains everything you would load by invoking
                   10545: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    10546: @example
1.29      crook    10547: gforthmi @i{file} @i{options}
1.1       anton    10548: @end example
                   10549: 
                   10550: E.g., if you want to create an image @file{asm.fi} that has the file
                   10551: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   10552: like this:
                   10553: 
                   10554: @example
                   10555: gforthmi asm.fi asm.fs
                   10556: @end example
                   10557: 
1.27      crook    10558: @file{gforthmi} is implemented as a sh script and works like this: It
                   10559: produces two non-relocatable images for different addresses and then
                   10560: compares them. Its output reflects this: first you see the output (if
                   10561: any) of the two Gforth invocations that produce the nonrelocatable image
                   10562: files, then you see the output of the comparing program: It displays the
                   10563: offset used for data addresses and the offset used for code addresses;
1.1       anton    10564: moreover, for each cell that cannot be represented correctly in the
                   10565: image files, it displays a line like the following one:
                   10566: 
                   10567: @example
                   10568:      78DC         BFFFFA50         BFFFFA40
                   10569: @end example
                   10570: 
                   10571: This means that at offset $78dc from @code{forthstart}, one input image
                   10572: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   10573: cannot be represented correctly in the output image, you should examine
                   10574: these places in the dictionary and verify that these cells are dead
                   10575: (i.e., not read before they are written).
1.39    ! anton    10576: 
        !          10577: @cindex --application, @code{gforthmi} option
        !          10578: If you insert the option @code{--application} in front of the image file
        !          10579: name, you will get an image that uses the @code{--appl-image} option
        !          10580: instead of the @code{--image-file} option (@pxref{Invoking
        !          10581: Gforth}). When you execute such an image on Unix (by typing the image
        !          10582: name as command), the Gforth engine will pass all options to the image
        !          10583: instead of trying to interpret them as engine options.
1.1       anton    10584: 
1.27      crook    10585: If you type @file{gforthmi} with no arguments, it prints some usage
                   10586: instructions.
                   10587: 
1.1       anton    10588: @cindex @code{savesystem} during @file{gforthmi}
                   10589: @cindex @code{bye} during @file{gforthmi}
                   10590: @cindex doubly indirect threaded code
                   10591: @cindex environment variable @code{GFORTHD}
                   10592: @cindex @code{GFORTHD} environment variable
                   10593: @cindex @code{gforth-ditc}
1.29      crook    10594: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    10595: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   10596: indirect threaded version of the @file{gforth} executable is used for
                   10597: creating the nonrelocatable images; you can pass the exact filename of
                   10598: this executable through the environment variable @code{GFORTHD}
                   10599: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   10600: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    10601: data-relocatable image (because there is no code address offset). The
                   10602: normal @file{gforth} executable is used for creating the relocatable
                   10603: image; you can pass the exact filename of this executable through the
                   10604: environment variable @code{GFORTH}.
1.1       anton    10605: 
                   10606: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   10607: @subsection @file{cross.fs}
                   10608: @cindex @file{cross.fs}
                   10609: @cindex cross-compiler
                   10610: @cindex metacompiler
                   10611: 
                   10612: You can also use @code{cross}, a batch compiler that accepts a Forth-like
                   10613: programming language. This @code{cross} language has to be documented
                   10614: yet.
                   10615: 
                   10616: @cindex target compiler
                   10617: @code{cross} also allows you to create image files for machines with
                   10618: different data sizes and data formats than the one used for generating
                   10619: the image file. You can also use it to create an application image that
                   10620: does not contain a Forth compiler. These features are bought with
                   10621: restrictions and inconveniences in programming. E.g., addresses have to
                   10622: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   10623: order to make the code relocatable.
                   10624: 
                   10625: 
                   10626: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   10627: @section Stack and Dictionary Sizes
                   10628: @cindex image file, stack and dictionary sizes
                   10629: @cindex dictionary size default
                   10630: @cindex stack size default
                   10631: 
                   10632: If you invoke Gforth with a command line flag for the size
                   10633: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   10634: dictionary. If you save the dictionary with @code{savesystem} or create
                   10635: an image with @file{gforthmi}, this size will become the default
                   10636: for the resulting image file. E.g., the following will create a
1.21      crook    10637: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    10638: 
                   10639: @example
                   10640: gforthmi gforth.fi -m 1M
                   10641: @end example
                   10642: 
                   10643: In other words, if you want to set the default size for the dictionary
                   10644: and the stacks of an image, just invoke @file{gforthmi} with the
                   10645: appropriate options when creating the image.
                   10646: 
                   10647: @cindex stack size, cache-friendly
                   10648: Note: For cache-friendly behaviour (i.e., good performance), you should
                   10649: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   10650: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   10651: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   10652: 
                   10653: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   10654: @section Running Image Files
                   10655: @cindex running image files
                   10656: @cindex invoking image files
                   10657: @cindex image file invocation
                   10658: 
                   10659: @cindex -i, invoke image file
                   10660: @cindex --image file, invoke image file
1.29      crook    10661: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    10662: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   10663: @example
1.29      crook    10664: gforth -i @i{image}
1.1       anton    10665: @end example
                   10666: 
                   10667: @cindex executable image file
1.26      crook    10668: @cindex image file, executable
1.1       anton    10669: If your operating system supports starting scripts with a line of the
                   10670: form @code{#! ...}, you just have to type the image file name to start
                   10671: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    10672: just a convention). I.e., to run Gforth with the image file @i{image},
                   10673: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    10674: This works because every @code{.fi} file starts with a line of this
                   10675: format:
                   10676: 
                   10677: @example
                   10678: #! /usr/local/bin/gforth-0.4.0 -i
                   10679: @end example
                   10680: 
                   10681: The file and pathname for the Gforth engine specified on this line is
                   10682: the specific Gforth executable that it was built against; i.e. the value
                   10683: of the environment variable @code{GFORTH} at the time that
                   10684: @file{gforthmi} was executed.
1.1       anton    10685: 
1.27      crook    10686: You can make use of the same shell capability to make a Forth source
                   10687: file into an executable. For example, if you place this text in a file:
1.26      crook    10688: 
                   10689: @example
                   10690: #! /usr/local/bin/gforth
                   10691: 
                   10692: ." Hello, world" CR
                   10693: bye
                   10694: @end example
                   10695: 
                   10696: @noindent
1.27      crook    10697: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    10698: directly from the command line. The sequence @code{#!} is used in two
                   10699: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    10700: system@footnote{The Unix kernel actually recognises two types of files:
                   10701: executable files and files of data, where the data is processed by an
                   10702: interpreter that is specified on the ``interpreter line'' -- the first
                   10703: line of the file, starting with the sequence #!. There may be a small
                   10704: limit (e.g., 32) on the number of characters that may be specified on
                   10705: the interpreter line.} secondly it is treated as a comment character by
                   10706: Gforth. Because of the second usage, a space is required between
                   10707: @code{#!} and the path to the executable.
1.27      crook    10708: 
                   10709: The disadvantage of this latter technique, compared with using
                   10710: @file{gforthmi}, is that it is slower; the Forth source code is compiled
                   10711: on-the-fly, each time the program is invoked.
                   10712: 
1.26      crook    10713: @comment TODO describe the #! magic with reference to the Power Tools book.
                   10714: 
1.1       anton    10715: doc-#!
                   10716: 
                   10717: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   10718: @section Modifying the Startup Sequence
                   10719: @cindex startup sequence for image file
                   10720: @cindex image file initialization sequence
                   10721: @cindex initialization sequence of image file
                   10722: 
                   10723: You can add your own initialization to the startup sequence through the
1.26      crook    10724: deferred word @code{'cold}. @code{'cold} is invoked just before the
                   10725: image-specific command line processing (by default, loading files and
                   10726: evaluating (@code{-e}) strings) starts.
1.1       anton    10727: 
                   10728: A sequence for adding your initialization usually looks like this:
                   10729: 
                   10730: @example
                   10731: :noname
                   10732:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   10733:     ... \ your stuff
                   10734: ; IS 'cold
                   10735: @end example
                   10736: 
                   10737: @cindex turnkey image files
1.26      crook    10738: @cindex image file, turnkey applications
1.1       anton    10739: You can make a turnkey image by letting @code{'cold} execute a word
                   10740: (your turnkey application) that never returns; instead, it exits Gforth
                   10741: via @code{bye} or @code{throw}.
                   10742: 
                   10743: @cindex command-line arguments, access
                   10744: @cindex arguments on the command line, access
                   10745: You can access the (image-specific) command-line arguments through the
1.26      crook    10746: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1       anton    10747: access to @code{argv}.
                   10748: 
1.26      crook    10749: If @code{'cold} exits normally, Gforth processes the command-line
                   10750: arguments as files to be loaded and strings to be evaluated.  Therefore,
                   10751: @code{'cold} should remove the arguments it has used in this case.
                   10752: 
                   10753: doc-'cold
1.1       anton    10754: doc-argc
                   10755: doc-argv
                   10756: doc-arg
                   10757: 
                   10758: 
                   10759: @c ******************************************************************
1.13      pazsan   10760: @node Engine, Binding to System Library, Image Files, Top
1.1       anton    10761: @chapter Engine
                   10762: @cindex engine
                   10763: @cindex virtual machine
                   10764: 
1.26      crook    10765: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    10766: may be helpful for finding your way in the Gforth sources.
                   10767: 
                   10768: The ideas in this section have also been published in the papers
                   10769: @cite{ANS fig/GNU/??? Forth} (in German) by Bernd Paysan, presented at
                   10770: the Forth-Tagung '93 and @cite{A Portable Forth Engine} by M. Anton
                   10771: Ertl, presented at EuroForth '93; the latter is available at
                   10772: @*@url{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z}.
                   10773: 
                   10774: @menu
                   10775: * Portability::                 
                   10776: * Threading::                   
                   10777: * Primitives::                  
                   10778: * Performance::                 
                   10779: @end menu
                   10780: 
                   10781: @node Portability, Threading, Engine, Engine
                   10782: @section Portability
                   10783: @cindex engine portability
                   10784: 
1.26      crook    10785: An important goal of the Gforth Project is availability across a wide
                   10786: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   10787: achieved this goal by manually coding the engine in assembly language
                   10788: for several then-popular processors. This approach is very
                   10789: labor-intensive and the results are short-lived due to progress in
                   10790: computer architecture.
1.1       anton    10791: 
                   10792: @cindex C, using C for the engine
                   10793: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   10794: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   10795: particularly popular for UNIX-based Forths due to the large variety of
                   10796: architectures of UNIX machines. Unfortunately an implementation in C
                   10797: does not mix well with the goals of efficiency and with using
                   10798: traditional techniques: Indirect or direct threading cannot be expressed
                   10799: in C, and switch threading, the fastest technique available in C, is
                   10800: significantly slower. Another problem with C is that it is very
                   10801: cumbersome to express double integer arithmetic.
                   10802: 
                   10803: @cindex GNU C for the engine
                   10804: @cindex long long
                   10805: Fortunately, there is a portable language that does not have these
                   10806: limitations: GNU C, the version of C processed by the GNU C compiler
                   10807: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   10808: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   10809: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   10810: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   10811: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
                   10812: double numbers@footnote{Unfortunately, long longs are not implemented
                   10813: properly on all machines (e.g., on alpha-osf1, long longs are only 64
                   10814: bits, the same size as longs (and pointers), but they should be twice as
1.4       anton    10815: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1       anton    10816: C Manual}). So, we had to implement doubles in C after all. Still, on
                   10817: most machines we can use long longs and achieve better performance than
                   10818: with the emulation package.}. GNU C is available for free on all
                   10819: important (and many unimportant) UNIX machines, VMS, 80386s running
                   10820: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   10821: on all these machines.
                   10822: 
                   10823: Writing in a portable language has the reputation of producing code that
                   10824: is slower than assembly. For our Forth engine we repeatedly looked at
                   10825: the code produced by the compiler and eliminated most compiler-induced
                   10826: inefficiencies by appropriate changes in the source code.
                   10827: 
                   10828: @cindex explicit register declarations
                   10829: @cindex --enable-force-reg, configuration flag
                   10830: @cindex -DFORCE_REG
                   10831: However, register allocation cannot be portably influenced by the
                   10832: programmer, leading to some inefficiencies on register-starved
                   10833: machines. We use explicit register declarations (@pxref{Explicit Reg
                   10834: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   10835: improve the speed on some machines. They are turned on by using the
                   10836: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   10837: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   10838: machine, but also on the compiler version: On some machines some
                   10839: compiler versions produce incorrect code when certain explicit register
                   10840: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   10841: 
                   10842: @node Threading, Primitives, Portability, Engine
                   10843: @section Threading
                   10844: @cindex inner interpreter implementation
                   10845: @cindex threaded code implementation
                   10846: 
                   10847: @cindex labels as values
                   10848: GNU C's labels as values extension (available since @code{gcc-2.0},
                   10849: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    10850: makes it possible to take the address of @i{label} by writing
                   10851: @code{&&@i{label}}.  This address can then be used in a statement like
                   10852: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    10853: @code{goto x}.
                   10854: 
1.26      crook    10855: @cindex @code{NEXT}, indirect threaded
1.1       anton    10856: @cindex indirect threaded inner interpreter
                   10857: @cindex inner interpreter, indirect threaded
1.26      crook    10858: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    10859: @example
                   10860: cfa = *ip++;
                   10861: ca = *cfa;
                   10862: goto *ca;
                   10863: @end example
                   10864: @cindex instruction pointer
                   10865: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   10866: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   10867: execution token and points to the code field of the next word to be
                   10868: executed; The @code{ca} (code address) fetched from there points to some
                   10869: executable code, e.g., a primitive or the colon definition handler
                   10870: @code{docol}.
                   10871: 
1.26      crook    10872: @cindex @code{NEXT}, direct threaded
1.1       anton    10873: @cindex direct threaded inner interpreter
                   10874: @cindex inner interpreter, direct threaded
                   10875: Direct threading is even simpler:
                   10876: @example
                   10877: ca = *ip++;
                   10878: goto *ca;
                   10879: @end example
                   10880: 
                   10881: Of course we have packaged the whole thing neatly in macros called
1.26      crook    10882: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    10883: 
                   10884: @menu
                   10885: * Scheduling::                  
                   10886: * Direct or Indirect Threaded?::  
                   10887: * DOES>::                       
                   10888: @end menu
                   10889: 
                   10890: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   10891: @subsection Scheduling
                   10892: @cindex inner interpreter optimization
                   10893: 
                   10894: There is a little complication: Pipelined and superscalar processors,
                   10895: i.e., RISC and some modern CISC machines can process independent
                   10896: instructions while waiting for the results of an instruction. The
                   10897: compiler usually reorders (schedules) the instructions in a way that
                   10898: achieves good usage of these delay slots. However, on our first tries
                   10899: the compiler did not do well on scheduling primitives. E.g., for
                   10900: @code{+} implemented as
                   10901: @example
                   10902: n=sp[0]+sp[1];
                   10903: sp++;
                   10904: sp[0]=n;
                   10905: NEXT;
                   10906: @end example
1.26      crook    10907: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1       anton    10908: scheduling. After a little thought the problem becomes clear: The
1.21      crook    10909: compiler cannot know that @code{sp} and @code{ip} point to different
                   10910: addresses (and the version of @code{gcc} we used would not know it even
                   10911: if it was possible), so it could not move the load of the cfa above the
                   10912: store to the TOS. Indeed the pointers could be the same, if code on or
                   10913: very near the top of stack were executed. In the interest of speed we
                   10914: chose to forbid this probably unused ``feature'' and helped the compiler
1.26      crook    10915: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21      crook    10916: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1       anton    10917: @example
                   10918: n=sp[0]+sp[1];
                   10919: sp++;
                   10920: NEXT_P1;
                   10921: sp[0]=n;
                   10922: NEXT_P2;
                   10923: @end example
                   10924: This can be scheduled optimally by the compiler.
                   10925: 
                   10926: This division can be turned off with the switch @code{-DCISC_NEXT}. This
                   10927: switch is on by default on machines that do not profit from scheduling
                   10928: (e.g., the 80386), in order to preserve registers.
                   10929: 
                   10930: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
                   10931: @subsection Direct or Indirect Threaded?
                   10932: @cindex threading, direct or indirect?
                   10933: 
                   10934: @cindex -DDIRECT_THREADED
                   10935: Both! After packaging the nasty details in macro definitions we
                   10936: realized that we could switch between direct and indirect threading by
                   10937: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
                   10938: defining a few machine-specific macros for the direct-threading case.
                   10939: On the Forth level we also offer access words that hide the
                   10940: differences between the threading methods (@pxref{Threading Words}).
                   10941: 
                   10942: Indirect threading is implemented completely machine-independently.
                   10943: Direct threading needs routines for creating jumps to the executable
1.21      crook    10944: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
                   10945: machine-dependent, but they do not amount to many source lines. Therefore,
                   10946: even porting direct threading to a new machine requires little effort.
1.1       anton    10947: 
                   10948: @cindex --enable-indirect-threaded, configuration flag
                   10949: @cindex --enable-direct-threaded, configuration flag
                   10950: The default threading method is machine-dependent. You can enforce a
                   10951: specific threading method when building Gforth with the configuration
                   10952: flag @code{--enable-direct-threaded} or
                   10953: @code{--enable-indirect-threaded}. Note that direct threading is not
                   10954: supported on all machines.
                   10955: 
                   10956: @node DOES>,  , Direct or Indirect Threaded?, Threading
                   10957: @subsection DOES>
                   10958: @cindex @code{DOES>} implementation
                   10959: 
1.26      crook    10960: @cindex @code{dodoes} routine
                   10961: @cindex @code{DOES>}-code
1.1       anton    10962: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   10963: the chunk of code executed by every word defined by a
                   10964: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
                   10965: the Forth code to be executed, i.e. the code after the
1.26      crook    10966: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1       anton    10967: 
1.21      crook    10968: In fig-Forth the code field points directly to the @code{dodoes} and the
1.26      crook    10969: @code{DOES>}code address is stored in the cell after the code address (i.e. at
1.29      crook    10970: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1       anton    10971: the Forth-79 and all later standards, because in fig-Forth this address
                   10972: lies in the body (which is illegal in these standards). However, by
                   10973: making the code field larger for all words this solution becomes legal
                   10974: again. We use this approach for the indirect threaded version and for
                   10975: direct threading on some machines. Leaving a cell unused in most words
                   10976: is a bit wasteful, but on the machines we are targeting this is hardly a
                   10977: problem. The other reason for having a code field size of two cells is
                   10978: to avoid having different image files for direct and indirect threaded
                   10979: systems (direct threaded systems require two-cell code fields on many
                   10980: machines).
                   10981: 
1.26      crook    10982: @cindex @code{DOES>}-handler
1.1       anton    10983: The other approach is that the code field points or jumps to the cell
1.26      crook    10984: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
                   10985: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
                   10986: @code{DOES>}-code address by computing the code address, i.e., the address of
1.1       anton    10987: the jump to dodoes, and add the length of that jump field. A variant of
                   10988: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
                   10989: return address (which can be found in the return register on RISCs) is
1.26      crook    10990: the @code{DOES>}-code address. Since the two cells available in the code field
1.1       anton    10991: are used up by the jump to the code address in direct threading on many
                   10992: architectures, we use this approach for direct threading on these
                   10993: architectures. We did not want to add another cell to the code field.
                   10994: 
                   10995: @node Primitives, Performance, Threading, Engine
                   10996: @section Primitives
                   10997: @cindex primitives, implementation
                   10998: @cindex virtual machine instructions, implementation
                   10999: 
                   11000: @menu
                   11001: * Automatic Generation::        
                   11002: * TOS Optimization::            
                   11003: * Produced code::               
                   11004: @end menu
                   11005: 
                   11006: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   11007: @subsection Automatic Generation
                   11008: @cindex primitives, automatic generation
                   11009: 
                   11010: @cindex @file{prims2x.fs}
                   11011: Since the primitives are implemented in a portable language, there is no
                   11012: longer any need to minimize the number of primitives. On the contrary,
                   11013: having many primitives has an advantage: speed. In order to reduce the
                   11014: number of errors in primitives and to make programming them easier, we
                   11015: provide a tool, the primitive generator (@file{prims2x.fs}), that
                   11016: automatically generates most (and sometimes all) of the C code for a
                   11017: primitive from the stack effect notation.  The source for a primitive
                   11018: has the following form:
                   11019: 
                   11020: @cindex primitive source format
                   11021: @format
1.29      crook    11022: @i{Forth-name} @i{stack-effect}        @i{category}    [@i{pronounc.}]
                   11023: [@code{""}@i{glossary entry}@code{""}]
                   11024: @i{C code}
1.1       anton    11025: [@code{:}
1.29      crook    11026: @i{Forth code}]
1.1       anton    11027: @end format
                   11028: 
                   11029: The items in brackets are optional. The category and glossary fields
                   11030: are there for generating the documentation, the Forth code is there
                   11031: for manual implementations on machines without GNU C. E.g., the source
                   11032: for the primitive @code{+} is:
                   11033: @example
                   11034: +    n1 n2 -- n    core    plus
                   11035: n = n1+n2;
                   11036: @end example
                   11037: 
                   11038: This looks like a specification, but in fact @code{n = n1+n2} is C
                   11039: code. Our primitive generation tool extracts a lot of information from
                   11040: the stack effect notations@footnote{We use a one-stack notation, even
                   11041: though we have separate data and floating-point stacks; The separate
                   11042: notation can be generated easily from the unified notation.}: The number
                   11043: of items popped from and pushed on the stack, their type, and by what
                   11044: name they are referred to in the C code. It then generates a C code
                   11045: prelude and postlude for each primitive. The final C code for @code{+}
                   11046: looks like this:
                   11047: 
                   11048: @example
                   11049: I_plus:        /* + ( n1 n2 -- n ) */  /* label, stack effect */
                   11050: /*  */                          /* documentation */
                   11051: @{
                   11052: DEF_CA                          /* definition of variable ca (indirect threading) */
                   11053: Cell n1;                        /* definitions of variables */
                   11054: Cell n2;
                   11055: Cell n;
                   11056: n1 = (Cell) sp[1];              /* input */
                   11057: n2 = (Cell) TOS;
                   11058: sp += 1;                        /* stack adjustment */
                   11059: NAME("+")                       /* debugging output (with -DDEBUG) */
                   11060: @{
                   11061: n = n1+n2;                      /* C code taken from the source */
                   11062: @}
                   11063: NEXT_P1;                        /* NEXT part 1 */
                   11064: TOS = (Cell)n;                  /* output */
                   11065: NEXT_P2;                        /* NEXT part 2 */
                   11066: @}
                   11067: @end example
                   11068: 
                   11069: This looks long and inefficient, but the GNU C compiler optimizes quite
                   11070: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   11071: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   11072: using them as intermediate storage also adds no cost.
                   11073: 
1.26      crook    11074: There are also other optimizations that are not illustrated by this
                   11075: example: assignments between simple variables are usually for free (copy
1.1       anton    11076: propagation). If one of the stack items is not used by the primitive
                   11077: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   11078: (dead code elimination). On the other hand, there are some things that
                   11079: the compiler does not do, therefore they are performed by
                   11080: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   11081: a stack item to the place where it just came from (e.g., @code{over}).
                   11082: 
                   11083: While programming a primitive is usually easy, there are a few cases
                   11084: where the programmer has to take the actions of the generator into
                   11085: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    11086: fall through to @code{NEXT}.
1.1       anton    11087: 
                   11088: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   11089: @subsection TOS Optimization
                   11090: @cindex TOS optimization for primitives
                   11091: @cindex primitives, keeping the TOS in a register
                   11092: 
                   11093: An important optimization for stack machine emulators, e.g., Forth
                   11094: engines, is keeping  one or more of the top stack items in
1.29      crook    11095: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   11096: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    11097: @itemize @bullet
                   11098: @item
1.29      crook    11099: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    11100: due to fewer loads from and stores to the stack.
1.29      crook    11101: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   11102: @i{y<n}, due to additional moves between registers.
1.1       anton    11103: @end itemize
                   11104: 
                   11105: @cindex -DUSE_TOS
                   11106: @cindex -DUSE_NO_TOS
                   11107: In particular, keeping one item in a register is never a disadvantage,
                   11108: if there are enough registers. Keeping two items in registers is a
                   11109: disadvantage for frequent words like @code{?branch}, constants,
                   11110: variables, literals and @code{i}. Therefore our generator only produces
                   11111: code that keeps zero or one items in registers. The generated C code
                   11112: covers both cases; the selection between these alternatives is made at
                   11113: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   11114: code for @code{+} is just a simple variable name in the one-item case,
                   11115: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   11116: GNU C compiler tries to keep simple variables like @code{TOS} in
                   11117: registers, and it usually succeeds, if there are enough registers.
                   11118: 
                   11119: @cindex -DUSE_FTOS
                   11120: @cindex -DUSE_NO_FTOS
                   11121: The primitive generator performs the TOS optimization for the
                   11122: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   11123: operations the benefit of this optimization is even larger:
                   11124: floating-point operations take quite long on most processors, but can be
                   11125: performed in parallel with other operations as long as their results are
                   11126: not used. If the FP-TOS is kept in a register, this works. If
                   11127: it is kept on the stack, i.e., in memory, the store into memory has to
                   11128: wait for the result of the floating-point operation, lengthening the
                   11129: execution time of the primitive considerably.
                   11130: 
                   11131: The TOS optimization makes the automatic generation of primitives a
                   11132: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   11133: @code{TOS} is not sufficient. There are some special cases to
                   11134: consider:
                   11135: @itemize @bullet
                   11136: @item In the case of @code{dup ( w -- w w )} the generator must not
                   11137: eliminate the store to the original location of the item on the stack,
                   11138: if the TOS optimization is turned on.
                   11139: @item Primitives with stack effects of the form @code{--}
1.29      crook    11140: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   11141: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    11142: must load the TOS from the stack at the end. But for the null stack
                   11143: effect @code{--} no stores or loads should be generated.
                   11144: @end itemize
                   11145: 
                   11146: @node Produced code,  , TOS Optimization, Primitives
                   11147: @subsection Produced code
                   11148: @cindex primitives, assembly code listing
                   11149: 
                   11150: @cindex @file{engine.s}
                   11151: To see what assembly code is produced for the primitives on your machine
                   11152: with your compiler and your flag settings, type @code{make engine.s} and
                   11153: look at the resulting file @file{engine.s}.
                   11154: 
                   11155: @node  Performance,  , Primitives, Engine
                   11156: @section Performance
                   11157: @cindex performance of some Forth interpreters
                   11158: @cindex engine performance
                   11159: @cindex benchmarking Forth systems
                   11160: @cindex Gforth performance
                   11161: 
                   11162: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
                   11163: impossible to write a significantly faster engine.
                   11164: 
                   11165: On register-starved machines like the 386 architecture processors
                   11166: improvements are possible, because @code{gcc} does not utilize the
                   11167: registers as well as a human, even with explicit register declarations;
                   11168: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   11169: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   11170: Sieve benchmark on a 486DX2/66 than Gforth compiled with
                   11171: @code{gcc-2.6.3} with @code{-DFORCE_REG}.
                   11172: 
                   11173: @cindex Win32Forth performance
                   11174: @cindex NT Forth performance
                   11175: @cindex eforth performance
                   11176: @cindex ThisForth performance
                   11177: @cindex PFE performance
                   11178: @cindex TILE performance
                   11179: However, this potential advantage of assembly language implementations
                   11180: is not necessarily realized in complete Forth systems: We compared
                   11181: Gforth (direct threaded, compiled with @code{gcc-2.6.3} and
                   11182: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
                   11183: 1994) and Eforth (with and without peephole (aka pinhole) optimization
                   11184: of the threaded code); all these systems were written in assembly
                   11185: language. We also compared Gforth with three systems written in C:
                   11186: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
                   11187: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21      crook    11188: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
                   11189: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1       anton    11190: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
                   11191: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
                   11192: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
                   11193: 486DX2/66 with similar memory performance under Windows NT. Marcel
                   11194: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
                   11195: added the peephole optimizer, ran the benchmarks and reported the
                   11196: results.
                   11197:  
                   11198: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   11199: matrix multiplication come from the Stanford integer benchmarks and have
                   11200: been translated into Forth by Martin Fraeman; we used the versions
                   11201: included in the TILE Forth package, but with bigger data set sizes; and
                   11202: a recursive Fibonacci number computation for benchmarking calling
                   11203: performance. The following table shows the time taken for the benchmarks
                   11204: scaled by the time taken by Gforth (in other words, it shows the speedup
                   11205: factor that Gforth achieved over the other systems).
                   11206: 
                   11207: @example
                   11208: relative      Win32-    NT       eforth       This-
                   11209:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
                   11210: sieve     1.00  1.39  1.14   1.39  0.85  1.58  3.18  8.58
                   11211: bubble    1.00  1.31  1.41   1.48  0.88  1.50        3.88
                   11212: matmul    1.00  1.47  1.35   1.46  0.74  1.58        4.09
                   11213: fib       1.00  1.52  1.34   1.22  0.86  1.74  2.99  4.30
                   11214: @end example
                   11215: 
1.26      crook    11216: You may be quite surprised by the good performance of Gforth when
                   11217: compared with systems written in assembly language. One important reason
                   11218: for the disappointing performance of these other systems is probably
                   11219: that they are not written optimally for the 486 (e.g., they use the
                   11220: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   11221: but costly method for relocating the Forth image: like @code{cforth}, it
                   11222: computes the actual addresses at run time, resulting in two address
                   11223: computations per @code{NEXT} (@pxref{Image File Background}).
                   11224: 
                   11225: Only Eforth with the peephole optimizer has a performance that is
                   11226: comparable to Gforth. The speedups achieved with peephole optimization
                   11227: of threaded code are quite remarkable. Adding a peephole optimizer to
                   11228: Gforth should cause similar speedups.
1.1       anton    11229: 
                   11230: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   11231: explained with the self-imposed restriction of the latter systems to
                   11232: standard C, which makes efficient threading impossible (however, the
1.4       anton    11233: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    11234: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   11235: Moreover, current C compilers have a hard time optimizing other aspects
                   11236: of the ThisForth and the TILE source.
                   11237: 
1.26      crook    11238: The performance of Gforth on 386 architecture processors varies widely
                   11239: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   11240: allocate any of the virtual machine registers into real machine
                   11241: registers by itself and would not work correctly with explicit register
                   11242: declarations, giving a 1.3 times slower engine (on a 486DX2/66 running
                   11243: the Sieve) than the one measured above.
1.1       anton    11244: 
1.26      crook    11245: Note that there have been several releases of Win32Forth since the
                   11246: release presented here, so the results presented above may have little
1.1       anton    11247: predictive value for the performance of Win32Forth today.
                   11248: 
                   11249: @cindex @file{Benchres}
                   11250: In @cite{Translating Forth to Efficient C} by M. Anton Ertl and Martin
                   11251: Maierhofer (presented at EuroForth '95), an indirect threaded version of
                   11252: Gforth is compared with Win32Forth, NT Forth, PFE, and ThisForth; that
                   11253: version of Gforth is 2%@minus{}8% slower on a 486 than the direct
                   11254: threaded version used here. The paper available at
                   11255: @*@url{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz};
                   11256: it also contains numbers for some native code systems. You can find a
                   11257: newer version of these measurements at
                   11258: @url{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
                   11259: find numbers for Gforth on various machines in @file{Benchres}.
                   11260: 
1.26      crook    11261: @c ******************************************************************
1.13      pazsan   11262: @node Binding to System Library, Cross Compiler, Engine, Top
1.14      pazsan   11263: @chapter Binding to System Library
1.13      pazsan   11264: 
                   11265: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14      pazsan   11266: @chapter Cross Compiler
1.13      pazsan   11267: 
                   11268: Cross Compiler
                   11269: 
                   11270: @menu
                   11271: * Using the Cross Compiler::
                   11272: * How the Cross Compiler Works::
                   11273: @end menu
                   11274: 
1.21      crook    11275: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   11276: @section Using the Cross Compiler
1.13      pazsan   11277: 
1.21      crook    11278: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14      pazsan   11279: @section How the Cross Compiler Works
1.13      pazsan   11280: 
                   11281: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    11282: @appendix Bugs
1.1       anton    11283: @cindex bug reporting
                   11284: 
1.21      crook    11285: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    11286: 
                   11287: If you find a bug, please send a bug report to
1.33      anton    11288: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21      crook    11289: information:
                   11290: 
                   11291: @itemize @bullet
                   11292: @item
                   11293: The Gforth version used (it is announced at the start of an
                   11294: interactive Gforth session).
                   11295: @item
                   11296: The machine and operating system (on Unix
                   11297: systems @code{uname -a} will report this information).
                   11298: @item
                   11299: The installation options (send the file @file{config.status}).
                   11300: @item
                   11301: A complete list of changes (if any) you (or your installer) have made to the
                   11302: Gforth sources.
                   11303: @item
                   11304: A program (or a sequence of keyboard commands) that reproduces the bug.
                   11305: @item
                   11306: A description of what you think constitutes the buggy behaviour.
                   11307: @end itemize
1.1       anton    11308: 
                   11309: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   11310: to Report Bugs, gcc.info, GNU C Manual}.
                   11311: 
                   11312: 
1.21      crook    11313: @node Origin, Forth-related information, Bugs, Top
                   11314: @appendix Authors and Ancestors of Gforth
1.1       anton    11315: 
                   11316: @section Authors and Contributors
                   11317: @cindex authors of Gforth
                   11318: @cindex contributors to Gforth
                   11319: 
                   11320: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
                   11321: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
                   11322: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
                   11323: with their continuous feedback. Lennart Benshop contributed
                   11324: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
                   11325: support for calling C libraries. Helpful comments also came from Paul
                   11326: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.12      anton    11327: Wavrik, Barrie Stott, Marc de Groot, and Jorge Acerada. Since the
                   11328: release of Gforth-0.2.1 there were also helpful comments from many
                   11329: others; thank you all, sorry for not listing you here (but digging
1.23      crook    11330: through my mailbox to extract your names is on my to-do list). Since the
                   11331: release of Gforth-0.4.0 Neal Crook worked on the manual.
1.1       anton    11332: 
                   11333: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   11334: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    11335: was developed across the Internet, and its authors did not meet
1.20      pazsan   11336: physically for the first 4 years of development.
1.1       anton    11337: 
                   11338: @section Pedigree
1.26      crook    11339: @cindex pedigree of Gforth
1.1       anton    11340: 
1.20      pazsan   11341: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1       anton    11342: Dirk Zoller) will cross-fertilize each other. Of course, a significant
                   11343: part of the design of Gforth was prescribed by ANS Forth.
                   11344: 
1.20      pazsan   11345: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    11346: 32 bit native code version of VolksForth for the Atari ST, written
                   11347: mostly by Dietrich Weineck.
                   11348: 
                   11349: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
                   11350: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
                   11351: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
                   11352: 
                   11353: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   11354: Forth-83 standard. !! Pedigree? When?
                   11355: 
                   11356: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   11357: 1979. Robert Selzer and Bill Ragsdale developed the original
                   11358: implementation of fig-Forth for the 6502 based on microForth.
                   11359: 
                   11360: The principal architect of microForth was Dean Sanderson. microForth was
                   11361: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   11362: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   11363: Z80.
                   11364: 
                   11365: All earlier Forth systems were custom-made, usually by Charles Moore,
                   11366: who discovered (as he puts it) Forth during the late 60s. The first full
                   11367: Forth existed in 1971.
                   11368: 
                   11369: A part of the information in this section comes from @cite{The Evolution
                   11370: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
                   11371: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
                   11372: Notices 28(3), 1993.  You can find more historical and genealogical
                   11373: information about Forth there.
                   11374: 
1.21      crook    11375: @node Forth-related information, Word Index, Origin, Top
                   11376: @appendix Other Forth-related information
                   11377: @cindex Forth-related information
                   11378: 
                   11379: @menu
                   11380: * Internet resources::
                   11381: * Books::
                   11382: * The Forth Interest Group::
                   11383: * Conferences::
                   11384: @end menu
                   11385: 
                   11386: 
                   11387: @node Internet resources, Books, Forth-related information, Forth-related information
                   11388: @section Internet resources
1.26      crook    11389: @cindex internet resources
1.21      crook    11390: 
                   11391: @cindex comp.lang.forth
                   11392: @cindex frequently asked questions
                   11393: There is an active newsgroup (comp.lang.forth) discussing Forth and
                   11394: Forth-related issues. A frequently-asked-questions (FAQ) list
                   11395: is posted to the newsgroup regulary, and archived at these sites:
                   11396: 
                   11397: @itemize @bullet
                   11398: @item
                   11399: @url{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
                   11400: @item
                   11401: @url{ftp://ftp.forth.org/pub/Forth/FAQ/}
                   11402: @end itemize
                   11403: 
                   11404: The FAQ list should be considered mandatory reading before posting to
                   11405: the newsgroup.
                   11406: 
                   11407: Here are some other web sites holding Forth-related material:
                   11408: 
                   11409: @itemize @bullet
                   11410: @item
                   11411: @url{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
                   11412: @item
                   11413: @url{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
                   11414: @item
                   11415: @url{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
                   11416: @item
                   11417: @url{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
                   11418: Research page, including links to the Journal of Forth Application and
                   11419: Research (JFAR) and a searchable Forth bibliography.
                   11420: @end itemize
                   11421: 
                   11422: 
                   11423: @node Books, The Forth Interest Group, Internet resources, Forth-related information
                   11424: @section Books
1.26      crook    11425: @cindex books on Forth
1.21      crook    11426: 
                   11427: As the Standard is relatively new, there are not many books out yet. It
                   11428: is not recommended to learn Forth by using Gforth and a book that is not
                   11429: written for ANS Forth, as you will not know your mistakes from the
                   11430: deviations of the book. However, books based on the Forth-83 standard
                   11431: should be ok, because ANS Forth is primarily an extension of Forth-83.
                   11432: 
                   11433: @cindex standard document for ANS Forth
                   11434: @cindex ANS Forth document
                   11435: The definite reference if you want to write ANS Forth programs is, of
1.26      crook    11436: course, the ANS Forth document. It is available in printed form from the
1.21      crook    11437: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
                   11438: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
                   11439: $200. You can also get it from Global Engineering Documents (Tel.: USA
                   11440: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
                   11441: 
                   11442: @cite{dpANS6}, the last draft of the standard, which was then submitted
                   11443: to ANSI for publication is available electronically and for free in some
                   11444: MS Word format, and it has been converted to HTML
                   11445: (@url{http://www.taygeta.com/forth/dpans.html}; this is my favourite
                   11446: format); this HTML version also includes the answers to Requests for
                   11447: Interpretation (RFIs). Some pointers to these versions can be found
                   11448: through @*@url{http://www.complang.tuwien.ac.at/projects/forth.html}.
                   11449: 
1.26      crook    11450: @cindex introductory book on Forth
                   11451: @cindex book on Forth, introductory
1.21      crook    11452: @cindex Woehr, Jack: @cite{Forth: The New Model}
                   11453: @cindex @cite{Forth: The new model} (book)
                   11454: @cite{Forth: The New Model} by Jack Woehr (Prentice-Hall, 1993) is an
                   11455: introductory book based on a draft version of the standard. It does not
                   11456: cover the whole standard. It also contains interesting background
                   11457: information (Jack Woehr was in the ANS Forth Technical Committee). It is
                   11458: not appropriate for complete newbies, but programmers experienced in
                   11459: other languages should find it ok.
                   11460: 
                   11461: @cindex Conklin, Edward K., and Elizabeth Rather: @cite{Forth Programmer's Handbook}
                   11462: @cindex Rather, Elizabeth and Edward K. Conklin: @cite{Forth Programmer's Handbook}
                   11463: @cindex @cite{Forth Programmer's Handbook} (book)
                   11464: @cite{Forth Programmer's Handbook} by Edward K. Conklin, Elizabeth
                   11465: D. Rather and the technical staff of Forth, Inc. (Forth, Inc., 1997;
                   11466: ISBN 0-9662156-0-5) contains little introductory material. The majority
                   11467: of the book is similar to @ref{Words}, but the book covers most of the
                   11468: standard words and some non-standard words (whereas this manual is
                   11469: quite incomplete). In addition, the book contains a chapter on
                   11470: programming style. The major drawback of this book is that it usually
                   11471: does not identify what is standard and what is specific to the Forth
                   11472: system described in the book (probably one of Forth, Inc.'s systems).
                   11473: Fortunately, many of the non-standard programming practices described in
                   11474: the book work in Gforth, too.  Still, this drawback makes the book
                   11475: hardly more useful than a pre-ANS book.
                   11476: 
                   11477: @node The Forth Interest Group, Conferences, Books, Forth-related information
                   11478: @section The Forth Interest Group
                   11479: @cindex Forth interest group (FIG)
                   11480: 
                   11481: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26      crook    11482: member-supported organisation. It publishes a regular magazine,
                   11483: @var{FORTH Dimensions}, and offers other benefits of membership. You can
                   11484: contact the FIG through their office email address:
                   11485: @email{office@@forth.org} or by visiting their web site at
                   11486: @url{http://www.forth.org/}. This web site also includes links to FIG
                   11487: chapters in other countries and American cities
1.21      crook    11488: (@url{http://www.forth.org/chapters.html}).
                   11489: 
                   11490: @node Conferences, , The Forth Interest Group, Forth-related information
                   11491: @section Conferences
                   11492: @cindex Conferences
                   11493: 
                   11494: There are several regular conferences related to Forth. They are all
1.26      crook    11495: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
                   11496: news group:
1.21      crook    11497: 
                   11498: @itemize @bullet
                   11499: @item
                   11500: FORML -- the Forth modification laboratory convenes every year near
                   11501: Monterey, California.
                   11502: @item
                   11503: The Rochester Forth Conference -- an annual conference traditionally
                   11504: held in Rochester, New York.
                   11505: @item
                   11506: EuroForth -- this European conference takes place annually.
                   11507: @end itemize
                   11508: 
                   11509: 
                   11510: @node Word Index, Concept Index, Forth-related information, Top
1.1       anton    11511: @unnumbered Word Index
                   11512: 
1.26      crook    11513: This index is a list of Forth words that have ``glossary'' entries
                   11514: within this manual. Each word is listed with its stack effect and
                   11515: wordset.
1.1       anton    11516: 
                   11517: @printindex fn
                   11518: 
                   11519: @node Concept Index,  , Word Index, Top
                   11520: @unnumbered Concept and Word Index
                   11521: 
1.26      crook    11522: Not all entries listed in this index are present verbatim in the
                   11523: text. This index also duplicates, in abbreviated form, all of the words
                   11524: listed in the Word Index (only the names are listed for the words here).
1.1       anton    11525: 
                   11526: @printindex cp
                   11527: 
                   11528: @contents
                   11529: @bye
                   11530: 

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