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

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.66    ! anton      17: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28      crook      18: 
1.1       anton      19: @comment %**start of header (This is for running Texinfo on a region.)
                     20: @setfilename gforth.info
                     21: @settitle Gforth Manual
                     22: @dircategory GNU programming tools
                     23: @direntry
                     24: * Gforth: (gforth).             A fast interpreter for the Forth language.
                     25: @end direntry
1.49      anton      26: @c The Texinfo manual also recommends doing this, but for Gforth it may
                     27: @c  not make much sense
                     28: @c @dircategory Individual utilities
                     29: @c @direntry
                     30: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
                     31: @c @end direntry
                     32: 
1.1       anton      33: @comment @setchapternewpage odd
1.29      crook      34: @comment TODO this gets left in by HTML converter
1.12      anton      35: @macro progstyle {}
                     36: Programming style note:
1.3       anton      37: @end macro
1.48      anton      38: 
                     39: @macro assignment {}
                     40: @table @i
                     41: @item Assignment:
                     42: @end macro
                     43: @macro endassignment {}
                     44: @end table
                     45: @end macro
                     46: 
1.1       anton      47: @comment %**end of header (This is for running Texinfo on a region.)
                     48: 
1.29      crook      49: 
                     50: @comment ----------------------------------------------------------
                     51: @comment macros for beautifying glossary entries
                     52: @comment if these are used, need to strip them out for HTML converter
                     53: @comment else they get repeated verbatim in HTML output.
                     54: @comment .. not working yet.
                     55: 
                     56: @macro GLOSS-START {}
                     57: @iftex
                     58: @ninerm
                     59: @end iftex
                     60: @end macro
                     61: 
                     62: @macro GLOSS-END {}
                     63: @iftex
                     64: @rm
                     65: @end iftex
                     66: @end macro
                     67: 
                     68: @comment ----------------------------------------------------------
                     69: 
                     70: 
1.10      anton      71: @include version.texi
                     72: 
1.49      anton      73: @ifnottex
1.11      anton      74: This file documents Gforth @value{VERSION}
1.1       anton      75: 
1.62      crook      76: Copyright @copyright{} 1995--2000 Free Software Foundation, Inc.
1.1       anton      77: 
                     78:      Permission is granted to make and distribute verbatim copies of
                     79:      this manual provided the copyright notice and this permission notice
                     80:      are preserved on all copies.
                     81:      
                     82: @ignore
                     83:      Permission is granted to process this file through TeX and print the
                     84:      results, provided the printed document carries a copying permission
                     85:      notice identical to this one except for the removal of this paragraph
                     86:      (this paragraph not being relevant to the printed manual).
                     87:      
                     88: @end ignore
                     89:      Permission is granted to copy and distribute modified versions of this
                     90:      manual under the conditions for verbatim copying, provided also that the
                     91:      sections entitled "Distribution" and "General Public License" are
                     92:      included exactly as in the original, and provided that the entire
                     93:      resulting derived work is distributed under the terms of a permission
                     94:      notice identical to this one.
                     95:      
                     96:      Permission is granted to copy and distribute translations of this manual
                     97:      into another language, under the above conditions for modified versions,
                     98:      except that the sections entitled "Distribution" and "General Public
                     99:      License" may be included in a translation approved by the author instead
                    100:      of in the original English.
1.49      anton     101: @end ifnottex
1.1       anton     102: 
                    103: @finalout
                    104: @titlepage
                    105: @sp 10
                    106: @center @titlefont{Gforth Manual}
                    107: @sp 2
1.11      anton     108: @center for version @value{VERSION}
1.1       anton     109: @sp 2
1.34      anton     110: @center Neal Crook
1.1       anton     111: @center Anton Ertl
1.6       pazsan    112: @center Bernd Paysan
1.5       anton     113: @center Jens Wilke
1.1       anton     114: @sp 3
1.47      crook     115: @center This manual is permanently under construction and was last updated on 15-Mar-2000
1.1       anton     116: 
                    117: @comment  The following two commands start the copyright page.
                    118: @page
                    119: @vskip 0pt plus 1filll
1.62      crook     120: Copyright @copyright{} 1995--2000 Free Software Foundation, Inc.
1.1       anton     121: 
                    122: @comment !! Published by ... or You can get a copy of this manual ...
                    123: 
                    124:      Permission is granted to make and distribute verbatim copies of
                    125:      this manual provided the copyright notice and this permission notice
                    126:      are preserved on all copies.
                    127:      
                    128:      Permission is granted to copy and distribute modified versions of this
                    129:      manual under the conditions for verbatim copying, provided also that the
                    130:      sections entitled "Distribution" and "General Public License" are
                    131:      included exactly as in the original, and provided that the entire
                    132:      resulting derived work is distributed under the terms of a permission
                    133:      notice identical to this one.
                    134:      
                    135:      Permission is granted to copy and distribute translations of this manual
                    136:      into another language, under the above conditions for modified versions,
                    137:      except that the sections entitled "Distribution" and "General Public
                    138:      License" may be included in a translation approved by the author instead
                    139:      of in the original English.
                    140: @end titlepage
                    141: 
                    142: @node Top, License, (dir), (dir)
1.49      anton     143: @ifnottex
1.1       anton     144: Gforth is a free implementation of ANS Forth available on many
1.11      anton     145: personal machines. This manual corresponds to version @value{VERSION}.
1.49      anton     146: @end ifnottex
1.1       anton     147: 
                    148: @menu
1.21      crook     149: * License::                     The GPL
1.26      crook     150: * Goals::                       About the Gforth Project
1.29      crook     151: * Gforth Environment::          Starting (and exiting) Gforth
1.48      anton     152: * Tutorial::                    Hands-on Forth Tutorial
1.21      crook     153: * Introduction::                An introduction to ANS Forth
1.1       anton     154: * Words::                       Forth words available in Gforth
1.24      anton     155: * Error messages::              How to interpret them
1.1       anton     156: * Tools::                       Programming tools
                    157: * ANS conformance::             Implementation-defined options etc.
1.65      anton     158: * Standard vs Extensions::      Should I use extensions?
1.1       anton     159: * Model::                       The abstract machine of Gforth
                    160: * Integrating Gforth::          Forth as scripting language for applications
                    161: * Emacs and Gforth::            The Gforth Mode
                    162: * Image Files::                 @code{.fi} files contain compiled code
                    163: * Engine::                      The inner interpreter and the primitives
1.24      anton     164: * Binding to System Library::   
1.13      pazsan    165: * Cross Compiler::              The Cross Compiler
1.1       anton     166: * Bugs::                        How to report them
                    167: * Origin::                      Authors and ancestors of Gforth
1.21      crook     168: * Forth-related information::   Books and places to look on the WWW
1.1       anton     169: * Word Index::                  An item for each Forth word
1.41      anton     170: * Name Index::                  Forth words, only names listed
1.1       anton     171: * Concept Index::               A menu covering many topics
1.12      anton     172: 
1.48      anton     173: @detailmenu --- The Detailed Node Listing ---
1.12      anton     174: 
1.29      crook     175: Gforth Environment
                    176: 
1.32      anton     177: * Invoking Gforth::             Getting in
                    178: * Leaving Gforth::              Getting out
                    179: * Command-line editing::        
1.48      anton     180: * Environment variables::       that affect how Gforth starts up
1.32      anton     181: * Gforth Files::                What gets installed and where
1.48      anton     182: * Startup speed::               When 35ms is not fast enough ...
                    183: 
                    184: Forth Tutorial
                    185: 
                    186: * Starting Gforth Tutorial::    
                    187: * Syntax Tutorial::             
                    188: * Crash Course Tutorial::       
                    189: * Stack Tutorial::              
                    190: * Arithmetics Tutorial::        
                    191: * Stack Manipulation Tutorial::  
                    192: * Using files for Forth code Tutorial::  
                    193: * Comments Tutorial::           
                    194: * Colon Definitions Tutorial::  
                    195: * Decompilation Tutorial::      
                    196: * Stack-Effect Comments Tutorial::  
                    197: * Types Tutorial::              
                    198: * Factoring Tutorial::          
                    199: * Designing the stack effect Tutorial::  
                    200: * Local Variables Tutorial::    
                    201: * Conditional execution Tutorial::  
                    202: * Flags and Comparisons Tutorial::  
                    203: * General Loops Tutorial::      
                    204: * Counted loops Tutorial::      
                    205: * Recursion Tutorial::          
                    206: * Leaving definitions or loops Tutorial::  
                    207: * Return Stack Tutorial::       
                    208: * Memory Tutorial::             
                    209: * Characters and Strings Tutorial::  
                    210: * Alignment Tutorial::          
                    211: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                    212: * Execution Tokens Tutorial::   
                    213: * Exceptions Tutorial::         
                    214: * Defining Words Tutorial::     
                    215: * Arrays and Records Tutorial::  
                    216: * POSTPONE Tutorial::           
                    217: * Literal Tutorial::            
                    218: * Advanced macros Tutorial::    
                    219: * Compilation Tokens Tutorial::  
                    220: * Wordlists and Search Order Tutorial::  
1.29      crook     221: 
1.24      anton     222: An Introduction to ANS Forth
                    223: 
                    224: * Introducing the Text Interpreter::
                    225: * Stacks and Postfix notation::
                    226: * Your first definition::
                    227: * How does that work?::
                    228: * Forth is written in Forth::
                    229: * Review - elements of a Forth system::
1.29      crook     230: * Where to go next::
1.24      anton     231: * Exercises::
                    232: 
1.12      anton     233: Forth Words
                    234: 
                    235: * Notation::                    
1.65      anton     236: * Case insensitivity::          
                    237: * Comments::                    
                    238: * Boolean Flags::               
1.12      anton     239: * Arithmetic::                  
                    240: * Stack Manipulation::          
                    241: * Memory::                      
                    242: * Control Structures::          
                    243: * Defining Words::              
1.65      anton     244: * Interpretation and Compilation Semantics::  
1.47      crook     245: * Tokens for Words::            
1.65      anton     246: * The Text Interpreter::        
                    247: * Word Lists::                  
                    248: * Environmental Queries::       
1.12      anton     249: * Files::                       
                    250: * Blocks::                      
                    251: * Other I/O::                   
                    252: * Programming Tools::           
                    253: * Assembler and Code Words::    
                    254: * Threading Words::             
1.26      crook     255: * Locals::                      
                    256: * Structures::                  
                    257: * Object-oriented Forth::       
1.65      anton     258: * Passing Commands to the OS::  
                    259: * Keeping track of Time::       
                    260: * Miscellaneous Words::         
1.12      anton     261: 
                    262: Arithmetic
                    263: 
                    264: * Single precision::            
                    265: * Bitwise operations::          
1.21      crook     266: * Double precision::            Double-cell integer arithmetic
                    267: * Numeric comparison::
1.32      anton     268: * Mixed precision::             Operations with single and double-cell integers
1.12      anton     269: * Floating Point::              
                    270: 
                    271: Stack Manipulation
                    272: 
                    273: * Data stack::                  
                    274: * Floating point stack::        
                    275: * Return stack::                
                    276: * Locals stack::                
                    277: * Stack pointer manipulation::  
                    278: 
                    279: Memory
                    280: 
1.32      anton     281: * Memory model::                
                    282: * Dictionary allocation::       
                    283: * Heap Allocation::             
                    284: * Memory Access::               
                    285: * Address arithmetic::          
                    286: * Memory Blocks::               
1.12      anton     287: 
                    288: Control Structures
                    289: 
1.41      anton     290: * Selection::                   IF ... ELSE ... ENDIF
                    291: * Simple Loops::                BEGIN ...
1.32      anton     292: * Counted Loops::               DO
                    293: * Arbitrary control structures::
                    294: * Calls and returns::
1.12      anton     295: * Exception Handling::          
                    296: 
                    297: Defining Words
                    298: 
1.45      crook     299: * CREATE::
1.44      crook     300: * Variables::                   Variables and user variables
                    301: * Constants::
                    302: * Values::                      Initialised variables
1.32      anton     303: * Colon Definitions::
1.44      crook     304: * Anonymous Definitions::       Definitions without names
1.32      anton     305: * User-defined Defining Words::
1.44      crook     306: * Deferred words::              Allow forward references
                    307: * Aliases::
1.32      anton     308: * Supplying names::
1.47      crook     309: 
1.63      anton     310: User-defined Defining Words
                    311: 
                    312: * CREATE..DOES> applications::  
                    313: * CREATE..DOES> details::       
                    314: * Advanced does> usage example::  
                    315: 
1.47      crook     316: Interpretation and Compilation Semantics
                    317: 
1.44      crook     318: * Combined words::
1.12      anton     319: 
1.21      crook     320: The Text Interpreter
                    321: 
1.29      crook     322: * Input Sources::
1.21      crook     323: * Number Conversion::
                    324: * Interpret/Compile states::
                    325: * Literals::
                    326: * Interpreter Directives::
                    327: 
1.26      crook     328: Word Lists
                    329: 
                    330: * Why use word lists?::
                    331: * Word list examples::
                    332: 
                    333: Files
                    334: 
1.48      anton     335: * Forth source files::          
                    336: * General files::               
                    337: * Search Paths::                
                    338: 
                    339: Search Paths
                    340: 
                    341: * Forth Search Paths::          
1.26      crook     342: * General Search Paths::        
                    343: 
                    344: Other I/O
                    345: 
1.32      anton     346: * Simple numeric output::       Predefined formats
                    347: * Formatted numeric output::    Formatted (pictured) output
                    348: * String Formats::              How Forth stores strings in memory
                    349: * Displaying characters and strings:: Other stuff
                    350: * Input::                       Input
1.26      crook     351: 
                    352: Programming Tools
                    353: 
                    354: * Debugging::                   Simple and quick.
                    355: * Assertions::                  Making your programs self-checking.
1.46      pazsan    356: * Singlestep Debugger::         Executing your program word by word.
1.26      crook     357: 
1.63      anton     358: Assembler and Code Words
                    359: 
                    360: * Code and ;code::              
                    361: * Common Assembler::            Assembler Syntax
                    362: * Common Disassembler::         
                    363: * 386 Assembler::               Deviations and special cases
                    364: * Alpha Assembler::             Deviations and special cases
                    365: * MIPS assembler::              Deviations and special cases
                    366: * Other assemblers::            How to write them
                    367: 
1.26      crook     368: Locals
                    369: 
                    370: * Gforth locals::               
                    371: * ANS Forth locals::            
                    372: 
                    373: Gforth locals
                    374: 
                    375: * Where are locals visible by name?::  
                    376: * How long do locals live?::    
                    377: * Programming Style::           
                    378: * Implementation::              
                    379: 
1.12      anton     380: Structures
                    381: 
                    382: * Why explicit structure support?::  
                    383: * Structure Usage::             
                    384: * Structure Naming Convention::  
                    385: * Structure Implementation::    
                    386: * Structure Glossary::          
                    387: 
                    388: Object-oriented Forth
                    389: 
1.48      anton     390: * Why object-oriented programming?::  
                    391: * Object-Oriented Terminology::  
                    392: * Objects::                     
                    393: * OOF::                         
                    394: * Mini-OOF::                    
1.23      crook     395: * Comparison with other object models::  
1.12      anton     396: 
1.24      anton     397: The @file{objects.fs} model
1.12      anton     398: 
                    399: * Properties of the Objects model::  
                    400: * Basic Objects Usage::         
1.41      anton     401: * The Objects base class::      
1.12      anton     402: * Creating objects::            
                    403: * Object-Oriented Programming Style::  
                    404: * Class Binding::               
                    405: * Method conveniences::         
                    406: * Classes and Scoping::         
1.41      anton     407: * Dividing classes::            
1.12      anton     408: * Object Interfaces::           
                    409: * Objects Implementation::      
                    410: * Objects Glossary::            
                    411: 
1.24      anton     412: The @file{oof.fs} model
1.12      anton     413: 
                    414: * Properties of the OOF model::
                    415: * Basic OOF Usage::
1.23      crook     416: * The OOF base class::
1.12      anton     417: * Class Declaration::
                    418: * Class Implementation::
                    419: 
1.24      anton     420: The @file{mini-oof.fs} model
1.23      crook     421: 
1.48      anton     422: * Basic Mini-OOF Usage::        
                    423: * Mini-OOF Example::            
                    424: * Mini-OOF Implementation::     
                    425: * Comparison with other object models::  
1.23      crook     426: 
1.12      anton     427: Tools
                    428: 
                    429: * ANS Report::                  Report the words used, sorted by wordset.
                    430: 
                    431: ANS conformance
                    432: 
                    433: * The Core Words::              
                    434: * The optional Block word set::  
                    435: * The optional Double Number word set::  
                    436: * The optional Exception word set::  
                    437: * The optional Facility word set::  
                    438: * The optional File-Access word set::  
                    439: * The optional Floating-Point word set::  
                    440: * The optional Locals word set::  
                    441: * The optional Memory-Allocation word set::  
                    442: * The optional Programming-Tools word set::  
                    443: * The optional Search-Order word set::  
                    444: 
                    445: The Core Words
                    446: 
                    447: * core-idef::                   Implementation Defined Options                   
                    448: * core-ambcond::                Ambiguous Conditions                
                    449: * core-other::                  Other System Documentation                  
                    450: 
                    451: The optional Block word set
                    452: 
                    453: * block-idef::                  Implementation Defined Options
                    454: * block-ambcond::               Ambiguous Conditions               
                    455: * block-other::                 Other System Documentation                 
                    456: 
                    457: The optional Double Number word set
                    458: 
                    459: * double-ambcond::              Ambiguous Conditions              
                    460: 
                    461: The optional Exception word set
                    462: 
                    463: * exception-idef::              Implementation Defined Options              
                    464: 
                    465: The optional Facility word set
                    466: 
                    467: * facility-idef::               Implementation Defined Options               
                    468: * facility-ambcond::            Ambiguous Conditions            
                    469: 
                    470: The optional File-Access word set
                    471: 
                    472: * file-idef::                   Implementation Defined Options
                    473: * file-ambcond::                Ambiguous Conditions                
                    474: 
                    475: The optional Floating-Point word set
                    476: 
                    477: * floating-idef::               Implementation Defined Options
                    478: * floating-ambcond::            Ambiguous Conditions            
                    479: 
                    480: The optional Locals word set
                    481: 
                    482: * locals-idef::                 Implementation Defined Options                 
                    483: * locals-ambcond::              Ambiguous Conditions              
                    484: 
                    485: The optional Memory-Allocation word set
                    486: 
                    487: * memory-idef::                 Implementation Defined Options                 
                    488: 
                    489: The optional Programming-Tools word set
                    490: 
                    491: * programming-idef::            Implementation Defined Options            
                    492: * programming-ambcond::         Ambiguous Conditions         
                    493: 
                    494: The optional Search-Order word set
                    495: 
                    496: * search-idef::                 Implementation Defined Options                 
                    497: * search-ambcond::              Ambiguous Conditions              
                    498: 
                    499: Image Files
                    500: 
1.24      anton     501: * Image Licensing Issues::      Distribution terms for images.
                    502: * Image File Background::       Why have image files?
1.32      anton     503: * Non-Relocatable Image Files::   don't always work.
1.24      anton     504: * Data-Relocatable Image Files::  are better.
1.32      anton     505: * Fully Relocatable Image Files:: better yet.
1.24      anton     506: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     507: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     508: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     509: 
                    510: Fully Relocatable Image Files
                    511: 
1.27      crook     512: * gforthmi::                    The normal way
1.12      anton     513: * cross.fs::                    The hard way
                    514: 
                    515: Engine
                    516: 
                    517: * Portability::                 
                    518: * Threading::                   
                    519: * Primitives::                  
                    520: * Performance::                 
                    521: 
                    522: Threading
                    523: 
                    524: * Scheduling::                  
                    525: * Direct or Indirect Threaded?::  
                    526: * DOES>::                       
                    527: 
                    528: Primitives
                    529: 
                    530: * Automatic Generation::        
                    531: * TOS Optimization::            
                    532: * Produced code::               
1.13      pazsan    533: 
                    534: Cross Compiler
                    535: 
                    536: * Using the Cross Compiler::
                    537: * How the Cross Compiler Works::
                    538: 
1.24      anton     539: Other Forth-related information
1.21      crook     540: 
                    541: * Internet resources::
                    542: * Books::
                    543: * The Forth Interest Group::
                    544: * Conferences::
                    545: 
1.24      anton     546: @end detailmenu
1.1       anton     547: @end menu
                    548: 
1.26      crook     549: @node License, Goals, Top, Top
1.1       anton     550: @unnumbered GNU GENERAL PUBLIC LICENSE
                    551: @center Version 2, June 1991
                    552: 
                    553: @display
                    554: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
                    555: 675 Mass Ave, Cambridge, MA 02139, USA
                    556: 
                    557: Everyone is permitted to copy and distribute verbatim copies
                    558: of this license document, but changing it is not allowed.
                    559: @end display
                    560: 
                    561: @unnumberedsec Preamble
                    562: 
                    563:   The licenses for most software are designed to take away your
                    564: freedom to share and change it.  By contrast, the GNU General Public
                    565: License is intended to guarantee your freedom to share and change free
                    566: software---to make sure the software is free for all its users.  This
                    567: General Public License applies to most of the Free Software
                    568: Foundation's software and to any other program whose authors commit to
                    569: using it.  (Some other Free Software Foundation software is covered by
                    570: the GNU Library General Public License instead.)  You can apply it to
                    571: your programs, too.
                    572: 
                    573:   When we speak of free software, we are referring to freedom, not
                    574: price.  Our General Public Licenses are designed to make sure that you
                    575: have the freedom to distribute copies of free software (and charge for
                    576: this service if you wish), that you receive source code or can get it
                    577: if you want it, that you can change the software or use pieces of it
                    578: in new free programs; and that you know you can do these things.
                    579: 
                    580:   To protect your rights, we need to make restrictions that forbid
                    581: anyone to deny you these rights or to ask you to surrender the rights.
                    582: These restrictions translate to certain responsibilities for you if you
                    583: distribute copies of the software, or if you modify it.
                    584: 
                    585:   For example, if you distribute copies of such a program, whether
                    586: gratis or for a fee, you must give the recipients all the rights that
                    587: you have.  You must make sure that they, too, receive or can get the
                    588: source code.  And you must show them these terms so they know their
                    589: rights.
                    590: 
                    591:   We protect your rights with two steps: (1) copyright the software, and
                    592: (2) offer you this license which gives you legal permission to copy,
                    593: distribute and/or modify the software.
                    594: 
                    595:   Also, for each author's protection and ours, we want to make certain
                    596: that everyone understands that there is no warranty for this free
                    597: software.  If the software is modified by someone else and passed on, we
                    598: want its recipients to know that what they have is not the original, so
                    599: that any problems introduced by others will not reflect on the original
                    600: authors' reputations.
                    601: 
                    602:   Finally, any free program is threatened constantly by software
                    603: patents.  We wish to avoid the danger that redistributors of a free
                    604: program will individually obtain patent licenses, in effect making the
                    605: program proprietary.  To prevent this, we have made it clear that any
                    606: patent must be licensed for everyone's free use or not licensed at all.
                    607: 
                    608:   The precise terms and conditions for copying, distribution and
                    609: modification follow.
                    610: 
                    611: @iftex
                    612: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    613: @end iftex
1.49      anton     614: @ifnottex
1.1       anton     615: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
1.49      anton     616: @end ifnottex
1.1       anton     617: 
                    618: @enumerate 0
                    619: @item
                    620: This License applies to any program or other work which contains
                    621: a notice placed by the copyright holder saying it may be distributed
                    622: under the terms of this General Public License.  The ``Program'', below,
                    623: refers to any such program or work, and a ``work based on the Program''
                    624: means either the Program or any derivative work under copyright law:
                    625: that is to say, a work containing the Program or a portion of it,
                    626: either verbatim or with modifications and/or translated into another
                    627: language.  (Hereinafter, translation is included without limitation in
                    628: the term ``modification''.)  Each licensee is addressed as ``you''.
                    629: 
                    630: Activities other than copying, distribution and modification are not
                    631: covered by this License; they are outside its scope.  The act of
                    632: running the Program is not restricted, and the output from the Program
                    633: is covered only if its contents constitute a work based on the
                    634: Program (independent of having been made by running the Program).
                    635: Whether that is true depends on what the Program does.
                    636: 
                    637: @item
                    638: You may copy and distribute verbatim copies of the Program's
                    639: source code as you receive it, in any medium, provided that you
                    640: conspicuously and appropriately publish on each copy an appropriate
                    641: copyright notice and disclaimer of warranty; keep intact all the
                    642: notices that refer to this License and to the absence of any warranty;
                    643: and give any other recipients of the Program a copy of this License
                    644: along with the Program.
                    645: 
                    646: You may charge a fee for the physical act of transferring a copy, and
                    647: you may at your option offer warranty protection in exchange for a fee.
                    648: 
                    649: @item
                    650: You may modify your copy or copies of the Program or any portion
                    651: of it, thus forming a work based on the Program, and copy and
                    652: distribute such modifications or work under the terms of Section 1
                    653: above, provided that you also meet all of these conditions:
                    654: 
                    655: @enumerate a
                    656: @item
                    657: You must cause the modified files to carry prominent notices
                    658: stating that you changed the files and the date of any change.
                    659: 
                    660: @item
                    661: You must cause any work that you distribute or publish, that in
                    662: whole or in part contains or is derived from the Program or any
                    663: part thereof, to be licensed as a whole at no charge to all third
                    664: parties under the terms of this License.
                    665: 
                    666: @item
                    667: If the modified program normally reads commands interactively
                    668: when run, you must cause it, when started running for such
                    669: interactive use in the most ordinary way, to print or display an
                    670: announcement including an appropriate copyright notice and a
                    671: notice that there is no warranty (or else, saying that you provide
                    672: a warranty) and that users may redistribute the program under
                    673: these conditions, and telling the user how to view a copy of this
                    674: License.  (Exception: if the Program itself is interactive but
                    675: does not normally print such an announcement, your work based on
                    676: the Program is not required to print an announcement.)
                    677: @end enumerate
                    678: 
                    679: These requirements apply to the modified work as a whole.  If
                    680: identifiable sections of that work are not derived from the Program,
                    681: and can be reasonably considered independent and separate works in
                    682: themselves, then this License, and its terms, do not apply to those
                    683: sections when you distribute them as separate works.  But when you
                    684: distribute the same sections as part of a whole which is a work based
                    685: on the Program, the distribution of the whole must be on the terms of
                    686: this License, whose permissions for other licensees extend to the
                    687: entire whole, and thus to each and every part regardless of who wrote it.
                    688: 
                    689: Thus, it is not the intent of this section to claim rights or contest
                    690: your rights to work written entirely by you; rather, the intent is to
                    691: exercise the right to control the distribution of derivative or
                    692: collective works based on the Program.
                    693: 
                    694: In addition, mere aggregation of another work not based on the Program
                    695: with the Program (or with a work based on the Program) on a volume of
                    696: a storage or distribution medium does not bring the other work under
                    697: the scope of this License.
                    698: 
                    699: @item
                    700: You may copy and distribute the Program (or a work based on it,
                    701: under Section 2) in object code or executable form under the terms of
                    702: Sections 1 and 2 above provided that you also do one of the following:
                    703: 
                    704: @enumerate a
                    705: @item
                    706: Accompany it with the complete corresponding machine-readable
                    707: source code, which must be distributed under the terms of Sections
                    708: 1 and 2 above on a medium customarily used for software interchange; or,
                    709: 
                    710: @item
                    711: Accompany it with a written offer, valid for at least three
                    712: years, to give any third party, for a charge no more than your
                    713: cost of physically performing source distribution, a complete
                    714: machine-readable copy of the corresponding source code, to be
                    715: distributed under the terms of Sections 1 and 2 above on a medium
                    716: customarily used for software interchange; or,
                    717: 
                    718: @item
                    719: Accompany it with the information you received as to the offer
                    720: to distribute corresponding source code.  (This alternative is
                    721: allowed only for noncommercial distribution and only if you
                    722: received the program in object code or executable form with such
                    723: an offer, in accord with Subsection b above.)
                    724: @end enumerate
                    725: 
                    726: The source code for a work means the preferred form of the work for
                    727: making modifications to it.  For an executable work, complete source
                    728: code means all the source code for all modules it contains, plus any
                    729: associated interface definition files, plus the scripts used to
                    730: control compilation and installation of the executable.  However, as a
                    731: special exception, the source code distributed need not include
                    732: anything that is normally distributed (in either source or binary
                    733: form) with the major components (compiler, kernel, and so on) of the
                    734: operating system on which the executable runs, unless that component
                    735: itself accompanies the executable.
                    736: 
                    737: If distribution of executable or object code is made by offering
                    738: access to copy from a designated place, then offering equivalent
                    739: access to copy the source code from the same place counts as
                    740: distribution of the source code, even though third parties are not
                    741: compelled to copy the source along with the object code.
                    742: 
                    743: @item
                    744: You may not copy, modify, sublicense, or distribute the Program
                    745: except as expressly provided under this License.  Any attempt
                    746: otherwise to copy, modify, sublicense or distribute the Program is
                    747: void, and will automatically terminate your rights under this License.
                    748: However, parties who have received copies, or rights, from you under
                    749: this License will not have their licenses terminated so long as such
                    750: parties remain in full compliance.
                    751: 
                    752: @item
                    753: You are not required to accept this License, since you have not
                    754: signed it.  However, nothing else grants you permission to modify or
                    755: distribute the Program or its derivative works.  These actions are
                    756: prohibited by law if you do not accept this License.  Therefore, by
                    757: modifying or distributing the Program (or any work based on the
                    758: Program), you indicate your acceptance of this License to do so, and
                    759: all its terms and conditions for copying, distributing or modifying
                    760: the Program or works based on it.
                    761: 
                    762: @item
                    763: Each time you redistribute the Program (or any work based on the
                    764: Program), the recipient automatically receives a license from the
                    765: original licensor to copy, distribute or modify the Program subject to
                    766: these terms and conditions.  You may not impose any further
                    767: restrictions on the recipients' exercise of the rights granted herein.
                    768: You are not responsible for enforcing compliance by third parties to
                    769: this License.
                    770: 
                    771: @item
                    772: If, as a consequence of a court judgment or allegation of patent
                    773: infringement or for any other reason (not limited to patent issues),
                    774: conditions are imposed on you (whether by court order, agreement or
                    775: otherwise) that contradict the conditions of this License, they do not
                    776: excuse you from the conditions of this License.  If you cannot
                    777: distribute so as to satisfy simultaneously your obligations under this
                    778: License and any other pertinent obligations, then as a consequence you
                    779: may not distribute the Program at all.  For example, if a patent
                    780: license would not permit royalty-free redistribution of the Program by
                    781: all those who receive copies directly or indirectly through you, then
                    782: the only way you could satisfy both it and this License would be to
                    783: refrain entirely from distribution of the Program.
                    784: 
                    785: If any portion of this section is held invalid or unenforceable under
                    786: any particular circumstance, the balance of the section is intended to
                    787: apply and the section as a whole is intended to apply in other
                    788: circumstances.
                    789: 
                    790: It is not the purpose of this section to induce you to infringe any
                    791: patents or other property right claims or to contest validity of any
                    792: such claims; this section has the sole purpose of protecting the
                    793: integrity of the free software distribution system, which is
                    794: implemented by public license practices.  Many people have made
                    795: generous contributions to the wide range of software distributed
                    796: through that system in reliance on consistent application of that
                    797: system; it is up to the author/donor to decide if he or she is willing
                    798: to distribute software through any other system and a licensee cannot
                    799: impose that choice.
                    800: 
                    801: This section is intended to make thoroughly clear what is believed to
                    802: be a consequence of the rest of this License.
                    803: 
                    804: @item
                    805: If the distribution and/or use of the Program is restricted in
                    806: certain countries either by patents or by copyrighted interfaces, the
                    807: original copyright holder who places the Program under this License
                    808: may add an explicit geographical distribution limitation excluding
                    809: those countries, so that distribution is permitted only in or among
                    810: countries not thus excluded.  In such case, this License incorporates
                    811: the limitation as if written in the body of this License.
                    812: 
                    813: @item
                    814: The Free Software Foundation may publish revised and/or new versions
                    815: of the General Public License from time to time.  Such new versions will
                    816: be similar in spirit to the present version, but may differ in detail to
                    817: address new problems or concerns.
                    818: 
                    819: Each version is given a distinguishing version number.  If the Program
                    820: specifies a version number of this License which applies to it and ``any
                    821: later version'', you have the option of following the terms and conditions
                    822: either of that version or of any later version published by the Free
                    823: Software Foundation.  If the Program does not specify a version number of
                    824: this License, you may choose any version ever published by the Free Software
                    825: Foundation.
                    826: 
                    827: @item
                    828: If you wish to incorporate parts of the Program into other free
                    829: programs whose distribution conditions are different, write to the author
                    830: to ask for permission.  For software which is copyrighted by the Free
                    831: Software Foundation, write to the Free Software Foundation; we sometimes
                    832: make exceptions for this.  Our decision will be guided by the two goals
                    833: of preserving the free status of all derivatives of our free software and
                    834: of promoting the sharing and reuse of software generally.
                    835: 
                    836: @iftex
                    837: @heading NO WARRANTY
                    838: @end iftex
1.49      anton     839: @ifnottex
1.1       anton     840: @center NO WARRANTY
1.49      anton     841: @end ifnottex
1.1       anton     842: 
                    843: @item
                    844: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
                    845: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
                    846: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
                    847: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
                    848: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
                    849: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
                    850: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
                    851: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
                    852: REPAIR OR CORRECTION.
                    853: 
                    854: @item
                    855: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                    856: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
                    857: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
                    858: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
                    859: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
                    860: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
                    861: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
                    862: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
                    863: POSSIBILITY OF SUCH DAMAGES.
                    864: @end enumerate
                    865: 
                    866: @iftex
                    867: @heading END OF TERMS AND CONDITIONS
                    868: @end iftex
1.49      anton     869: @ifnottex
1.1       anton     870: @center END OF TERMS AND CONDITIONS
1.49      anton     871: @end ifnottex
1.1       anton     872: 
                    873: @page
                    874: @unnumberedsec How to Apply These Terms to Your New Programs
                    875: 
                    876:   If you develop a new program, and you want it to be of the greatest
                    877: possible use to the public, the best way to achieve this is to make it
                    878: free software which everyone can redistribute and change under these terms.
                    879: 
                    880:   To do so, attach the following notices to the program.  It is safest
                    881: to attach them to the start of each source file to most effectively
                    882: convey the exclusion of warranty; and each file should have at least
                    883: the ``copyright'' line and a pointer to where the full notice is found.
                    884: 
                    885: @smallexample
                    886: @var{one line to give the program's name and a brief idea of what it does.}
                    887: Copyright (C) 19@var{yy}  @var{name of author}
                    888: 
                    889: This program is free software; you can redistribute it and/or modify 
                    890: it under the terms of the GNU General Public License as published by 
                    891: the Free Software Foundation; either version 2 of the License, or 
                    892: (at your option) any later version.
                    893: 
                    894: This program is distributed in the hope that it will be useful,
                    895: but WITHOUT ANY WARRANTY; without even the implied warranty of
                    896: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    897: GNU General Public License for more details.
                    898: 
                    899: You should have received a copy of the GNU General Public License
                    900: along with this program; if not, write to the Free Software
                    901: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
                    902: @end smallexample
                    903: 
                    904: Also add information on how to contact you by electronic and paper mail.
                    905: 
                    906: If the program is interactive, make it output a short notice like this
                    907: when it starts in an interactive mode:
                    908: 
                    909: @smallexample
                    910: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
                    911: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
                    912: type `show w'.  
                    913: This is free software, and you are welcome to redistribute it 
                    914: under certain conditions; type `show c' for details.
                    915: @end smallexample
                    916: 
                    917: The hypothetical commands @samp{show w} and @samp{show c} should show
                    918: the appropriate parts of the General Public License.  Of course, the
                    919: commands you use may be called something other than @samp{show w} and
                    920: @samp{show c}; they could even be mouse-clicks or menu items---whatever
                    921: suits your program.
                    922: 
                    923: You should also get your employer (if you work as a programmer) or your
                    924: school, if any, to sign a ``copyright disclaimer'' for the program, if
                    925: necessary.  Here is a sample; alter the names:
                    926: 
                    927: @smallexample
                    928: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
                    929: `Gnomovision' (which makes passes at compilers) written by James Hacker.
                    930: 
                    931: @var{signature of Ty Coon}, 1 April 1989
                    932: Ty Coon, President of Vice
                    933: @end smallexample
                    934: 
                    935: This General Public License does not permit incorporating your program into
                    936: proprietary programs.  If your program is a subroutine library, you may
                    937: consider it more useful to permit linking proprietary applications with the
                    938: library.  If this is what you want to do, use the GNU Library General
                    939: Public License instead of this License.
                    940: 
                    941: @iftex
                    942: @unnumbered Preface
                    943: @cindex Preface
1.21      crook     944: This manual documents Gforth. Some introductory material is provided for
                    945: readers who are unfamiliar with Forth or who are migrating to Gforth
                    946: from other Forth compilers. However, this manual is primarily a
                    947: reference manual.
1.1       anton     948: @end iftex
                    949: 
1.28      crook     950: @comment TODO much more blurb here.
1.26      crook     951: 
                    952: @c ******************************************************************
1.29      crook     953: @node Goals, Gforth Environment, License, Top
1.26      crook     954: @comment node-name,     next,           previous, up
                    955: @chapter Goals of Gforth
                    956: @cindex goals of the Gforth project
                    957: The goal of the Gforth Project is to develop a standard model for
                    958: ANS Forth. This can be split into several subgoals:
                    959: 
                    960: @itemize @bullet
                    961: @item
                    962: Gforth should conform to the ANS Forth Standard.
                    963: @item
                    964: It should be a model, i.e. it should define all the
                    965: implementation-dependent things.
                    966: @item
                    967: It should become standard, i.e. widely accepted and used. This goal
                    968: is the most difficult one.
                    969: @end itemize
                    970: 
                    971: To achieve these goals Gforth should be
                    972: @itemize @bullet
                    973: @item
                    974: Similar to previous models (fig-Forth, F83)
                    975: @item
                    976: Powerful. It should provide for all the things that are considered
                    977: necessary today and even some that are not yet considered necessary.
                    978: @item
                    979: Efficient. It should not get the reputation of being exceptionally
                    980: slow.
                    981: @item
                    982: Free.
                    983: @item
                    984: Available on many machines/easy to port.
                    985: @end itemize
                    986: 
                    987: Have we achieved these goals? Gforth conforms to the ANS Forth
                    988: standard. It may be considered a model, but we have not yet documented
                    989: which parts of the model are stable and which parts we are likely to
                    990: change. It certainly has not yet become a de facto standard, but it
                    991: appears to be quite popular. It has some similarities to and some
                    992: differences from previous models. It has some powerful features, but not
                    993: yet everything that we envisioned. We certainly have achieved our
1.65      anton     994: execution speed goals (@pxref{Performance})@footnote{However, in 1998
                    995: the bar was raised when the major commercial Forth vendors switched to
                    996: native code compilers.}.  It is free and available on many machines.
1.29      crook     997: 
1.26      crook     998: @c ******************************************************************
1.48      anton     999: @node Gforth Environment, Tutorial, Goals, Top
1.29      crook    1000: @chapter Gforth Environment
                   1001: @cindex Gforth environment
1.21      crook    1002: 
1.45      crook    1003: Note: ultimately, the Gforth man page will be auto-generated from the
1.29      crook    1004: material in this chapter.
1.21      crook    1005: 
                   1006: @menu
1.29      crook    1007: * Invoking Gforth::             Getting in
                   1008: * Leaving Gforth::              Getting out
                   1009: * Command-line editing::        
1.48      anton    1010: * Environment variables::       that affect how Gforth starts up
1.29      crook    1011: * Gforth Files::                What gets installed and where
1.48      anton    1012: * Startup speed::               When 35ms is not fast enough ...
1.21      crook    1013: @end menu
                   1014: 
1.49      anton    1015: For related information about the creation of images see @ref{Image Files}.
1.29      crook    1016: 
1.21      crook    1017: @comment ----------------------------------------------
1.48      anton    1018: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29      crook    1019: @section Invoking Gforth
                   1020: @cindex invoking Gforth
                   1021: @cindex running Gforth
                   1022: @cindex command-line options
                   1023: @cindex options on the command line
                   1024: @cindex flags on the command line
1.21      crook    1025: 
1.30      anton    1026: Gforth is made up of two parts; an executable ``engine'' (named
                   1027: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
                   1028: will usually just say @code{gforth} -- this automatically loads the
                   1029: default image file @file{gforth.fi}. In many other cases the default
                   1030: Gforth image will be invoked like this:
1.21      crook    1031: @example
1.30      anton    1032: gforth [file | -e forth-code] ...
1.21      crook    1033: @end example
1.29      crook    1034: @noindent
                   1035: This interprets the contents of the files and the Forth code in the order they
                   1036: are given.
1.21      crook    1037: 
1.30      anton    1038: In addition to the @file{gforth} engine, there is also an engine called
                   1039: @file{gforth-fast}, which is faster, but gives less informative error
                   1040: messages (@pxref{Error messages}).
                   1041: 
1.29      crook    1042: In general, the command line looks like this:
1.21      crook    1043: 
                   1044: @example
1.30      anton    1045: gforth[-fast] [engine options] [image options]
1.21      crook    1046: @end example
                   1047: 
1.30      anton    1048: The engine options must come before the rest of the command
1.29      crook    1049: line. They are:
1.26      crook    1050: 
1.29      crook    1051: @table @code
                   1052: @cindex -i, command-line option
                   1053: @cindex --image-file, command-line option
                   1054: @item --image-file @i{file}
                   1055: @itemx -i @i{file}
                   1056: Loads the Forth image @i{file} instead of the default
                   1057: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook    1058: 
1.39      anton    1059: @cindex --appl-image, command-line option
                   1060: @item --appl-image @i{file}
                   1061: Loads the image @i{file} and leaves all further command-line arguments
1.65      anton    1062: to the image (instead of processing them as engine options).  This is
                   1063: useful for building executable application images on Unix, built with
1.39      anton    1064: @code{gforthmi --application ...}.
                   1065: 
1.29      crook    1066: @cindex --path, command-line option
                   1067: @cindex -p, command-line option
                   1068: @item --path @i{path}
                   1069: @itemx -p @i{path}
                   1070: Uses @i{path} for searching the image file and Forth source code files
                   1071: instead of the default in the environment variable @code{GFORTHPATH} or
                   1072: the path specified at installation time (e.g.,
                   1073: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                   1074: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook    1075: 
1.29      crook    1076: @cindex --dictionary-size, command-line option
                   1077: @cindex -m, command-line option
                   1078: @cindex @i{size} parameters for command-line options
                   1079: @cindex size of the dictionary and the stacks
                   1080: @item --dictionary-size @i{size}
                   1081: @itemx -m @i{size}
                   1082: Allocate @i{size} space for the Forth dictionary space instead of
                   1083: using the default specified in the image (typically 256K). The
                   1084: @i{size} specification for this and subsequent options consists of
                   1085: an integer and a unit (e.g.,
                   1086: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                   1087: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                   1088: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                   1089: @code{e} is used.
1.21      crook    1090: 
1.29      crook    1091: @cindex --data-stack-size, command-line option
                   1092: @cindex -d, command-line option
                   1093: @item --data-stack-size @i{size}
                   1094: @itemx -d @i{size}
                   1095: Allocate @i{size} space for the data stack instead of using the
                   1096: default specified in the image (typically 16K).
1.21      crook    1097: 
1.29      crook    1098: @cindex --return-stack-size, command-line option
                   1099: @cindex -r, command-line option
                   1100: @item --return-stack-size @i{size}
                   1101: @itemx -r @i{size}
                   1102: Allocate @i{size} space for the return stack instead of using the
                   1103: default specified in the image (typically 15K).
1.21      crook    1104: 
1.29      crook    1105: @cindex --fp-stack-size, command-line option
                   1106: @cindex -f, command-line option
                   1107: @item --fp-stack-size @i{size}
                   1108: @itemx -f @i{size}
                   1109: Allocate @i{size} space for the floating point stack instead of
                   1110: using the default specified in the image (typically 15.5K). In this case
                   1111: the unit specifier @code{e} refers to floating point numbers.
1.21      crook    1112: 
1.48      anton    1113: @cindex --locals-stack-size, command-line option
                   1114: @cindex -l, command-line option
                   1115: @item --locals-stack-size @i{size}
                   1116: @itemx -l @i{size}
                   1117: Allocate @i{size} space for the locals stack instead of using the
                   1118: default specified in the image (typically 14.5K).
                   1119: 
                   1120: @cindex -h, command-line option
                   1121: @cindex --help, command-line option
                   1122: @item --help
                   1123: @itemx -h
                   1124: Print a message about the command-line options
                   1125: 
                   1126: @cindex -v, command-line option
                   1127: @cindex --version, command-line option
                   1128: @item --version
                   1129: @itemx -v
                   1130: Print version and exit
                   1131: 
                   1132: @cindex --debug, command-line option
                   1133: @item --debug
                   1134: Print some information useful for debugging on startup.
                   1135: 
                   1136: @cindex --offset-image, command-line option
                   1137: @item --offset-image
                   1138: Start the dictionary at a slightly different position than would be used
                   1139: otherwise (useful for creating data-relocatable images,
                   1140: @pxref{Data-Relocatable Image Files}).
                   1141: 
                   1142: @cindex --no-offset-im, command-line option
                   1143: @item --no-offset-im
                   1144: Start the dictionary at the normal position.
                   1145: 
                   1146: @cindex --clear-dictionary, command-line option
                   1147: @item --clear-dictionary
                   1148: Initialize all bytes in the dictionary to 0 before loading the image
                   1149: (@pxref{Data-Relocatable Image Files}).
                   1150: 
                   1151: @cindex --die-on-signal, command-line-option
                   1152: @item --die-on-signal
                   1153: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                   1154: or the segmentation violation SIGSEGV) by translating it into a Forth
                   1155: @code{THROW}. With this option, Gforth exits if it receives such a
                   1156: signal. This option is useful when the engine and/or the image might be
                   1157: severely broken (such that it causes another signal before recovering
                   1158: from the first); this option avoids endless loops in such cases.
                   1159: @end table
                   1160: 
                   1161: @cindex loading files at startup
                   1162: @cindex executing code on startup
                   1163: @cindex batch processing with Gforth
                   1164: As explained above, the image-specific command-line arguments for the
                   1165: default image @file{gforth.fi} consist of a sequence of filenames and
                   1166: @code{-e @var{forth-code}} options that are interpreted in the sequence
                   1167: in which they are given. The @code{-e @var{forth-code}} or
                   1168: @code{--evaluate @var{forth-code}} option evaluates the Forth
                   1169: code. This option takes only one argument; if you want to evaluate more
                   1170: Forth words, you have to quote them or use @code{-e} several times. To exit
                   1171: after processing the command line (instead of entering interactive mode)
                   1172: append @code{-e bye} to the command line.
                   1173: 
                   1174: @cindex versions, invoking other versions of Gforth
                   1175: If you have several versions of Gforth installed, @code{gforth} will
                   1176: invoke the version that was installed last. @code{gforth-@i{version}}
                   1177: invokes a specific version. If your environment contains the variable
                   1178: @code{GFORTHPATH}, you may want to override it by using the
                   1179: @code{--path} option.
                   1180: 
                   1181: Not yet implemented:
                   1182: On startup the system first executes the system initialization file
                   1183: (unless the option @code{--no-init-file} is given; note that the system
                   1184: resulting from using this option may not be ANS Forth conformant). Then
                   1185: the user initialization file @file{.gforth.fs} is executed, unless the
1.62      crook    1186: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48      anton    1187: then in @file{~}, then in the normal path (see above).
                   1188: 
                   1189: 
                   1190: 
                   1191: @comment ----------------------------------------------
                   1192: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                   1193: @section Leaving Gforth
                   1194: @cindex Gforth - leaving
                   1195: @cindex leaving Gforth
                   1196: 
                   1197: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                   1198: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                   1199: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49      anton    1200: data are discarded.  For ways of saving the state of the system before
                   1201: leaving Gforth see @ref{Image Files}.
1.48      anton    1202: 
                   1203: doc-bye
                   1204: 
                   1205: 
                   1206: @comment ----------------------------------------------
1.65      anton    1207: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48      anton    1208: @section Command-line editing
                   1209: @cindex command-line editing
                   1210: 
                   1211: Gforth maintains a history file that records every line that you type to
                   1212: the text interpreter. This file is preserved between sessions, and is
                   1213: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
                   1214: repeatedly you can recall successively older commands from this (or
                   1215: previous) session(s). The full list of command-line editing facilities is:
                   1216: 
                   1217: @itemize @bullet
                   1218: @item
                   1219: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
                   1220: commands from the history buffer.
                   1221: @item
                   1222: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
                   1223: from the history buffer.
                   1224: @item
                   1225: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
                   1226: @item
                   1227: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
                   1228: @item
                   1229: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
                   1230: closing up the line.
                   1231: @item
                   1232: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
                   1233: @item
                   1234: @kbd{Ctrl-a} to move the cursor to the start of the line.
                   1235: @item
                   1236: @kbd{Ctrl-e} to move the cursor to the end of the line.
                   1237: @item
                   1238: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
                   1239: line.
                   1240: @item
                   1241: @key{TAB} to step through all possible full-word completions of the word
                   1242: currently being typed.
                   1243: @item
1.65      anton    1244: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
                   1245: using @code{bye}). 
                   1246: @item
                   1247: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
                   1248: character under the cursor.
1.48      anton    1249: @end itemize
                   1250: 
                   1251: When editing, displayable characters are inserted to the left of the
                   1252: cursor position; the line is always in ``insert'' (as opposed to
                   1253: ``overstrike'') mode.
                   1254: 
                   1255: @cindex history file
                   1256: @cindex @file{.gforth-history}
                   1257: On Unix systems, the history file is @file{~/.gforth-history} by
                   1258: default@footnote{i.e. it is stored in the user's home directory.}. You
                   1259: can find out the name and location of your history file using:
                   1260: 
                   1261: @example 
                   1262: history-file type \ Unix-class systems
                   1263: 
                   1264: history-file type \ Other systems
                   1265: history-dir  type
                   1266: @end example
                   1267: 
                   1268: If you enter long definitions by hand, you can use a text editor to
                   1269: paste them out of the history file into a Forth source file for reuse at
                   1270: a later time.
                   1271: 
                   1272: Gforth never trims the size of the history file, so you should do this
                   1273: periodically, if necessary.
                   1274: 
                   1275: @comment this is all defined in history.fs
                   1276: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
                   1277: @comment chosen?
                   1278: 
                   1279: 
                   1280: @comment ----------------------------------------------
1.65      anton    1281: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48      anton    1282: @section Environment variables
                   1283: @cindex environment variables
                   1284: 
                   1285: Gforth uses these environment variables:
                   1286: 
                   1287: @itemize @bullet
                   1288: @item
                   1289: @cindex @code{GFORTHHIST} -- environment variable
                   1290: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
                   1291: open/create the history file, @file{.gforth-history}. Default:
                   1292: @code{$HOME}.
                   1293: 
                   1294: @item
                   1295: @cindex @code{GFORTHPATH} -- environment variable
                   1296: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
                   1297: for Forth source-code files.
                   1298: 
                   1299: @item
                   1300: @cindex @code{GFORTH} -- environment variable
1.49      anton    1301: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1302: 
                   1303: @item
                   1304: @cindex @code{GFORTHD} -- environment variable
1.62      crook    1305: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1306: 
                   1307: @item
                   1308: @cindex @code{TMP}, @code{TEMP} - environment variable
                   1309: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
                   1310: location for the history file.
                   1311: @end itemize
                   1312: 
                   1313: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1314: @comment mentioning these.
                   1315: 
                   1316: All the Gforth environment variables default to sensible values if they
                   1317: are not set.
                   1318: 
                   1319: 
                   1320: @comment ----------------------------------------------
                   1321: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
                   1322: @section Gforth files
                   1323: @cindex Gforth files
                   1324: 
                   1325: When you install Gforth on a Unix system, it installs files in these
                   1326: locations by default:
                   1327: 
                   1328: @itemize @bullet
                   1329: @item
                   1330: @file{/usr/local/bin/gforth}
                   1331: @item
                   1332: @file{/usr/local/bin/gforthmi}
                   1333: @item
                   1334: @file{/usr/local/man/man1/gforth.1} - man page.
                   1335: @item
                   1336: @file{/usr/local/info} - the Info version of this manual.
                   1337: @item
                   1338: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
                   1339: @item
                   1340: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
                   1341: @item
                   1342: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
                   1343: @item
                   1344: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
                   1345: @end itemize
                   1346: 
                   1347: You can select different places for installation by using
                   1348: @code{configure} options (listed with @code{configure --help}).
                   1349: 
                   1350: @comment ----------------------------------------------
                   1351: @node Startup speed,  , Gforth Files, Gforth Environment
                   1352: @section Startup speed
                   1353: @cindex Startup speed
                   1354: @cindex speed, startup
                   1355: 
                   1356: If Gforth is used for CGI scripts or in shell scripts, its startup
                   1357: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
                   1358: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
                   1359: system time.
                   1360: 
                   1361: If startup speed is a problem, you may consider the following ways to
                   1362: improve it; or you may consider ways to reduce the number of startups
1.62      crook    1363: (for example, by using Fast-CGI).
1.48      anton    1364: 
                   1365: The first step to improve startup speed is to statically link Gforth, by
                   1366: building it with @code{XLDFLAGS=-static}.  This requires more memory for
                   1367: the code and will therefore slow down the first invocation, but
                   1368: subsequent invocations avoid the dynamic linking overhead.  Another
                   1369: disadvantage is that Gforth won't profit from library upgrades.  As a
                   1370: result, @code{gforth-static -e bye} takes about 17.1ms user and
                   1371: 8.2ms system time.
                   1372: 
                   1373: The next step to improve startup speed is to use a non-relocatable image
1.65      anton    1374: (@pxref{Non-Relocatable Image Files}).  You can create this image with
1.48      anton    1375: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
                   1376: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
                   1377: and a part of the copy-on-write overhead.  The disadvantage is that the
1.62      crook    1378: non-relocatable image does not work if the OS gives Gforth a different
1.48      anton    1379: address for the dictionary, for whatever reason; so you better provide a
                   1380: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
                   1381: bye} takes about 15.3ms user and 7.5ms system time.
                   1382: 
                   1383: The final step is to disable dictionary hashing in Gforth.  Gforth
                   1384: builds the hash table on startup, which takes much of the startup
                   1385: overhead. You can do this by commenting out the @code{include hash.fs}
                   1386: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
                   1387: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
                   1388: The disadvantages are that functionality like @code{table} and
                   1389: @code{ekey} is missing and that text interpretation (e.g., compiling)
                   1390: now takes much longer. So, you should only use this method if there is
                   1391: no significant text interpretation to perform (the script should be
1.62      crook    1392: compiled into the image, amongst other things).  @code{gforth-static -i
1.48      anton    1393: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
                   1394: 
                   1395: @c ******************************************************************
                   1396: @node Tutorial, Introduction, Gforth Environment, Top
                   1397: @chapter Forth Tutorial
                   1398: @cindex Tutorial
                   1399: @cindex Forth Tutorial
                   1400: 
1.62      crook    1401: This tutorial can be used with any ANS-compliant Forth; any
                   1402: Gforth-specific features are marked as such and you can skip them if you
                   1403: work with another Forth.  This tutorial does not explain all features of
                   1404: Forth, just enough to get you started and give you some ideas about the
                   1405: facilities available in Forth.  Read the rest of the manual and the
                   1406: standard when you are through this.
1.48      anton    1407: 
                   1408: The intended way to use this tutorial is that you work through it while
                   1409: sitting in front of the console, take a look at the examples and predict
                   1410: what they will do, then try them out; if the outcome is not as expected,
                   1411: find out why (e.g., by trying out variations of the example), so you
                   1412: understand what's going on.  There are also some assignments that you
                   1413: should solve.
                   1414: 
                   1415: This tutorial assumes that you have programmed before and know what,
                   1416: e.g., a loop is.
                   1417: 
                   1418: @c !! explain compat library
                   1419: 
                   1420: @menu
                   1421: * Starting Gforth Tutorial::    
                   1422: * Syntax Tutorial::             
                   1423: * Crash Course Tutorial::       
                   1424: * Stack Tutorial::              
                   1425: * Arithmetics Tutorial::        
                   1426: * Stack Manipulation Tutorial::  
                   1427: * Using files for Forth code Tutorial::  
                   1428: * Comments Tutorial::           
                   1429: * Colon Definitions Tutorial::  
                   1430: * Decompilation Tutorial::      
                   1431: * Stack-Effect Comments Tutorial::  
                   1432: * Types Tutorial::              
                   1433: * Factoring Tutorial::          
                   1434: * Designing the stack effect Tutorial::  
                   1435: * Local Variables Tutorial::    
                   1436: * Conditional execution Tutorial::  
                   1437: * Flags and Comparisons Tutorial::  
                   1438: * General Loops Tutorial::      
                   1439: * Counted loops Tutorial::      
                   1440: * Recursion Tutorial::          
                   1441: * Leaving definitions or loops Tutorial::  
                   1442: * Return Stack Tutorial::       
                   1443: * Memory Tutorial::             
                   1444: * Characters and Strings Tutorial::  
                   1445: * Alignment Tutorial::          
                   1446: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1447: * Execution Tokens Tutorial::   
                   1448: * Exceptions Tutorial::         
                   1449: * Defining Words Tutorial::     
                   1450: * Arrays and Records Tutorial::  
                   1451: * POSTPONE Tutorial::           
                   1452: * Literal Tutorial::            
                   1453: * Advanced macros Tutorial::    
                   1454: * Compilation Tokens Tutorial::  
                   1455: * Wordlists and Search Order Tutorial::  
                   1456: @end menu
                   1457: 
                   1458: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1459: @section Starting Gforth
1.66    ! anton    1460: @cindex starting Gforth tutorial
1.48      anton    1461: You can start Gforth by typing its name:
                   1462: 
                   1463: @example
                   1464: gforth
                   1465: @end example
                   1466: 
                   1467: That puts you into interactive mode; you can leave Gforth by typing
                   1468: @code{bye}.  While in Gforth, you can edit the command line and access
                   1469: the command line history with cursor keys, similar to bash.
                   1470: 
                   1471: 
                   1472: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1473: @section Syntax
1.66    ! anton    1474: @cindex syntax tutorial
1.48      anton    1475: 
                   1476: A @dfn{word} is a sequence of arbitrary characters (expcept white
                   1477: space).  Words are separated by white space.  E.g., each of the
                   1478: following lines contains exactly one word:
                   1479: 
                   1480: @example
                   1481: word
                   1482: !@@#$%^&*()
                   1483: 1234567890
                   1484: 5!a
                   1485: @end example
                   1486: 
                   1487: A frequent beginner's error is to leave away necessary white space,
                   1488: resulting in an error like @samp{Undefined word}; so if you see such an
                   1489: error, check if you have put spaces wherever necessary.
                   1490: 
                   1491: @example
                   1492: ." hello, world" \ correct
                   1493: ."hello, world"  \ gives an "Undefined word" error
                   1494: @end example
                   1495: 
1.65      anton    1496: Gforth and most other Forth systems ignore differences in case (they are
1.48      anton    1497: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1498: your system is case-sensitive, you may have to type all the examples
                   1499: given here in upper case.
                   1500: 
                   1501: 
                   1502: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1503: @section Crash Course
                   1504: 
                   1505: Type
                   1506: 
                   1507: @example
                   1508: 0 0 !
                   1509: here execute
                   1510: ' catch >body 20 erase abort
                   1511: ' (quit) >body 20 erase
                   1512: @end example
                   1513: 
                   1514: The last two examples are guaranteed to destroy parts of Gforth (and
                   1515: most other systems), so you better leave Gforth afterwards (if it has
                   1516: not finished by itself).  On some systems you may have to kill gforth
                   1517: from outside (e.g., in Unix with @code{kill}).
                   1518: 
                   1519: Now that you know how to produce crashes (and that there's not much to
                   1520: them), let's learn how to produce meaningful programs.
                   1521: 
                   1522: 
                   1523: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1524: @section Stack
1.66    ! anton    1525: @cindex stack tutorial
1.48      anton    1526: 
                   1527: The most obvious feature of Forth is the stack.  When you type in a
                   1528: number, it is pushed on the stack.  You can display the content of the
                   1529: stack with @code{.s}.
                   1530: 
                   1531: @example
                   1532: 1 2 .s
                   1533: 3 .s
                   1534: @end example
                   1535: 
                   1536: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1537: appear in @code{.s} output as they appeared in the input.
                   1538: 
                   1539: You can print the top of stack element with @code{.}.
                   1540: 
                   1541: @example
                   1542: 1 2 3 . . .
                   1543: @end example
                   1544: 
                   1545: In general, words consume their stack arguments (@code{.s} is an
                   1546: exception).
                   1547: 
                   1548: @assignment
                   1549: What does the stack contain after @code{5 6 7 .}?
                   1550: @endassignment
                   1551: 
                   1552: 
                   1553: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1554: @section Arithmetics
1.66    ! anton    1555: @cindex arithmetics tutorial
1.48      anton    1556: 
                   1557: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1558: operate on the top two stack items:
                   1559: 
                   1560: @example
                   1561: 2 2 + .
                   1562: 2 1 - .
                   1563: 7 3 mod .
                   1564: @end example
                   1565: 
                   1566: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1567: as in the corresponding infix expression (this is generally the case in
                   1568: Forth).
                   1569: 
                   1570: Parentheses are superfluous (and not available), because the order of
                   1571: the words unambiguously determines the order of evaluation and the
                   1572: operands:
                   1573: 
                   1574: @example
                   1575: 3 4 + 5 * .
                   1576: 3 4 5 * + .
                   1577: @end example
                   1578: 
                   1579: @assignment
                   1580: What are the infix expressions corresponding to the Forth code above?
                   1581: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1582: known as Postfix or RPN (Reverse Polish Notation).}.
                   1583: @endassignment
                   1584: 
                   1585: To change the sign, use @code{negate}:
                   1586: 
                   1587: @example
                   1588: 2 negate .
                   1589: @end example
                   1590: 
                   1591: @assignment
                   1592: Convert -(-3)*4-5 to Forth.
                   1593: @endassignment
                   1594: 
                   1595: @code{/mod} performs both @code{/} and @code{mod}.
                   1596: 
                   1597: @example
                   1598: 7 3 /mod . .
                   1599: @end example
                   1600: 
1.66    ! anton    1601: Reference: @ref{Arithmetic}.
        !          1602: 
        !          1603: 
1.48      anton    1604: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1605: @section Stack Manipulation
1.66    ! anton    1606: @cindex stack manipulation tutorial
1.48      anton    1607: 
                   1608: Stack manipulation words rearrange the data on the stack.
                   1609: 
                   1610: @example
                   1611: 1 .s drop .s
                   1612: 1 .s dup .s drop drop .s
                   1613: 1 2 .s over .s drop drop drop
                   1614: 1 2 .s swap .s drop drop
                   1615: 1 2 3 .s rot .s drop drop drop
                   1616: @end example
                   1617: 
                   1618: These are the most important stack manipulation words.  There are also
                   1619: variants that manipulate twice as many stack items:
                   1620: 
                   1621: @example
                   1622: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1623: @end example
                   1624: 
                   1625: Two more stack manipulation words are:
                   1626: 
                   1627: @example
                   1628: 1 2 .s nip .s drop
                   1629: 1 2 .s tuck .s 2drop drop
                   1630: @end example
                   1631: 
                   1632: @assignment
                   1633: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1634: manipulation words.
                   1635: 
                   1636: @example
                   1637: Given:          How do you get:
                   1638: 1 2 3           3 2 1           
                   1639: 1 2 3           1 2 3 2                 
                   1640: 1 2 3           1 2 3 3                 
                   1641: 1 2 3           1 3 3           
                   1642: 1 2 3           2 1 3           
                   1643: 1 2 3 4         4 3 2 1         
                   1644: 1 2 3           1 2 3 1 2 3             
                   1645: 1 2 3 4         1 2 3 4 1 2             
                   1646: 1 2 3
                   1647: 1 2 3           1 2 3 4                 
                   1648: 1 2 3           1 3             
                   1649: @end example
                   1650: @endassignment
                   1651: 
                   1652: @example
                   1653: 5 dup * .
                   1654: @end example
                   1655: 
                   1656: @assignment
                   1657: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1658: Write a piece of Forth code that expects two numbers on the stack
                   1659: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1660: @code{(a-b)(a+1)}.
                   1661: @endassignment
                   1662: 
1.66    ! anton    1663: Reference: @ref{Stack Manipulation}.
        !          1664: 
        !          1665: 
1.48      anton    1666: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1667: @section Using files for Forth code
1.66    ! anton    1668: @cindex loading Forth code, tutorial
        !          1669: @cindex files containing Forth code, tutorial
1.48      anton    1670: 
                   1671: While working at the Forth command line is convenient for one-line
                   1672: examples and short one-off code, you probably want to store your source
                   1673: code in files for convenient editing and persistence.  You can use your
                   1674: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
                   1675: Gforth}) to create @var{file} and use
                   1676: 
                   1677: @example
                   1678: s" @var{file}" included
                   1679: @end example
                   1680: 
                   1681: to load it into your Forth system.  The file name extension I use for
                   1682: Forth files is @samp{.fs}.
                   1683: 
                   1684: You can easily start Gforth with some files loaded like this:
                   1685: 
                   1686: @example
                   1687: gforth @var{file1} @var{file2}
                   1688: @end example
                   1689: 
                   1690: If an error occurs during loading these files, Gforth terminates,
                   1691: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1692: a Gforth command line.  Starting the Forth system every time gives you a
                   1693: clean start every time, without interference from the results of earlier
                   1694: tries.
                   1695: 
                   1696: I often put all the tests in a file, then load the code and run the
                   1697: tests with
                   1698: 
                   1699: @example
                   1700: gforth @var{code} @var{tests} -e bye
                   1701: @end example
                   1702: 
                   1703: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1704: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1705: restart this command without ado.
                   1706: 
                   1707: The advantage of this approach is that the tests can be repeated easily
                   1708: every time the program ist changed, making it easy to catch bugs
                   1709: introduced by the change.
                   1710: 
1.66    ! anton    1711: Reference: @ref{Forth source files}.
        !          1712: 
1.48      anton    1713: 
                   1714: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1715: @section Comments
1.66    ! anton    1716: @cindex comments tutorial
1.48      anton    1717: 
                   1718: @example
                   1719: \ That's a comment; it ends at the end of the line
                   1720: ( Another comment; it ends here: )  .s
                   1721: @end example
                   1722: 
                   1723: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1724: separated with white space from the following text.
                   1725: 
                   1726: @example
                   1727: \This gives an "Undefined word" error
                   1728: @end example
                   1729: 
                   1730: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1731: nest @code{(}-comments; and you cannot comment out text containing a
                   1732: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1733: avoid @code{)} in word names.}.
                   1734: 
                   1735: I use @code{\}-comments for descriptive text and for commenting out code
                   1736: of one or more line; I use @code{(}-comments for describing the stack
                   1737: effect, the stack contents, or for commenting out sub-line pieces of
                   1738: code.
                   1739: 
                   1740: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1741: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1742: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1743: with @kbd{M-q}.
                   1744: 
1.66    ! anton    1745: Reference: @ref{Comments}.
        !          1746: 
1.48      anton    1747: 
                   1748: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1749: @section Colon Definitions
1.66    ! anton    1750: @cindex colon definitions, tutorial
        !          1751: @cindex definitions, tutorial
        !          1752: @cindex procedures, tutorial
        !          1753: @cindex functions, tutorial
1.48      anton    1754: 
                   1755: are similar to procedures and functions in other programming languages.
                   1756: 
                   1757: @example
                   1758: : squared ( n -- n^2 )
                   1759:    dup * ;
                   1760: 5 squared .
                   1761: 7 squared .
                   1762: @end example
                   1763: 
                   1764: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1765: following comment describes its stack effect.  The words @code{dup *}
                   1766: are not executed, but compiled into the definition.  @code{;} ends the
                   1767: colon definition.
                   1768: 
                   1769: The newly-defined word can be used like any other word, including using
                   1770: it in other definitions:
                   1771: 
                   1772: @example
                   1773: : cubed ( n -- n^3 )
                   1774:    dup squared * ;
                   1775: -5 cubed .
                   1776: : fourth-power ( n -- n^4 )
                   1777:    squared squared ;
                   1778: 3 fourth-power .
                   1779: @end example
                   1780: 
                   1781: @assignment
                   1782: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1783: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1784: test your tests on the originals first).  Don't let the
                   1785: @samp{redefined}-Messages spook you, they are just warnings.
                   1786: @endassignment
                   1787: 
1.66    ! anton    1788: Reference: @ref{Colon Definitions}.
        !          1789: 
1.48      anton    1790: 
                   1791: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1792: @section Decompilation
1.66    ! anton    1793: @cindex decompilation tutorial
        !          1794: @cindex see tutorial
1.48      anton    1795: 
                   1796: You can decompile colon definitions with @code{see}:
                   1797: 
                   1798: @example
                   1799: see squared
                   1800: see cubed
                   1801: @end example
                   1802: 
                   1803: In Gforth @code{see} shows you a reconstruction of the source code from
                   1804: the executable code.  Informations that were present in the source, but
                   1805: not in the executable code, are lost (e.g., comments).
                   1806: 
1.65      anton    1807: You can also decompile the predefined words:
                   1808: 
                   1809: @example
                   1810: see .
                   1811: see +
                   1812: @end example
                   1813: 
                   1814: 
1.48      anton    1815: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1816: @section Stack-Effect Comments
1.66    ! anton    1817: @cindex stack-effect comments, tutorial
        !          1818: @cindex --, tutorial
1.48      anton    1819: By convention the comment after the name of a definition describes the
                   1820: stack effect: The part in from of the @samp{--} describes the state of
                   1821: the stack before the execution of the definition, i.e., the parameters
                   1822: that are passed into the colon definition; the part behind the @samp{--}
                   1823: is the state of the stack after the execution of the definition, i.e.,
                   1824: the results of the definition.  The stack comment only shows the top
                   1825: stack items that the definition accesses and/or changes.
                   1826: 
                   1827: You should put a correct stack effect on every definition, even if it is
                   1828: just @code{( -- )}.  You should also add some descriptive comment to
                   1829: more complicated words (I usually do this in the lines following
                   1830: @code{:}).  If you don't do this, your code becomes unreadable (because
                   1831: you have to work through every definition before you can undertsand
                   1832: any).
                   1833: 
                   1834: @assignment
                   1835: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1836: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1837: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
1.65      anton    1838: are done, you can compare your stack effects to those in this manual
1.48      anton    1839: (@pxref{Word Index}).
                   1840: @endassignment
                   1841: 
                   1842: Sometimes programmers put comments at various places in colon
                   1843: definitions that describe the contents of the stack at that place (stack
                   1844: comments); i.e., they are like the first part of a stack-effect
                   1845: comment. E.g.,
                   1846: 
                   1847: @example
                   1848: : cubed ( n -- n^3 )
                   1849:    dup squared  ( n n^2 ) * ;
                   1850: @end example
                   1851: 
                   1852: In this case the stack comment is pretty superfluous, because the word
                   1853: is simple enough.  If you think it would be a good idea to add such a
                   1854: comment to increase readability, you should also consider factoring the
                   1855: word into several simpler words (@pxref{Factoring Tutorial,,
1.60      anton    1856: Factoring}), which typically eliminates the need for the stack comment;
1.48      anton    1857: however, if you decide not to refactor it, then having such a comment is
                   1858: better than not having it.
                   1859: 
                   1860: The names of the stack items in stack-effect and stack comments in the
                   1861: standard, in this manual, and in many programs specify the type through
                   1862: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1863: frequent prefixes are:
                   1864: 
                   1865: @table @code
                   1866: @item n
                   1867: signed integer
                   1868: @item u
                   1869: unsigned integer
                   1870: @item c
                   1871: character
                   1872: @item f
                   1873: Boolean flags, i.e. @code{false} or @code{true}.
                   1874: @item a-addr,a-
                   1875: Cell-aligned address
                   1876: @item c-addr,c-
                   1877: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1878: @item xt
                   1879: Execution token, same size as Cell
                   1880: @item w,x
                   1881: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1882: 16 bits (depending on your platform and Forth system). A cell is more
                   1883: commonly known as machine word, but the term @emph{word} already means
                   1884: something different in Forth.
                   1885: @item d
                   1886: signed double-cell integer
                   1887: @item ud
                   1888: unsigned double-cell integer
                   1889: @item r
                   1890: Float (on the FP stack)
                   1891: @end table
                   1892: 
                   1893: You can find a more complete list in @ref{Notation}.
                   1894: 
                   1895: @assignment
                   1896: Write stack-effect comments for all definitions you have written up to
                   1897: now.
                   1898: @endassignment
                   1899: 
                   1900: 
                   1901: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1902: @section Types
1.66    ! anton    1903: @cindex types tutorial
1.48      anton    1904: 
                   1905: In Forth the names of the operations are not overloaded; so similar
                   1906: operations on different types need different names; e.g., @code{+} adds
                   1907: integers, and you have to use @code{f+} to add floating-point numbers.
                   1908: The following prefixes are often used for related operations on
                   1909: different types:
                   1910: 
                   1911: @table @code
                   1912: @item (none)
                   1913: signed integer
                   1914: @item u
                   1915: unsigned integer
                   1916: @item c
                   1917: character
                   1918: @item d
                   1919: signed double-cell integer
                   1920: @item ud, du
                   1921: unsigned double-cell integer
                   1922: @item 2
                   1923: two cells (not-necessarily double-cell numbers)
                   1924: @item m, um
                   1925: mixed single-cell and double-cell operations
                   1926: @item f
                   1927: floating-point (note that in stack comments @samp{f} represents flags,
1.66    ! anton    1928: and @samp{r} represents FP numbers).
1.48      anton    1929: @end table
                   1930: 
                   1931: If there are no differences between the signed and the unsigned variant
                   1932: (e.g., for @code{+}), there is only the prefix-less variant.
                   1933: 
                   1934: Forth does not perform type checking, neither at compile time, nor at
                   1935: run time.  If you use the wrong oeration, the data are interpreted
                   1936: incorrectly:
                   1937: 
                   1938: @example
                   1939: -1 u.
                   1940: @end example
                   1941: 
                   1942: If you have only experience with type-checked languages until now, and
                   1943: have heard how important type-checking is, don't panic!  In my
                   1944: experience (and that of other Forthers), type errors in Forth code are
                   1945: usually easy to find (once you get used to it), the increased vigilance
                   1946: of the programmer tends to catch some harder errors in addition to most
                   1947: type errors, and you never have to work around the type system, so in
                   1948: most situations the lack of type-checking seems to be a win (projects to
                   1949: add type checking to Forth have not caught on).
                   1950: 
                   1951: 
                   1952: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   1953: @section Factoring
1.66    ! anton    1954: @cindex factoring tutorial
1.48      anton    1955: 
                   1956: If you try to write longer definitions, you will soon find it hard to
                   1957: keep track of the stack contents.  Therefore, good Forth programmers
                   1958: tend to write only short definitions (e.g., three lines).  The art of
                   1959: finding meaningful short definitions is known as factoring (as in
                   1960: factoring polynomials).
                   1961: 
                   1962: Well-factored programs offer additional advantages: smaller, more
                   1963: general words, are easier to test and debug and can be reused more and
                   1964: better than larger, specialized words.
                   1965: 
                   1966: So, if you run into difficulties with stack management, when writing
                   1967: code, try to define meaningful factors for the word, and define the word
                   1968: in terms of those.  Even if a factor contains only two words, it is
                   1969: often helpful.
                   1970: 
1.65      anton    1971: Good factoring is not easy, and it takes some practice to get the knack
                   1972: for it; but even experienced Forth programmers often don't find the
                   1973: right solution right away, but only when rewriting the program.  So, if
                   1974: you don't come up with a good solution immediately, keep trying, don't
                   1975: despair.
1.48      anton    1976: 
                   1977: @c example !!
                   1978: 
                   1979: 
                   1980: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   1981: @section Designing the stack effect
1.66    ! anton    1982: @cindex Stack effect design, tutorial
        !          1983: @cindex design of stack effects, tutorial
1.48      anton    1984: 
                   1985: In other languages you can use an arbitrary order of parameters for a
1.65      anton    1986: function; and since there is only one result, you don't have to deal with
1.48      anton    1987: the order of results, either.
                   1988: 
                   1989: In Forth (and other stack-based languages, e.g., Postscript) the
                   1990: parameter and result order of a definition is important and should be
                   1991: designed well.  The general guideline is to design the stack effect such
                   1992: that the word is simple to use in most cases, even if that complicates
                   1993: the implementation of the word.  Some concrete rules are:
                   1994: 
                   1995: @itemize @bullet
                   1996: 
                   1997: @item
                   1998: Words consume all of their parameters (e.g., @code{.}).
                   1999: 
                   2000: @item
                   2001: If there is a convention on the order of parameters (e.g., from
                   2002: mathematics or another programming language), stick with it (e.g.,
                   2003: @code{-}).
                   2004: 
                   2005: @item
                   2006: If one parameter usually requires only a short computation (e.g., it is
                   2007: a constant), pass it on the top of the stack.  Conversely, parameters
                   2008: that usually require a long sequence of code to compute should be passed
                   2009: as the bottom (i.e., first) parameter.  This makes the code easier to
                   2010: read, because reader does not need to keep track of the bottom item
                   2011: through a long sequence of code (or, alternatively, through stack
1.49      anton    2012: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    2013: address on top of the stack because it is usually simpler to compute
                   2014: than the stored value (often the address is just a variable).
                   2015: 
                   2016: @item
                   2017: Similarly, results that are usually consumed quickly should be returned
                   2018: on the top of stack, whereas a result that is often used in long
                   2019: computations should be passed as bottom result.  E.g., the file words
                   2020: like @code{open-file} return the error code on the top of stack, because
                   2021: it is usually consumed quickly by @code{throw}; moreover, the error code
                   2022: has to be checked before doing anything with the other results.
                   2023: 
                   2024: @end itemize
                   2025: 
                   2026: These rules are just general guidelines, don't lose sight of the overall
                   2027: goal to make the words easy to use.  E.g., if the convention rule
                   2028: conflicts with the computation-length rule, you might decide in favour
                   2029: of the convention if the word will be used rarely, and in favour of the
                   2030: computation-length rule if the word will be used frequently (because
                   2031: with frequent use the cost of breaking the computation-length rule would
                   2032: be quite high, and frequent use makes it easier to remember an
                   2033: unconventional order).
                   2034: 
                   2035: @c example !! structure package
                   2036: 
1.65      anton    2037: 
1.48      anton    2038: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   2039: @section Local Variables
1.66    ! anton    2040: @cindex local variables, tutorial
1.48      anton    2041: 
                   2042: You can define local variables (@emph{locals}) in a colon definition:
                   2043: 
                   2044: @example
                   2045: : swap @{ a b -- b a @}
                   2046:   b a ;
                   2047: 1 2 swap .s 2drop
                   2048: @end example
                   2049: 
                   2050: (If your Forth system does not support this syntax, include
                   2051: @file{compat/anslocals.fs} first).
                   2052: 
                   2053: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   2054: takes two cells from the stack, puts the top of stack in @code{b} and
                   2055: the next stack element in @code{a}.  @code{--} starts a comment ending
                   2056: with @code{@}}.  After the locals definition, using the name of the
                   2057: local will push its value on the stack.  You can leave the comment
                   2058: part (@code{-- b a}) away:
                   2059: 
                   2060: @example
                   2061: : swap ( x1 x2 -- x2 x1 )
                   2062:   @{ a b @} b a ;
                   2063: @end example
                   2064: 
                   2065: In Gforth you can have several locals definitions, anywhere in a colon
                   2066: definition; in contrast, in a standard program you can have only one
                   2067: locals definition per colon definition, and that locals definition must
                   2068: be outside any controll structure.
                   2069: 
                   2070: With locals you can write slightly longer definitions without running
                   2071: into stack trouble.  However, I recommend trying to write colon
                   2072: definitions without locals for exercise purposes to help you gain the
                   2073: essential factoring skills.
                   2074: 
                   2075: @assignment
                   2076: Rewrite your definitions until now with locals
                   2077: @endassignment
                   2078: 
1.66    ! anton    2079: Reference: @ref{Locals}.
        !          2080: 
1.48      anton    2081: 
                   2082: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   2083: @section Conditional execution
1.66    ! anton    2084: @cindex conditionals, tutorial
        !          2085: @cindex if, tutorial
1.48      anton    2086: 
                   2087: In Forth you can use control structures only inside colon definitions.
                   2088: An @code{if}-structure looks like this:
                   2089: 
                   2090: @example
                   2091: : abs ( n1 -- +n2 )
                   2092:     dup 0 < if
                   2093:         negate
                   2094:     endif ;
                   2095: 5 abs .
                   2096: -5 abs .
                   2097: @end example
                   2098: 
                   2099: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   2100: the following code is performed, otherwise execution continues after the
1.51      pazsan   2101: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.48      anton    2102: elements and prioduces a flag:
                   2103: 
                   2104: @example
                   2105: 1 2 < .
                   2106: 2 1 < .
                   2107: 1 1 < .
                   2108: @end example
                   2109: 
                   2110: Actually the standard name for @code{endif} is @code{then}.  This
                   2111: tutorial presents the examples using @code{endif}, because this is often
                   2112: less confusing for people familiar with other programming languages
                   2113: where @code{then} has a different meaning.  If your system does not have
                   2114: @code{endif}, define it with
                   2115: 
                   2116: @example
                   2117: : endif postpone then ; immediate
                   2118: @end example
                   2119: 
                   2120: You can optionally use an @code{else}-part:
                   2121: 
                   2122: @example
                   2123: : min ( n1 n2 -- n )
                   2124:   2dup < if
                   2125:     drop
                   2126:   else
                   2127:     nip
                   2128:   endif ;
                   2129: 2 3 min .
                   2130: 3 2 min .
                   2131: @end example
                   2132: 
                   2133: @assignment
                   2134: Write @code{min} without @code{else}-part (hint: what's the definition
                   2135: of @code{nip}?).
                   2136: @endassignment
                   2137: 
1.66    ! anton    2138: Reference: @ref{Selection}.
        !          2139: 
1.48      anton    2140: 
                   2141: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   2142: @section Flags and Comparisons
1.66    ! anton    2143: @cindex flags tutorial
        !          2144: @cindex comparison tutorial
1.48      anton    2145: 
                   2146: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   2147: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   2148: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   2149: treated as true flag.
                   2150: 
                   2151: @example
                   2152: false .
                   2153: true .
                   2154: true hex u. decimal
                   2155: @end example
                   2156: 
                   2157: Comparison words produce canonical flags:
                   2158: 
                   2159: @example
                   2160: 1 1 = .
                   2161: 1 0= .
                   2162: 0 1 < .
                   2163: 0 0 < .
                   2164: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   2165: -1 1 < .
                   2166: @end example
                   2167: 
1.66    ! anton    2168: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
        !          2169: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
        !          2170: these combinations are standard (for details see the standard,
        !          2171: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48      anton    2172: 
                   2173: You can use @code{and or xor invert} can be used as operations on
                   2174: canonical flags.  Actually they are bitwise operations:
                   2175: 
                   2176: @example
                   2177: 1 2 and .
                   2178: 1 2 or .
                   2179: 1 3 xor .
                   2180: 1 invert .
                   2181: @end example
                   2182: 
                   2183: You can convert a zero/non-zero flag into a canonical flag with
                   2184: @code{0<>} (and complement it on the way with @code{0=}).
                   2185: 
                   2186: @example
                   2187: 1 0= .
                   2188: 1 0<> .
                   2189: @end example
                   2190: 
1.65      anton    2191: You can use the all-bits-set feature of canonical flags and the bitwise
1.48      anton    2192: operation of the Boolean operations to avoid @code{if}s:
                   2193: 
                   2194: @example
                   2195: : foo ( n1 -- n2 )
                   2196:   0= if
                   2197:     14
                   2198:   else
                   2199:     0
                   2200:   endif ;
                   2201: 0 foo .
                   2202: 1 foo .
                   2203: 
                   2204: : foo ( n1 -- n2 )
                   2205:   0= 14 and ;
                   2206: 0 foo .
                   2207: 1 foo .
                   2208: @end example
                   2209: 
                   2210: @assignment
                   2211: Write @code{min} without @code{if}.
                   2212: @endassignment
                   2213: 
1.66    ! anton    2214: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
        !          2215: @ref{Bitwise operations}.
        !          2216: 
1.48      anton    2217: 
                   2218: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   2219: @section General Loops
1.66    ! anton    2220: @cindex loops, indefinite, tutorial
1.48      anton    2221: 
                   2222: The endless loop is the most simple one:
                   2223: 
                   2224: @example
                   2225: : endless ( -- )
                   2226:   0 begin
                   2227:     dup . 1+
                   2228:   again ;
                   2229: endless
                   2230: @end example
                   2231: 
                   2232: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   2233: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   2234: 
                   2235: A loop with one exit at any place looks like this:
                   2236: 
                   2237: @example
                   2238: : log2 ( +n1 -- n2 )
                   2239: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2240:   assert( dup 0> )
                   2241:   2/ 0 begin
                   2242:     over 0> while
                   2243:       1+ swap 2/ swap
                   2244:   repeat
                   2245:   nip ;
                   2246: 7 log2 .
                   2247: 8 log2 .
                   2248: @end example
                   2249: 
                   2250: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   2251: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    2252: continues behind the @code{while}.  @code{Repeat} jumps back to
                   2253: @code{begin}, just like @code{again}.
                   2254: 
                   2255: In Forth there are many combinations/abbreviations, like @code{1+}.
                   2256: However, @code{2/} is not one of them; it shifts it's argument right by
                   2257: one bit (arithmetic shift right):
                   2258: 
                   2259: @example
                   2260: -5 2 / .
                   2261: -5 2/ .
                   2262: @end example
                   2263: 
                   2264: @code{assert(} is no standard word, but you can get it on systems other
                   2265: then Gforth by including @file{compat/assert.fs}.  You can see what it
                   2266: does by trying
                   2267: 
                   2268: @example
                   2269: 0 log2 .
                   2270: @end example
                   2271: 
                   2272: Here's a loop with an exit at the end:
                   2273: 
                   2274: @example
                   2275: : log2 ( +n1 -- n2 )
                   2276: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2277:   assert( dup 0 > )
                   2278:   -1 begin
                   2279:     1+ swap 2/ swap
                   2280:     over 0 <=
                   2281:   until
                   2282:   nip ;
                   2283: @end example
                   2284: 
                   2285: @code{Until} consumes a flag; if it is non-zero, execution continues at
                   2286: the @code{begin}, otherwise after the @code{until}.
                   2287: 
                   2288: @assignment
                   2289: Write a definition for computing the greatest common divisor.
                   2290: @endassignment
                   2291: 
1.66    ! anton    2292: Reference: @ref{Simple Loops}.
        !          2293: 
1.48      anton    2294: 
                   2295: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   2296: @section Counted loops
1.66    ! anton    2297: @cindex loops, counted, tutorial
1.48      anton    2298: 
                   2299: @example
                   2300: : ^ ( n1 u -- n )
                   2301: \ n = the uth power of u1
                   2302:   1 swap 0 u+do
                   2303:     over *
                   2304:   loop
                   2305:   nip ;
                   2306: 3 2 ^ .
                   2307: 4 3 ^ .
                   2308: @end example
                   2309: 
                   2310: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   2311: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   2312: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2313: times (or not at all, if @code{u3-u4<0}).
                   2314: 
                   2315: You can see the stack effect design rules at work in the stack effect of
                   2316: the loop start words: Since the start value of the loop is more
                   2317: frequently constant than the end value, the start value is passed on
                   2318: the top-of-stack.
                   2319: 
                   2320: You can access the counter of a counted loop with @code{i}:
                   2321: 
                   2322: @example
                   2323: : fac ( u -- u! )
                   2324:   1 swap 1+ 1 u+do
                   2325:     i *
                   2326:   loop ;
                   2327: 5 fac .
                   2328: 7 fac .
                   2329: @end example
                   2330: 
                   2331: There is also @code{+do}, which expects signed numbers (important for
                   2332: deciding whether to enter the loop).
                   2333: 
                   2334: @assignment
                   2335: Write a definition for computing the nth Fibonacci number.
                   2336: @endassignment
                   2337: 
1.65      anton    2338: You can also use increments other than 1:
                   2339: 
                   2340: @example
                   2341: : up2 ( n1 n2 -- )
                   2342:   +do
                   2343:     i .
                   2344:   2 +loop ;
                   2345: 10 0 up2
                   2346: 
                   2347: : down2 ( n1 n2 -- )
                   2348:   -do
                   2349:     i .
                   2350:   2 -loop ;
                   2351: 0 10 down2
                   2352: @end example
1.48      anton    2353: 
1.66    ! anton    2354: Reference: @ref{Counted Loops}.
        !          2355: 
1.48      anton    2356: 
                   2357: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2358: @section Recursion
1.66    ! anton    2359: @cindex recursion tutorial
1.48      anton    2360: 
                   2361: Usually the name of a definition is not visible in the definition; but
                   2362: earlier definitions are usually visible:
                   2363: 
                   2364: @example
                   2365: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
                   2366: : / ( n1 n2 -- n )
                   2367:   dup 0= if
                   2368:     -10 throw \ report division by zero
                   2369:   endif
                   2370:   /           \ old version
                   2371: ;
                   2372: 1 0 /
                   2373: @end example
                   2374: 
                   2375: For recursive definitions you can use @code{recursive} (non-standard) or
                   2376: @code{recurse}:
                   2377: 
                   2378: @example
                   2379: : fac1 ( n -- n! ) recursive
                   2380:  dup 0> if
                   2381:    dup 1- fac1 *
                   2382:  else
                   2383:    drop 1
                   2384:  endif ;
                   2385: 7 fac1 .
                   2386: 
                   2387: : fac2 ( n -- n! )
                   2388:  dup 0> if
                   2389:    dup 1- recurse *
                   2390:  else
                   2391:    drop 1
                   2392:  endif ;
                   2393: 8 fac2 .
                   2394: @end example
                   2395: 
                   2396: @assignment
                   2397: Write a recursive definition for computing the nth Fibonacci number.
                   2398: @endassignment
                   2399: 
1.66    ! anton    2400: Reference (including indirect recursion): @xref{Calls and returns}.
        !          2401: 
1.48      anton    2402: 
                   2403: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2404: @section Leaving definitions or loops
1.66    ! anton    2405: @cindex leaving definitions, tutorial
        !          2406: @cindex leaving loops, tutorial
1.48      anton    2407: 
                   2408: @code{EXIT} exits the current definition right away.  For every counted
                   2409: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2410: before the @code{EXIT}:
                   2411: 
                   2412: @c !! real examples
                   2413: @example
                   2414: : ...
                   2415:  ... u+do
                   2416:    ... if
                   2417:      ... unloop exit
                   2418:    endif
                   2419:    ...
                   2420:  loop
                   2421:  ... ;
                   2422: @end example
                   2423: 
                   2424: @code{LEAVE} leaves the innermost counted loop right away:
                   2425: 
                   2426: @example
                   2427: : ...
                   2428:  ... u+do
                   2429:    ... if
                   2430:      ... leave
                   2431:    endif
                   2432:    ...
                   2433:  loop
                   2434:  ... ;
                   2435: @end example
                   2436: 
1.65      anton    2437: @c !! example
1.48      anton    2438: 
1.66    ! anton    2439: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
        !          2440: 
        !          2441: 
1.48      anton    2442: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2443: @section Return Stack
1.66    ! anton    2444: @cindex return stack tutorial
1.48      anton    2445: 
                   2446: In addition to the data stack Forth also has a second stack, the return
                   2447: stack; most Forth systems store the return addresses of procedure calls
                   2448: there (thus its name).  Programmers can also use this stack:
                   2449: 
                   2450: @example
                   2451: : foo ( n1 n2 -- )
                   2452:  .s
                   2453:  >r .s
1.50      anton    2454:  r@@ .
1.48      anton    2455:  >r .s
1.50      anton    2456:  r@@ .
1.48      anton    2457:  r> .
1.50      anton    2458:  r@@ .
1.48      anton    2459:  r> . ;
                   2460: 1 2 foo
                   2461: @end example
                   2462: 
                   2463: @code{>r} takes an element from the data stack and pushes it onto the
                   2464: return stack; conversely, @code{r>} moves an elementm from the return to
                   2465: the data stack; @code{r@@} pushes a copy of the top of the return stack
                   2466: on the return stack.
                   2467: 
                   2468: Forth programmers usually use the return stack for storing data
                   2469: temporarily, if using the data stack alone would be too complex, and
                   2470: factoring and locals are not an option:
                   2471: 
                   2472: @example
                   2473: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2474:  rot >r rot r> ;
                   2475: @end example
                   2476: 
                   2477: The return address of the definition and the loop control parameters of
                   2478: counted loops usually reside on the return stack, so you have to take
                   2479: all items, that you have pushed on the return stack in a colon
                   2480: definition or counted loop, from the return stack before the definition
                   2481: or loop ends.  You cannot access items that you pushed on the return
                   2482: stack outside some definition or loop within the definition of loop.
                   2483: 
                   2484: If you miscount the return stack items, this usually ends in a crash:
                   2485: 
                   2486: @example
                   2487: : crash ( n -- )
                   2488:   >r ;
                   2489: 5 crash
                   2490: @end example
                   2491: 
                   2492: You cannot mix using locals and using the return stack (according to the
                   2493: standard; Gforth has no problem).  However, they solve the same
                   2494: problems, so this shouldn't be an issue.
                   2495: 
                   2496: @assignment
                   2497: Can you rewrite any of the definitions you wrote until now in a better
                   2498: way using the return stack?
                   2499: @endassignment
                   2500: 
1.66    ! anton    2501: Reference: @ref{Return stack}.
        !          2502: 
1.48      anton    2503: 
                   2504: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2505: @section Memory
1.66    ! anton    2506: @cindex memory access/allocation tutorial
1.48      anton    2507: 
                   2508: You can create a global variable @code{v} with
                   2509: 
                   2510: @example
                   2511: variable v ( -- addr )
                   2512: @end example
                   2513: 
                   2514: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2515: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2516: values into this cell and @code{@@} (fetch) to load the value from the
                   2517: stack into memory:
                   2518: 
                   2519: @example
                   2520: v .
                   2521: 5 v ! .s
1.50      anton    2522: v @@ .
1.48      anton    2523: @end example
                   2524: 
1.65      anton    2525: You can see a raw dump of memory with @code{dump}:
                   2526: 
                   2527: @example
                   2528: v 1 cells .s dump
                   2529: @end example
                   2530: 
                   2531: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
                   2532: generally, address units (aus)) that @code{n1 cells} occupy.  You can
                   2533: also reserve more memory:
1.48      anton    2534: 
                   2535: @example
                   2536: create v2 20 cells allot
1.65      anton    2537: v2 20 cells dump
1.48      anton    2538: @end example
                   2539: 
1.65      anton    2540: creates a word @code{v2} and reserves 20 uninitialized cells; the
                   2541: address pushed by @code{v2} points to the start of these 20 cells.  You
                   2542: can use address arithmetic to access these cells:
1.48      anton    2543: 
                   2544: @example
                   2545: 3 v2 5 cells + !
1.65      anton    2546: v2 20 cells dump
1.48      anton    2547: @end example
                   2548: 
                   2549: You can reserve and initialize memory with @code{,}:
                   2550: 
                   2551: @example
                   2552: create v3
                   2553:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2554: v3 @@ .
                   2555: v3 cell+ @@ .
                   2556: v3 2 cells + @@ .
1.65      anton    2557: v3 5 cells dump
1.48      anton    2558: @end example
                   2559: 
                   2560: @assignment
                   2561: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2562: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2563: one at @code{addr cell+} etc.
                   2564: @endassignment
                   2565: 
                   2566: You can also reserve memory without creating a new word:
                   2567: 
                   2568: @example
1.60      anton    2569: here 10 cells allot .
                   2570: here .
1.48      anton    2571: @end example
                   2572: 
                   2573: @code{Here} pushes the start address of the memory area.  You should
                   2574: store it somewhere, or you will have a hard time finding the memory area
                   2575: again.
                   2576: 
                   2577: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2578: the system's data structures for words etc. on Gforth and most other
                   2579: Forth systems.  It is managed like a stack: You can free the memory that
                   2580: you have just @code{allot}ed with
                   2581: 
                   2582: @example
                   2583: -10 cells allot
1.60      anton    2584: here .
1.48      anton    2585: @end example
                   2586: 
                   2587: Note that you cannot do this if you have created a new word in the
                   2588: meantime (because then your @code{allot}ed memory is no longer on the
                   2589: top of the dictionary ``stack'').
                   2590: 
                   2591: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2592: freeing memory in any order:
                   2593: 
                   2594: @example
                   2595: 10 cells allocate throw .s
                   2596: 20 cells allocate throw .s
                   2597: swap
                   2598: free throw
                   2599: free throw
                   2600: @end example
                   2601: 
                   2602: The @code{throw}s deal with errors (e.g., out of memory).
                   2603: 
1.65      anton    2604: And there is also a
                   2605: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   2606: garbage collector}, which eliminates the need to @code{free} memory
                   2607: explicitly.
1.48      anton    2608: 
1.66    ! anton    2609: Reference: @ref{Memory}.
        !          2610: 
1.48      anton    2611: 
                   2612: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2613: @section Characters and Strings
1.66    ! anton    2614: @cindex strings tutorial
        !          2615: @cindex characters tutorial
1.48      anton    2616: 
                   2617: On the stack characters take up a cell, like numbers.  In memory they
                   2618: have their own size (one 8-bit byte on most systems), and therefore
                   2619: require their own words for memory access:
                   2620: 
                   2621: @example
                   2622: create v4 
                   2623:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2624: v4 4 chars + c@@ .
1.65      anton    2625: v4 5 chars dump
1.48      anton    2626: @end example
                   2627: 
                   2628: The preferred representation of strings on the stack is @code{addr
                   2629: u-count}, where @code{addr} is the address of the first character and
                   2630: @code{u-count} is the number of characters in the string.
                   2631: 
                   2632: @example
                   2633: v4 5 type
                   2634: @end example
                   2635: 
                   2636: You get a string constant with
                   2637: 
                   2638: @example
                   2639: s" hello, world" .s
                   2640: type
                   2641: @end example
                   2642: 
                   2643: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2644: is a normal Forth word and must be delimited with white space (try what
                   2645: happens when you remove the space).
                   2646: 
                   2647: However, this interpretive use of @code{s"} is quite restricted: the
                   2648: string exists only until the next call of @code{s"} (some Forth systems
                   2649: keep more than one of these strings, but usually they still have a
1.62      crook    2650: limited lifetime).
1.48      anton    2651: 
                   2652: @example
                   2653: s" hello," s" world" .s
                   2654: type
                   2655: type
                   2656: @end example
                   2657: 
1.62      crook    2658: You can also use @code{s"} in a definition, and the resulting
                   2659: strings then live forever (well, for as long as the definition):
1.48      anton    2660: 
                   2661: @example
                   2662: : foo s" hello," s" world" ;
                   2663: foo .s
                   2664: type
                   2665: type
                   2666: @end example
                   2667: 
                   2668: @assignment
                   2669: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2670: Implement @code{type ( addr u -- )}.
                   2671: @endassignment
                   2672: 
1.66    ! anton    2673: Reference: @ref{Memory Blocks}.
        !          2674: 
        !          2675: 
1.48      anton    2676: @node Alignment Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Characters and Strings Tutorial, Tutorial
                   2677: @section Alignment
1.66    ! anton    2678: @cindex alignment tutorial
        !          2679: @cindex memory alignment tutorial
1.48      anton    2680: 
                   2681: On many processors cells have to be aligned in memory, if you want to
                   2682: access them with @code{@@} and @code{!} (and even if the processor does
1.62      crook    2683: not require alignment, access to aligned cells is faster).
1.48      anton    2684: 
                   2685: @code{Create} aligns @code{here} (i.e., the place where the next
                   2686: allocation will occur, and that the @code{create}d word points to).
                   2687: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2688: address.  Adding a number of @code{cells} to an aligned address produces
                   2689: another aligned address.
                   2690: 
                   2691: However, address arithmetic involving @code{char+} and @code{chars} can
                   2692: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2693: a-addr )} produces the next aligned address:
                   2694: 
                   2695: @example
1.50      anton    2696: v3 char+ aligned .s @@ .
                   2697: v3 char+ .s @@ .
1.48      anton    2698: @end example
                   2699: 
                   2700: Similarly, @code{align} advances @code{here} to the next aligned
                   2701: address:
                   2702: 
                   2703: @example
                   2704: create v5 97 c,
                   2705: here .
                   2706: align here .
                   2707: 1000 ,
                   2708: @end example
                   2709: 
                   2710: Note that you should use aligned addresses even if your processor does
                   2711: not require them, if you want your program to be portable.
                   2712: 
1.66    ! anton    2713: Reference: @ref{Address arithmetic}.
        !          2714: 
1.48      anton    2715: 
                   2716: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Alignment Tutorial, Tutorial
                   2717: @section Interpretation and Compilation Semantics and Immediacy
1.66    ! anton    2718: @cindex semantics tutorial
        !          2719: @cindex interpretation semantics tutorial
        !          2720: @cindex compilation semantics tutorial
        !          2721: @cindex immediate, tutorial
1.48      anton    2722: 
                   2723: When a word is compiled, it behaves differently from being interpreted.
                   2724: E.g., consider @code{+}:
                   2725: 
                   2726: @example
                   2727: 1 2 + .
                   2728: : foo + ;
                   2729: @end example
                   2730: 
                   2731: These two behaviours are known as compilation and interpretation
                   2732: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2733: is to append the interpretation semantics to the currently defined word
                   2734: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2735: later, the interpretation semantics of @code{+} (i.e., adding two
                   2736: numbers) will be performed.
                   2737: 
                   2738: However, there are words with non-default compilation semantics, e.g.,
                   2739: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2740: change the compilation semantics of the last defined word to be equal to
                   2741: the interpretation semantics:
                   2742: 
                   2743: @example
                   2744: : [FOO] ( -- )
                   2745:  5 . ; immediate
                   2746: 
                   2747: [FOO]
                   2748: : bar ( -- )
                   2749:   [FOO] ;
                   2750: bar
                   2751: see bar
                   2752: @end example
                   2753: 
                   2754: Two conventions to mark words with non-default compilation semnatics are
                   2755: names with brackets (more frequently used) and to write them all in
                   2756: upper case (less frequently used).
                   2757: 
                   2758: In Gforth (and many other systems) you can also remove the
                   2759: interpretation semantics with @code{compile-only} (the compilation
                   2760: semantics is derived from the original interpretation semantics):
                   2761: 
                   2762: @example
                   2763: : flip ( -- )
                   2764:  6 . ; compile-only \ but not immediate
                   2765: flip
                   2766: 
                   2767: : flop ( -- )
                   2768:  flip ;
                   2769: flop
                   2770: @end example
                   2771: 
                   2772: In this example the interpretation semantics of @code{flop} is equal to
                   2773: the original interpretation semantics of @code{flip}.
                   2774: 
                   2775: The text interpreter has two states: in interpret state, it performs the
                   2776: interpretation semantics of words it encounters; in compile state, it
                   2777: performs the compilation semantics of these words.
                   2778: 
                   2779: Among other things, @code{:} switches into compile state, and @code{;}
                   2780: switches back to interpret state.  They contain the factors @code{]}
                   2781: (switch to compile state) and @code{[} (switch to interpret state), that
                   2782: do nothing but switch the state.
                   2783: 
                   2784: @example
                   2785: : xxx ( -- )
                   2786:   [ 5 . ]
                   2787: ;
                   2788: 
                   2789: xxx
                   2790: see xxx
                   2791: @end example
                   2792: 
                   2793: These brackets are also the source of the naming convention mentioned
                   2794: above.
                   2795: 
1.66    ! anton    2796: Reference: @ref{Interpretation and Compilation Semantics}.
        !          2797: 
1.48      anton    2798: 
                   2799: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2800: @section Execution Tokens
1.66    ! anton    2801: @cindex execution tokens tutorial
        !          2802: @cindex XT tutorial
1.48      anton    2803: 
                   2804: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2805: cell representing the interpretation semantics of a word.  You can
                   2806: execute this semantics with @code{execute}:
                   2807: 
                   2808: @example
                   2809: ' + .s
                   2810: 1 2 rot execute .
                   2811: @end example
                   2812: 
                   2813: The XT is similar to a function pointer in C.  However, parameter
                   2814: passing through the stack makes it a little more flexible:
                   2815: 
                   2816: @example
                   2817: : map-array ( ... addr u xt -- ... )
1.50      anton    2818: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2819: \ at addr and containing u elements
1.48      anton    2820:   @{ xt @}
                   2821:   cells over + swap ?do
1.50      anton    2822:     i @@ xt execute
1.48      anton    2823:   1 cells +loop ;
                   2824: 
                   2825: create a 3 , 4 , 2 , -1 , 4 ,
                   2826: a 5 ' . map-array .s
                   2827: 0 a 5 ' + map-array .
                   2828: s" max-n" environment? drop .s
                   2829: a 5 ' min map-array .
                   2830: @end example
                   2831: 
                   2832: You can use map-array with the XTs of words that consume one element
                   2833: more than they produce.  In theory you can also use it with other XTs,
                   2834: but the stack effect then depends on the size of the array, which is
                   2835: hard to understand.
                   2836: 
1.51      pazsan   2837: Since XTs are cell-sized, you can store them in memory and manipulate
                   2838: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2839: word with @code{compile,}:
                   2840: 
                   2841: @example
                   2842: : foo1 ( n1 n2 -- n )
                   2843:    [ ' + compile, ] ;
                   2844: see foo
                   2845: @end example
                   2846: 
                   2847: This is non-standard, because @code{compile,} has no compilation
                   2848: semantics in the standard, but it works in good Forth systems.  For the
                   2849: broken ones, use
                   2850: 
                   2851: @example
                   2852: : [compile,] compile, ; immediate
                   2853: 
                   2854: : foo1 ( n1 n2 -- n )
                   2855:    [ ' + ] [compile,] ;
                   2856: see foo
                   2857: @end example
                   2858: 
                   2859: @code{'} is a word with default compilation semantics; it parses the
                   2860: next word when its interpretation semantics are executed, not during
                   2861: compilation:
                   2862: 
                   2863: @example
                   2864: : foo ( -- xt )
                   2865:   ' ;
                   2866: see foo
                   2867: : bar ( ... "word" -- ... )
                   2868:   ' execute ;
                   2869: see bar
1.60      anton    2870: 1 2 bar + .
1.48      anton    2871: @end example
                   2872: 
                   2873: You often want to parse a word during compilation and compile its XT so
                   2874: it will be pushed on the stack at run-time.  @code{[']} does this:
                   2875: 
                   2876: @example
                   2877: : xt-+ ( -- xt )
                   2878:   ['] + ;
                   2879: see xt-+
                   2880: 1 2 xt-+ execute .
                   2881: @end example
                   2882: 
                   2883: Many programmers tend to see @code{'} and the word it parses as one
                   2884: unit, and expect it to behave like @code{[']} when compiled, and are
                   2885: confused by the actual behaviour.  If you are, just remember that the
                   2886: Forth system just takes @code{'} as one unit and has no idea that it is
                   2887: a parsing word (attempts to convenience programmers in this issue have
                   2888: usually resulted in even worse pitfalls, see
1.66    ! anton    2889: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
        !          2890: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48      anton    2891: 
                   2892: Note that the state of the interpreter does not come into play when
1.51      pazsan   2893: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    2894: compile state, it still gives you the interpretation semantics.  And
                   2895: whatever that state is, @code{execute} performs the semantics
1.66    ! anton    2896: represented by the XT (i.e., for XTs produced with @code{'} the
        !          2897: interpretation semantics).
        !          2898: 
        !          2899: Reference: @ref{Tokens for Words}.
1.48      anton    2900: 
                   2901: 
                   2902: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   2903: @section Exceptions
1.66    ! anton    2904: @cindex exceptions tutorial
1.48      anton    2905: 
                   2906: @code{throw ( n -- )} causes an exception unless n is zero.
                   2907: 
                   2908: @example
                   2909: 100 throw .s
                   2910: 0 throw .s
                   2911: @end example
                   2912: 
                   2913: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   2914: it catches exceptions and pushes the number of the exception on the
                   2915: stack (or 0, if the xt executed without exception).  If there was an
                   2916: exception, the stacks have the same depth as when entering @code{catch}:
                   2917: 
                   2918: @example
                   2919: .s
                   2920: 3 0 ' / catch .s
                   2921: 3 2 ' / catch .s
                   2922: @end example
                   2923: 
                   2924: @assignment
                   2925: Try the same with @code{execute} instead of @code{catch}.
                   2926: @endassignment
                   2927: 
                   2928: @code{Throw} always jumps to the dynamically next enclosing
                   2929: @code{catch}, even if it has to leave several call levels to achieve
                   2930: this:
                   2931: 
                   2932: @example
                   2933: : foo 100 throw ;
                   2934: : foo1 foo ." after foo" ;
1.51      pazsan   2935: : bar ['] foo1 catch ;
1.60      anton    2936: bar .
1.48      anton    2937: @end example
                   2938: 
                   2939: It is often important to restore a value upon leaving a definition, even
                   2940: if the definition is left through an exception.  You can ensure this
                   2941: like this:
                   2942: 
                   2943: @example
                   2944: : ...
                   2945:    save-x
1.51      pazsan   2946:    ['] word-changing-x catch ( ... n )
1.48      anton    2947:    restore-x
                   2948:    ( ... n ) throw ;
                   2949: @end example
                   2950: 
1.55      anton    2951: Gforth provides an alternative syntax in addition to @code{catch}:
1.48      anton    2952: @code{try ... recover ... endtry}.  If the code between @code{try} and
                   2953: @code{recover} has an exception, the stack depths are restored, the
                   2954: exception number is pushed on the stack, and the code between
                   2955: @code{recover} and @code{endtry} is performed.  E.g., the definition for
                   2956: @code{catch} is
                   2957: 
                   2958: @example
                   2959: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
                   2960:   try
                   2961:     execute 0
                   2962:   recover
                   2963:     nip
                   2964:   endtry ;
                   2965: @end example
                   2966: 
                   2967: The equivalent to the restoration code above is
                   2968: 
                   2969: @example
                   2970: : ...
                   2971:   save-x
                   2972:   try
                   2973:     word-changing-x
                   2974:   end-try
                   2975:   restore-x
                   2976:   throw ;
                   2977: @end example
                   2978: 
                   2979: As you can see, the @code{recover} part is optional.
                   2980: 
1.66    ! anton    2981: Reference: @ref{Exception Handling}.
        !          2982: 
1.48      anton    2983: 
                   2984: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   2985: @section Defining Words
1.66    ! anton    2986: @cindex defining words tutorial
        !          2987: @cindex does> tutorial
        !          2988: @cindex create...does> tutorial
        !          2989: 
        !          2990: @c before semantics?
1.48      anton    2991: 
                   2992: @code{:}, @code{create}, and @code{variable} are definition words: They
                   2993: define other words.  @code{Constant} is another definition word:
                   2994: 
                   2995: @example
                   2996: 5 constant foo
                   2997: foo .
                   2998: @end example
                   2999: 
                   3000: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   3001: (floating point) with @code{variable} and @code{constant}.
                   3002: 
                   3003: You can also define your own defining words.  E.g.:
                   3004: 
                   3005: @example
                   3006: : variable ( "name" -- )
                   3007:   create 0 , ;
                   3008: @end example
                   3009: 
                   3010: You can also define defining words that create words that do something
                   3011: other than just producing their address:
                   3012: 
                   3013: @example
                   3014: : constant ( n "name" -- )
                   3015:   create ,
                   3016: does> ( -- n )
1.50      anton    3017:   ( addr ) @@ ;
1.48      anton    3018: 
                   3019: 5 constant foo
                   3020: foo .
                   3021: @end example
                   3022: 
                   3023: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   3024: @code{does>} replaces @code{;}, but it also does something else: It
                   3025: changes the last defined word such that it pushes the address of the
                   3026: body of the word and then performs the code after the @code{does>}
                   3027: whenever it is called.
                   3028: 
                   3029: In the example above, @code{constant} uses @code{,} to store 5 into the
                   3030: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   3031: the body onto the stack, then (in the code after the @code{does>})
                   3032: fetches the 5 from there.
                   3033: 
                   3034: The stack comment near the @code{does>} reflects the stack effect of the
                   3035: defined word, not the stack effect of the code after the @code{does>}
                   3036: (the difference is that the code expects the address of the body that
                   3037: the stack comment does not show).
                   3038: 
                   3039: You can use these definition words to do factoring in cases that involve
                   3040: (other) definition words.  E.g., a field offset is always added to an
                   3041: address.  Instead of defining
                   3042: 
                   3043: @example
                   3044: 2 cells constant offset-field1
                   3045: @end example
                   3046: 
                   3047: and using this like
                   3048: 
                   3049: @example
                   3050: ( addr ) offset-field1 +
                   3051: @end example
                   3052: 
                   3053: you can define a definition word
                   3054: 
                   3055: @example
                   3056: : simple-field ( n "name" -- )
                   3057:   create ,
                   3058: does> ( n1 -- n1+n )
1.50      anton    3059:   ( addr ) @@ + ;
1.48      anton    3060: @end example
1.21      crook    3061: 
1.48      anton    3062: Definition and use of field offsets now look like this:
1.21      crook    3063: 
1.48      anton    3064: @example
                   3065: 2 cells simple-field field1
1.60      anton    3066: create mystruct 4 cells allot
                   3067: mystruct .s field1 .s drop
1.48      anton    3068: @end example
1.21      crook    3069: 
1.48      anton    3070: If you want to do something with the word without performing the code
                   3071: after the @code{does>}, you can access the body of a @code{create}d word
                   3072: with @code{>body ( xt -- addr )}:
1.21      crook    3073: 
1.48      anton    3074: @example
                   3075: : value ( n "name" -- )
                   3076:   create ,
                   3077: does> ( -- n1 )
1.50      anton    3078:   @@ ;
1.48      anton    3079: : to ( n "name" -- )
                   3080:   ' >body ! ;
1.21      crook    3081: 
1.48      anton    3082: 5 value foo
                   3083: foo .
                   3084: 7 to foo
                   3085: foo .
                   3086: @end example
1.21      crook    3087: 
1.48      anton    3088: @assignment
                   3089: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   3090: XT (at the start the XT of @code{abort}), and upon execution
                   3091: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   3092: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   3093: recursion is one application of @code{defer}.
                   3094: @endassignment
1.29      crook    3095: 
1.66    ! anton    3096: Reference: @ref{User-defined Defining Words}.
        !          3097: 
        !          3098: 
1.48      anton    3099: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   3100: @section Arrays and Records
1.66    ! anton    3101: @cindex arrays tutorial
        !          3102: @cindex records tutorial
        !          3103: @cindex structs tutorial
1.29      crook    3104: 
1.48      anton    3105: Forth has no standard words for defining data structures such as arrays
                   3106: and records (structs in C terminology), but you can build them yourself
                   3107: based on address arithmetic.  You can also define words for defining
                   3108: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    3109: 
1.48      anton    3110: One of the first projects a Forth newcomer sets out upon when learning
                   3111: about defining words is an array defining word (possibly for
                   3112: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   3113: learn something from it.  However, don't be disappointed when you later
                   3114: learn that you have little use for these words (inappropriate use would
                   3115: be even worse).  I have not yet found a set of useful array words yet;
                   3116: the needs are just too diverse, and named, global arrays (the result of
                   3117: naive use of defining words) are often not flexible enough (e.g.,
1.66    ! anton    3118: consider how to pass them as parameters).  Another such project is a set
        !          3119: of words to help dealing with strings.
1.29      crook    3120: 
1.48      anton    3121: On the other hand, there is a useful set of record words, and it has
                   3122: been defined in @file{compat/struct.fs}; these words are predefined in
                   3123: Gforth.  They are explained in depth elsewhere in this manual (see
                   3124: @pxref{Structures}).  The @code{simple-field} example above is
                   3125: simplified variant of fields in this package.
1.21      crook    3126: 
                   3127: 
1.48      anton    3128: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   3129: @section @code{POSTPONE}
1.66    ! anton    3130: @cindex postpone tutorial
1.21      crook    3131: 
1.48      anton    3132: You can compile the compilation semantics (instead of compiling the
                   3133: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    3134: 
1.48      anton    3135: @example
                   3136: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   3137:  POSTPONE + ; immediate
1.48      anton    3138: : foo ( n1 n2 -- n )
                   3139:  MY-+ ;
                   3140: 1 2 foo .
                   3141: see foo
                   3142: @end example
1.21      crook    3143: 
1.48      anton    3144: During the definition of @code{foo} the text interpreter performs the
                   3145: compilation semantics of @code{MY-+}, which performs the compilation
                   3146: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   3147: 
                   3148: This example also displays separate stack comments for the compilation
                   3149: semantics and for the stack effect of the compiled code.  For words with
                   3150: default compilation semantics these stack effects are usually not
                   3151: displayed; the stack effect of the compilation semantics is always
                   3152: @code{( -- )} for these words, the stack effect for the compiled code is
                   3153: the stack effect of the interpretation semantics.
                   3154: 
                   3155: Note that the state of the interpreter does not come into play when
                   3156: performing the compilation semantics in this way.  You can also perform
                   3157: it interpretively, e.g.:
                   3158: 
                   3159: @example
                   3160: : foo2 ( n1 n2 -- n )
                   3161:  [ MY-+ ] ;
                   3162: 1 2 foo .
                   3163: see foo
                   3164: @end example
1.21      crook    3165: 
1.48      anton    3166: However, there are some broken Forth systems where this does not always
1.62      crook    3167: work, and therefore this practice was been declared non-standard in
1.48      anton    3168: 1999.
                   3169: @c !! repair.fs
                   3170: 
                   3171: Here is another example for using @code{POSTPONE}:
1.44      crook    3172: 
1.48      anton    3173: @example
                   3174: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   3175:  POSTPONE negate POSTPONE + ; immediate compile-only
                   3176: : bar ( n1 n2 -- n )
                   3177:   MY-- ;
                   3178: 2 1 bar .
                   3179: see bar
                   3180: @end example
1.21      crook    3181: 
1.48      anton    3182: You can define @code{ENDIF} in this way:
1.21      crook    3183: 
1.48      anton    3184: @example
                   3185: : ENDIF ( Compilation: orig -- )
                   3186:   POSTPONE then ; immediate
                   3187: @end example
1.21      crook    3188: 
1.48      anton    3189: @assignment
                   3190: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   3191: @code{2dup}, but compiles @code{over over}.
                   3192: @endassignment
1.29      crook    3193: 
1.66    ! anton    3194: @c !! @xref{Macros} for reference
        !          3195: 
        !          3196: 
1.48      anton    3197: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3198: @section @code{Literal}
1.66    ! anton    3199: @cindex literal tutorial
1.29      crook    3200: 
1.48      anton    3201: You cannot @code{POSTPONE} numbers:
1.21      crook    3202: 
1.48      anton    3203: @example
                   3204: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3205: @end example
                   3206: 
1.48      anton    3207: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3208: 
1.48      anton    3209: @example
                   3210: : [FOO] ( compilation: --; run-time: -- n )
                   3211:   500 POSTPONE literal ; immediate
1.29      crook    3212: 
1.60      anton    3213: : flip [FOO] ;
1.48      anton    3214: flip .
                   3215: see flip
                   3216: @end example
1.29      crook    3217: 
1.48      anton    3218: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3219: semantics are executed) and pushes it at run-time (when the code it
                   3220: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3221: number computed at compile time into the current word:
1.29      crook    3222: 
1.48      anton    3223: @example
                   3224: : bar ( -- n )
                   3225:   [ 2 2 + ] literal ;
                   3226: see bar
                   3227: @end example
1.29      crook    3228: 
1.48      anton    3229: @assignment
                   3230: Write @code{]L} which allows writing the example above as @code{: bar (
                   3231: -- n ) [ 2 2 + ]L ;}
                   3232: @endassignment
                   3233: 
1.66    ! anton    3234: @c !! @xref{Macros} for reference
        !          3235: 
1.48      anton    3236: 
                   3237: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3238: @section Advanced macros
1.66    ! anton    3239: @cindex macros, advanced tutorial
        !          3240: @cindex run-time code generation, tutorial
1.48      anton    3241: 
1.66    ! anton    3242: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
        !          3243: Execution Tokens}.  It frequently performs @code{execute}, a relatively
        !          3244: expensive operation in some Forth implementations.  You can use
1.48      anton    3245: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3246: and produce a word that contains the word to be performed directly:
                   3247: 
                   3248: @c use ]] ... [[
                   3249: @example
                   3250: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3251: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3252: \ array beginning at addr and containing u elements
                   3253:   @{ xt @}
                   3254:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3255:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3256:   1 cells POSTPONE literal POSTPONE +loop ;
                   3257: 
                   3258: : sum-array ( addr u -- n )
                   3259:  0 rot rot [ ' + compile-map-array ] ;
                   3260: see sum-array
                   3261: a 5 sum-array .
                   3262: @end example
                   3263: 
                   3264: You can use the full power of Forth for generating the code; here's an
                   3265: example where the code is generated in a loop:
                   3266: 
                   3267: @example
                   3268: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3269: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3270:   POSTPONE tuck POSTPONE @@
1.48      anton    3271:   POSTPONE literal POSTPONE * POSTPONE +
                   3272:   POSTPONE swap POSTPONE cell+ ;
                   3273: 
                   3274: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3275: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3276:   0 postpone literal postpone swap
                   3277:   [ ' compile-vmul-step compile-map-array ]
                   3278:   postpone drop ;
                   3279: see compile-vmul
                   3280: 
                   3281: : a-vmul ( addr -- n )
1.51      pazsan   3282: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3283:  [ a 5 compile-vmul ] ;
                   3284: see a-vmul
                   3285: a a-vmul .
                   3286: @end example
                   3287: 
                   3288: This example uses @code{compile-map-array} to show off, but you could
1.66    ! anton    3289: also use @code{map-array} instead (try it now!).
1.48      anton    3290: 
                   3291: You can use this technique for efficient multiplication of large
                   3292: matrices.  In matrix multiplication, you multiply every line of one
                   3293: matrix with every column of the other matrix.  You can generate the code
                   3294: for one line once, and use it for every column.  The only downside of
                   3295: this technique is that it is cumbersome to recover the memory consumed
                   3296: by the generated code when you are done (and in more complicated cases
                   3297: it is not possible portably).
                   3298: 
1.66    ! anton    3299: @c !! @xref{Macros} for reference
        !          3300: 
        !          3301: 
1.48      anton    3302: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3303: @section Compilation Tokens
1.66    ! anton    3304: @cindex compilation tokens, tutorial
        !          3305: @cindex CT, tutorial
1.48      anton    3306: 
                   3307: This section is Gforth-specific.  You can skip it.
                   3308: 
                   3309: @code{' word compile,} compiles the interpretation semantics.  For words
                   3310: with default compilation semantics this is the same as performing the
                   3311: compilation semantics.  To represent the compilation semantics of other
                   3312: words (e.g., words like @code{if} that have no interpretation
                   3313: semantics), Gforth has the concept of a compilation token (CT,
                   3314: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3315: You can perform the compilation semantics represented by a CT with
                   3316: @code{execute}:
1.29      crook    3317: 
1.48      anton    3318: @example
                   3319: : foo2 ( n1 n2 -- n )
                   3320:    [ comp' + execute ] ;
                   3321: see foo
                   3322: @end example
1.29      crook    3323: 
1.48      anton    3324: You can compile the compilation semantics represented by a CT with
                   3325: @code{postpone,}:
1.30      anton    3326: 
1.48      anton    3327: @example
                   3328: : foo3 ( -- )
                   3329:   [ comp' + postpone, ] ;
                   3330: see foo3
                   3331: @end example
1.30      anton    3332: 
1.51      pazsan   3333: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3334: @code{comp'} is particularly useful for words that have no
                   3335: interpretation semantics:
1.29      crook    3336: 
1.30      anton    3337: @example
1.48      anton    3338: ' if
1.60      anton    3339: comp' if .s 2drop
1.30      anton    3340: @end example
                   3341: 
1.66    ! anton    3342: Reference: @ref{Tokens for Words}.
        !          3343: 
1.29      crook    3344: 
1.48      anton    3345: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3346: @section Wordlists and Search Order
1.66    ! anton    3347: @cindex wordlists tutorial
        !          3348: @cindex search order, tutorial
1.48      anton    3349: 
                   3350: The dictionary is not just a memory area that allows you to allocate
                   3351: memory with @code{allot}, it also contains the Forth words, arranged in
                   3352: several wordlists.  When searching for a word in a wordlist,
                   3353: conceptually you start searching at the youngest and proceed towards
                   3354: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3355: you define a word with the same name as an older word, the new word
                   3356: shadows the older word.
                   3357: 
                   3358: Which wordlists are searched in which order is determined by the search
                   3359: order.  You can display the search order with @code{order}.  It displays
                   3360: first the search order, starting with the wordlist searched first, then
                   3361: it displays the wordlist that will contain newly defined words.
1.21      crook    3362: 
1.48      anton    3363: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3364: 
1.48      anton    3365: @example
                   3366: wordlist constant mywords
                   3367: @end example
1.21      crook    3368: 
1.48      anton    3369: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3370: defined words (the @emph{current} wordlist):
1.21      crook    3371: 
1.48      anton    3372: @example
                   3373: mywords set-current
                   3374: order
                   3375: @end example
1.26      crook    3376: 
1.48      anton    3377: Gforth does not display a name for the wordlist in @code{mywords}
                   3378: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3379: 
1.48      anton    3380: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3381: you want to put something into a specific wordlist without overall
                   3382: effect on the current wordlist, this typically looks like this:
1.21      crook    3383: 
1.48      anton    3384: @example
                   3385: get-current mywords set-current ( wid )
                   3386: create someword
                   3387: ( wid ) set-current
                   3388: @end example
1.21      crook    3389: 
1.48      anton    3390: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3391: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3392: searched wordlist is topmost.
1.21      crook    3393: 
1.48      anton    3394: @example
                   3395: get-order mywords swap 1+ set-order
                   3396: order
                   3397: @end example
1.21      crook    3398: 
1.48      anton    3399: Yes, the order of wordlists in the output of @code{order} is reversed
                   3400: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3401: 
1.48      anton    3402: @assignment
                   3403: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3404: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3405: removes the first searched wordlist from the search order.  Experiment
                   3406: with boundary conditions (you will see some crashes or situations that
                   3407: are hard or impossible to leave).
                   3408: @endassignment
1.21      crook    3409: 
1.48      anton    3410: The search order is a powerful foundation for providing features similar
                   3411: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3412: programs in this way has disadvantages for debugging and reuse/factoring
                   3413: that overcome the advantages in my experience (I don't do huge projects,
1.55      anton    3414: though).  These disadvantages are not so clear in other
1.48      anton    3415: languages/programming environments, because these langauges are not so
                   3416: strong in debugging and reuse.
1.21      crook    3417: 
1.66    ! anton    3418: @c !! example
        !          3419: 
        !          3420: Reference: @ref{Word Lists}.
1.21      crook    3421: 
1.29      crook    3422: @c ******************************************************************
1.48      anton    3423: @node Introduction, Words, Tutorial, Top
1.29      crook    3424: @comment node-name,     next,           previous, up
                   3425: @chapter An Introduction to ANS Forth
                   3426: @cindex Forth - an introduction
1.21      crook    3427: 
1.29      crook    3428: The primary purpose of this manual is to document Gforth. However, since
                   3429: Forth is not a widely-known language and there is a lack of up-to-date
                   3430: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3431: material.  For other sources of Forth-related
                   3432: information, see @ref{Forth-related information}.
1.21      crook    3433: 
1.29      crook    3434: The examples in this section should work on any ANS Forth; the
                   3435: output shown was produced using Gforth. Each example attempts to
                   3436: reproduce the exact output that Gforth produces. If you try out the
                   3437: examples (and you should), what you should type is shown @kbd{like this}
                   3438: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3439: that, where the example shows @key{RET} it means that you should
1.29      crook    3440: press the ``carriage return'' key. Unfortunately, some output formats for
                   3441: this manual cannot show the difference between @kbd{this} and
                   3442: @code{this} which will make trying out the examples harder (but not
                   3443: impossible).
1.21      crook    3444: 
1.29      crook    3445: Forth is an unusual language. It provides an interactive development
                   3446: environment which includes both an interpreter and compiler. Forth
                   3447: programming style encourages you to break a problem down into many
                   3448: @cindex factoring
                   3449: small fragments (@dfn{factoring}), and then to develop and test each
                   3450: fragment interactively. Forth advocates assert that breaking the
                   3451: edit-compile-test cycle used by conventional programming languages can
                   3452: lead to great productivity improvements.
1.21      crook    3453: 
1.29      crook    3454: @menu
                   3455: * Introducing the Text Interpreter::
                   3456: * Stacks and Postfix notation::
                   3457: * Your first definition::
                   3458: * How does that work?::
                   3459: * Forth is written in Forth::
                   3460: * Review - elements of a Forth system::
                   3461: * Where to go next::
                   3462: * Exercises::
                   3463: @end menu
1.21      crook    3464: 
1.29      crook    3465: @comment ----------------------------------------------
                   3466: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3467: @section Introducing the Text Interpreter
                   3468: @cindex text interpreter
                   3469: @cindex outer interpreter
1.21      crook    3470: 
1.30      anton    3471: @c IMO this is too detailed and the pace is too slow for
                   3472: @c an introduction.  If you know German, take a look at
                   3473: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3474: @c to see how I do it - anton 
                   3475: 
1.44      crook    3476: @c nac-> Where I have accepted your comments 100% and modified the text
                   3477: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3478: @c response like this to attempt to rationalise what I have done. Of
                   3479: @c course, this is a very clumsy mechanism for something that would be
                   3480: @c done far more efficiently over a beer. Please delete any dialogue
                   3481: @c you consider closed.
                   3482: 
1.29      crook    3483: When you invoke the Forth image, you will see a startup banner printed
                   3484: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3485: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3486: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3487: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3488: about the text interpreter as you read through this chapter, for more
                   3489: detail @pxref{The Text Interpreter}).
1.21      crook    3490: 
1.29      crook    3491: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3492: input. Type a number and press the @key{RET} key:
1.21      crook    3493: 
1.26      crook    3494: @example
1.30      anton    3495: @kbd{45@key{RET}}  ok
1.26      crook    3496: @end example
1.21      crook    3497: 
1.29      crook    3498: Rather than give you a prompt to invite you to input something, the text
                   3499: interpreter prints a status message @i{after} it has processed a line
                   3500: of input. The status message in this case (``@code{ ok}'' followed by
                   3501: carriage-return) indicates that the text interpreter was able to process
                   3502: all of your input successfully. Now type something illegal:
                   3503: 
                   3504: @example
1.30      anton    3505: @kbd{qwer341@key{RET}}
1.29      crook    3506: :1: Undefined word
                   3507: qwer341
                   3508: ^^^^^^^
                   3509: $400D2BA8 Bounce
                   3510: $400DBDA8 no.extensions
                   3511: @end example
1.23      crook    3512: 
1.29      crook    3513: The exact text, other than the ``Undefined word'' may differ slightly on
                   3514: your system, but the effect is the same; when the text interpreter
                   3515: detects an error, it discards any remaining text on a line, resets
1.49      anton    3516: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
                   3517: messages}.
1.23      crook    3518: 
1.29      crook    3519: The text interpreter waits for you to press carriage-return, and then
                   3520: processes your input line. Starting at the beginning of the line, it
                   3521: breaks the line into groups of characters separated by spaces. For each
                   3522: group of characters in turn, it makes two attempts to do something:
1.23      crook    3523: 
1.29      crook    3524: @itemize @bullet
                   3525: @item
1.44      crook    3526: @cindex name dictionary
1.29      crook    3527: It tries to treat it as a command. It does this by searching a @dfn{name
                   3528: dictionary}. If the group of characters matches an entry in the name
                   3529: dictionary, the name dictionary provides the text interpreter with
                   3530: information that allows the text interpreter perform some actions. In
                   3531: Forth jargon, we say that the group
                   3532: @cindex word
                   3533: @cindex definition
                   3534: @cindex execution token
                   3535: @cindex xt
                   3536: of characters names a @dfn{word}, that the dictionary search returns an
                   3537: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3538: word, and that the text interpreter executes the xt. Often, the terms
                   3539: @dfn{word} and @dfn{definition} are used interchangeably.
                   3540: @item
                   3541: If the text interpreter fails to find a match in the name dictionary, it
                   3542: tries to treat the group of characters as a number in the current number
                   3543: base (when you start up Forth, the current number base is base 10). If
                   3544: the group of characters legitimately represents a number, the text
                   3545: interpreter pushes the number onto a stack (we'll learn more about that
                   3546: in the next section).
                   3547: @end itemize
1.23      crook    3548: 
1.29      crook    3549: If the text interpreter is unable to do either of these things with any
                   3550: group of characters, it discards the group of characters and the rest of
                   3551: the line, then prints an error message. If the text interpreter reaches
                   3552: the end of the line without error, it prints the status message ``@code{ ok}''
                   3553: followed by carriage-return.
1.21      crook    3554: 
1.29      crook    3555: This is the simplest command we can give to the text interpreter:
1.23      crook    3556: 
                   3557: @example
1.30      anton    3558: @key{RET}  ok
1.23      crook    3559: @end example
1.21      crook    3560: 
1.29      crook    3561: The text interpreter did everything we asked it to do (nothing) without
                   3562: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3563: command:
1.21      crook    3564: 
1.23      crook    3565: @example
1.30      anton    3566: @kbd{12 dup fred dup@key{RET}}
1.29      crook    3567: :1: Undefined word
                   3568: 12 dup fred dup
                   3569:        ^^^^
                   3570: $400D2BA8 Bounce
                   3571: $400DBDA8 no.extensions
1.23      crook    3572: @end example
1.21      crook    3573: 
1.29      crook    3574: When you press the carriage-return key, the text interpreter starts to
                   3575: work its way along the line:
1.21      crook    3576: 
1.29      crook    3577: @itemize @bullet
                   3578: @item
                   3579: When it gets to the space after the @code{2}, it takes the group of
                   3580: characters @code{12} and looks them up in the name
                   3581: dictionary@footnote{We can't tell if it found them or not, but assume
                   3582: for now that it did not}. There is no match for this group of characters
                   3583: in the name dictionary, so it tries to treat them as a number. It is
                   3584: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3585: (whatever that means).
                   3586: @item
                   3587: The text interpreter resumes scanning the line and gets the next group
                   3588: of characters, @code{dup}. It looks it up in the name dictionary and
                   3589: (you'll have to take my word for this) finds it, and executes the word
                   3590: @code{dup} (whatever that means).
                   3591: @item
                   3592: Once again, the text interpreter resumes scanning the line and gets the
                   3593: group of characters @code{fred}. It looks them up in the name
                   3594: dictionary, but can't find them. It tries to treat them as a number, but
                   3595: they don't represent any legal number.
                   3596: @end itemize
1.21      crook    3597: 
1.29      crook    3598: At this point, the text interpreter gives up and prints an error
                   3599: message. The error message shows exactly how far the text interpreter
                   3600: got in processing the line. In particular, it shows that the text
                   3601: interpreter made no attempt to do anything with the final character
                   3602: group, @code{dup}, even though we have good reason to believe that the
                   3603: text interpreter would have no problem looking that word up and
                   3604: executing it a second time.
1.21      crook    3605: 
                   3606: 
1.29      crook    3607: @comment ----------------------------------------------
                   3608: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3609: @section Stacks, postfix notation and parameter passing
                   3610: @cindex text interpreter
                   3611: @cindex outer interpreter
1.21      crook    3612: 
1.29      crook    3613: In procedural programming languages (like C and Pascal), the
                   3614: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3615: functions or procedures are called with @dfn{explicit parameters}. For
                   3616: example, in C we might write:
1.21      crook    3617: 
1.23      crook    3618: @example
1.29      crook    3619: total = total + new_volume(length,height,depth);
1.23      crook    3620: @end example
1.21      crook    3621: 
1.23      crook    3622: @noindent
1.29      crook    3623: where new_volume is a function-call to another piece of code, and total,
                   3624: length, height and depth are all variables. length, height and depth are
                   3625: parameters to the function-call.
1.21      crook    3626: 
1.29      crook    3627: In Forth, the equivalent of the function or procedure is the
                   3628: @dfn{definition} and parameters are implicitly passed between
                   3629: definitions using a shared stack that is visible to the
                   3630: programmer. Although Forth does support variables, the existence of the
                   3631: stack means that they are used far less often than in most other
                   3632: programming languages. When the text interpreter encounters a number, it
                   3633: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3634: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3635: used for any operation is implied unambiguously by the operation being
                   3636: performed. The stack used for all integer operations is called the @dfn{data
                   3637: stack} and, since this is the stack used most commonly, references to
                   3638: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3639: 
1.29      crook    3640: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3641: 
1.23      crook    3642: @example
1.30      anton    3643: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3644: @end example
1.21      crook    3645: 
1.29      crook    3646: Then this instructs the text interpreter to placed three numbers on the
                   3647: (data) stack. An analogy for the behaviour of the stack is to take a
                   3648: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3649: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3650: you take a card off the pile then, unless you're prepared to fiddle a
                   3651: bit, the card that you take off will be the 3 (``first-out''). The
                   3652: number that will be first-out of the stack is called the @dfn{top of
                   3653: stack}, which
                   3654: @cindex TOS definition
                   3655: is often abbreviated to @dfn{TOS}.
1.21      crook    3656: 
1.29      crook    3657: To understand how parameters are passed in Forth, consider the
                   3658: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3659: be surprised to learn that this definition performs addition. More
                   3660: precisely, it adds two number together and produces a result. Where does
                   3661: it get the two numbers from? It takes the top two numbers off the
                   3662: stack. Where does it place the result? On the stack. You can act-out the
                   3663: behaviour of @code{+} with your playing cards like this:
1.21      crook    3664: 
                   3665: @itemize @bullet
                   3666: @item
1.29      crook    3667: Pick up two cards from the stack on the table
1.21      crook    3668: @item
1.29      crook    3669: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3670: numbers''
1.21      crook    3671: @item
1.29      crook    3672: Decide that the answer is 5
1.21      crook    3673: @item
1.29      crook    3674: Shuffle the two cards back into the pack and find a 5
1.21      crook    3675: @item
1.29      crook    3676: Put a 5 on the remaining ace that's on the table.
1.21      crook    3677: @end itemize
                   3678: 
1.29      crook    3679: If you don't have a pack of cards handy but you do have Forth running,
                   3680: you can use the definition @code{.s} to show the current state of the stack,
                   3681: without affecting the stack. Type:
1.21      crook    3682: 
                   3683: @example
1.30      anton    3684: @kbd{clearstack 1 2 3@key{RET}} ok
                   3685: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3686: @end example
                   3687: 
1.29      crook    3688: The text interpreter looks up the word @code{clearstack} and executes
                   3689: it; it tidies up the stack and removes any entries that may have been
                   3690: left on it by earlier examples. The text interpreter pushes each of the
                   3691: three numbers in turn onto the stack. Finally, the text interpreter
                   3692: looks up the word @code{.s} and executes it. The effect of executing
                   3693: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3694: followed by a list of all the items on the stack; the item on the far
                   3695: right-hand side is the TOS.
1.21      crook    3696: 
1.29      crook    3697: You can now type:
1.21      crook    3698: 
1.29      crook    3699: @example
1.30      anton    3700: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3701: @end example
1.21      crook    3702: 
1.29      crook    3703: @noindent
                   3704: which is correct; there are now 2 items on the stack and the result of
                   3705: the addition is 5.
1.23      crook    3706: 
1.29      crook    3707: If you're playing with cards, try doing a second addition: pick up the
                   3708: two cards, work out that their sum is 6, shuffle them into the pack,
                   3709: look for a 6 and place that on the table. You now have just one item on
                   3710: the stack. What happens if you try to do a third addition? Pick up the
                   3711: first card, pick up the second card -- ah! There is no second card. This
                   3712: is called a @dfn{stack underflow} and consitutes an error. If you try to
                   3713: do the same thing with Forth it will report an error (probably a Stack
                   3714: Underflow or an Invalid Memory Address error).
1.23      crook    3715: 
1.29      crook    3716: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3717: which simply accepts that there is a finite amount of storage space
                   3718: reserved for the stack. To stretch the playing card analogy, if you had
                   3719: enough packs of cards and you piled the cards up on the table, you would
                   3720: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3721: allows you to set the maximum size of the stacks. In general, the only
                   3722: time that you will get a stack overflow is because a definition has a
                   3723: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3724: 
1.29      crook    3725: There's one final use for the playing card analogy. If you model your
                   3726: stack using a pack of playing cards, the maximum number of items on
                   3727: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3728: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3729: possible numbers are positive integer numbers 1 through 13; you can't
                   3730: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3731: think about some of the cards, you can accommodate different
                   3732: numbers. For example, you could think of the Jack as representing 0,
                   3733: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3734: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3735: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3736: 
1.29      crook    3737: In that analogy, the limit was the amount of information that a single
                   3738: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3739: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3740: implementation dependent and affects the maximum value that a stack
                   3741: entry can hold. A Standard Forth provides a cell size of at least
                   3742: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3743: 
1.29      crook    3744: Forth does not do any type checking for you, so you are free to
                   3745: manipulate and combine stack items in any way you wish. A convenient way
                   3746: of treating stack items is as 2's complement signed integers, and that
                   3747: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3748: 
1.29      crook    3749: @example
1.30      anton    3750: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3751: @end example
1.21      crook    3752: 
1.29      crook    3753: If you use numbers and definitions like @code{+} in order to turn Forth
                   3754: into a great big pocket calculator, you will realise that it's rather
                   3755: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3756: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3757: result). The terminology used to describe this difference is to say that
                   3758: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3759: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3760: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3761: 
1.29      crook    3762: Whilst postfix notation might look confusing to begin with, it has
                   3763: several important advantages:
1.21      crook    3764: 
1.23      crook    3765: @itemize @bullet
                   3766: @item
1.29      crook    3767: it is unambiguous
1.23      crook    3768: @item
1.29      crook    3769: it is more concise
1.23      crook    3770: @item
1.29      crook    3771: it fits naturally with a stack-based system
1.23      crook    3772: @end itemize
1.21      crook    3773: 
1.29      crook    3774: To examine these claims in more detail, consider these sums:
1.21      crook    3775: 
1.29      crook    3776: @example
                   3777: 6 + 5 * 4 =
                   3778: 4 * 5 + 6 =
                   3779: @end example
1.21      crook    3780: 
1.29      crook    3781: If you're just learning maths or your maths is very rusty, you will
                   3782: probably come up with the answer 44 for the first and 26 for the
                   3783: second. If you are a bit of a whizz at maths you will remember the
                   3784: @i{convention} that multiplication takes precendence over addition, and
                   3785: you'd come up with the answer 26 both times. To explain the answer 26
                   3786: to someone who got the answer 44, you'd probably rewrite the first sum
                   3787: like this:
1.21      crook    3788: 
1.29      crook    3789: @example
                   3790: 6 + (5 * 4) =
                   3791: @end example
1.21      crook    3792: 
1.29      crook    3793: If what you really wanted was to perform the addition before the
                   3794: multiplication, you would have to use parentheses to force it.
1.21      crook    3795: 
1.29      crook    3796: If you did the first two sums on a pocket calculator you would probably
                   3797: get the right answers, unless you were very cautious and entered them using
                   3798: these keystroke sequences:
1.21      crook    3799: 
1.29      crook    3800: 6 + 5 = * 4 =
                   3801: 4 * 5 = + 6 =
1.21      crook    3802: 
1.29      crook    3803: Postfix notation is unambiguous because the order that the operators
                   3804: are applied is always explicit; that also means that parentheses are
                   3805: never required. The operators are @i{active} (the act of quoting the
                   3806: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3807: 
1.29      crook    3808: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3809: equivalent ways:
1.26      crook    3810: 
                   3811: @example
1.29      crook    3812: 6 5 4 * +      or:
                   3813: 5 4 * 6 +
1.26      crook    3814: @end example
1.23      crook    3815: 
1.29      crook    3816: An important thing that you should notice about this notation is that
                   3817: the @i{order} of the numbers does not change; if you want to subtract
                   3818: 2 from 10 you type @code{10 2 -}.
1.1       anton    3819: 
1.29      crook    3820: The reason that Forth uses postfix notation is very simple to explain: it
                   3821: makes the implementation extremely simple, and it follows naturally from
                   3822: using the stack as a mechanism for passing parameters. Another way of
                   3823: thinking about this is to realise that all Forth definitions are
                   3824: @i{active}; they execute as they are encountered by the text
                   3825: interpreter. The result of this is that the syntax of Forth is trivially
                   3826: simple.
1.1       anton    3827: 
                   3828: 
                   3829: 
1.29      crook    3830: @comment ----------------------------------------------
                   3831: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3832: @section Your first Forth definition
                   3833: @cindex first definition
1.1       anton    3834: 
1.29      crook    3835: Until now, the examples we've seen have been trivial; we've just been
                   3836: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3837: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3838: again@footnote{That's not quite true. If you press the up-arrow key on
                   3839: your keyboard you should be able to scroll back to any earlier command,
                   3840: edit it and re-enter it.} In this section we'll see how to add new
                   3841: words to Forth's vocabulary.
1.1       anton    3842: 
1.29      crook    3843: The easiest way to create a new word is to use a @dfn{colon
                   3844: definition}. We'll define a few and try them out before worrying too
                   3845: much about how they work. Try typing in these examples; be careful to
                   3846: copy the spaces accurately:
1.1       anton    3847: 
1.29      crook    3848: @example
                   3849: : add-two 2 + . ;
                   3850: : greet ." Hello and welcome" ;
                   3851: : demo 5 add-two ;
                   3852: @end example
1.1       anton    3853: 
1.29      crook    3854: @noindent
                   3855: Now try them out:
1.1       anton    3856: 
1.29      crook    3857: @example
1.30      anton    3858: @kbd{greet@key{RET}} Hello and welcome  ok
                   3859: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3860: @kbd{4 add-two@key{RET}} 6  ok
                   3861: @kbd{demo@key{RET}} 7  ok
                   3862: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3863: @end example
1.1       anton    3864: 
1.29      crook    3865: The first new thing that we've introduced here is the pair of words
                   3866: @code{:} and @code{;}. These are used to start and terminate a new
                   3867: definition, respectively. The first word after the @code{:} is the name
                   3868: for the new definition.
1.1       anton    3869: 
1.29      crook    3870: As you can see from the examples, a definition is built up of words that
                   3871: have already been defined; Forth makes no distinction between
                   3872: definitions that existed when you started the system up, and those that
                   3873: you define yourself.
1.1       anton    3874: 
1.29      crook    3875: The examples also introduce the words @code{.} (dot), @code{."}
                   3876: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3877: the stack and displays it. It's like @code{.s} except that it only
                   3878: displays the top item of the stack and it is destructive; after it has
                   3879: executed, the number is no longer on the stack. There is always one
                   3880: space printed after the number, and no spaces before it. Dot-quote
                   3881: defines a string (a sequence of characters) that will be printed when
                   3882: the word is executed. The string can contain any printable characters
                   3883: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3884: word but it acts as a delimiter (the way that delimiters work is
                   3885: described in the next section). Finally, @code{dup} duplicates the value
                   3886: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3887: 
1.29      crook    3888: We already know that the text interpreter searches through the
                   3889: dictionary to locate names. If you've followed the examples earlier, you
                   3890: will already have a definition called @code{add-two}. Lets try modifying
                   3891: it by typing in a new definition:
1.1       anton    3892: 
1.29      crook    3893: @example
1.30      anton    3894: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3895: @end example
1.5       anton    3896: 
1.29      crook    3897: Forth recognised that we were defining a word that already exists, and
                   3898: printed a message to warn us of that fact. Let's try out the new
                   3899: definition:
1.5       anton    3900: 
1.29      crook    3901: @example
1.30      anton    3902: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3903: @end example
1.1       anton    3904: 
1.29      crook    3905: @noindent
                   3906: All that we've actually done here, though, is to create a new
                   3907: definition, with a particular name. The fact that there was already a
                   3908: definition with the same name did not make any difference to the way
                   3909: that the new definition was created (except that Forth printed a warning
                   3910: message). The old definition of add-two still exists (try @code{demo}
                   3911: again to see that this is true). Any new definition will use the new
                   3912: definition of @code{add-two}, but old definitions continue to use the
                   3913: version that already existed at the time that they were @code{compiled}.
1.1       anton    3914: 
1.29      crook    3915: Before you go on to the next section, try defining and redefining some
                   3916: words of your own.
1.1       anton    3917: 
1.29      crook    3918: @comment ----------------------------------------------
                   3919: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3920: @section How does that work?
                   3921: @cindex parsing words
1.1       anton    3922: 
1.30      anton    3923: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3924: 
                   3925: @c Is it a good idea to talk about the interpretation semantics of a
                   3926: @c number? We don't have an xt to go along with it. - anton
                   3927: 
                   3928: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3929: @c be better to keep them (or add run-time semantics), to make it easier to
                   3930: @c explain what compilation semantics usually does. - anton
                   3931: 
1.44      crook    3932: @c nac-> I removed the term ``default compilation sematics'' from the
                   3933: @c introductory chapter. Removing ``execution semantics'' was making
                   3934: @c everything simpler to explain, then I think the use of this term made
                   3935: @c everything more complex again. I replaced it with ``default
                   3936: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3937: @c ``a definition that has neither the immediate nor the compile-only
                   3938: @c flag set''. I reworded big chunks of the ``how does that work''
                   3939: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3940: @c what you think -- I know I have not addressed your primary concern
                   3941: @c that it is too heavy-going for an introduction. From what I understood
                   3942: @c of your course notes it looks as though they might be a good framework. 
                   3943: @c Things that I've tried to capture here are some things that came as a
                   3944: @c great revelation here when I first understood them. Also, I like the
                   3945: @c fact that a very simple code example shows up almost all of the issues
                   3946: @c that you need to understand to see how Forth works. That's unique and
                   3947: @c worthwhile to emphasise.
                   3948: 
1.29      crook    3949: Now we're going to take another look at the definition of @code{add-two}
                   3950: from the previous section. From our knowledge of the way that the text
                   3951: interpreter works, we would have expected this result when we tried to
                   3952: define @code{add-two}:
1.21      crook    3953: 
1.29      crook    3954: @example
1.44      crook    3955: @kbd{: add-two 2 + . ;@key{RET}}
1.29      crook    3956:   ^^^^^^^
                   3957: Error: Undefined word
                   3958: @end example
1.28      crook    3959: 
1.29      crook    3960: The reason that this didn't happen is bound up in the way that @code{:}
                   3961: works. The word @code{:} does two special things. The first special
                   3962: thing that it does prevents the text interpreter from ever seeing the
                   3963: characters @code{add-two}. The text interpreter uses a variable called
                   3964: @cindex modifying >IN
1.44      crook    3965: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    3966: input line. When it encounters the word @code{:} it behaves in exactly
                   3967: the same way as it does for any other word; it looks it up in the name
                   3968: dictionary, finds its xt and executes it. When @code{:} executes, it
                   3969: looks at the input buffer, finds the word @code{add-two} and advances the
                   3970: value of @code{>IN} to point past it. It then does some other stuff
                   3971: associated with creating the new definition (including creating an entry
                   3972: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   3973: completes, control returns to the text interpreter, which is oblivious
                   3974: to the fact that it has been tricked into ignoring part of the input
                   3975: line.
1.21      crook    3976: 
1.29      crook    3977: @cindex parsing words
                   3978: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   3979: prevent the text interpreter from acting on the whole of the input line
                   3980: -- are called @dfn{parsing words}.
1.21      crook    3981: 
1.29      crook    3982: @cindex @code{state} - effect on the text interpreter
                   3983: @cindex text interpreter - effect of state
                   3984: The second special thing that @code{:} does is change the value of a
                   3985: variable called @code{state}, which affects the way that the text
                   3986: interpreter behaves. When Gforth starts up, @code{state} has the value
                   3987: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   3988: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    3989: the text interpreter is said to be @dfn{compiling}.
                   3990: 
                   3991: In this example, the text interpreter is compiling when it processes the
                   3992: string ``@code{2 + . ;}''. It still breaks the string down into
                   3993: character sequences in the same way. However, instead of pushing the
                   3994: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   3995: into the definition of @code{add-two} that will make the number @code{2} get
                   3996: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   3997: the behaviours of @code{+} and @code{.} are also compiled into the
                   3998: definition.
                   3999: 
                   4000: One category of words don't get compiled. These so-called @dfn{immediate
                   4001: words} get executed (performed @i{now}) regardless of whether the text
                   4002: interpreter is interpreting or compiling. The word @code{;} is an
                   4003: immediate word. Rather than being compiled into the definition, it
                   4004: executes. Its effect is to terminate the current definition, which
                   4005: includes changing the value of @code{state} back to 0.
                   4006: 
                   4007: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   4008: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   4009: definition.
1.28      crook    4010: 
1.30      anton    4011: In Forth, every word or number can be described in terms of two
1.29      crook    4012: properties:
1.28      crook    4013: 
                   4014: @itemize @bullet
                   4015: @item
1.29      crook    4016: @cindex interpretation semantics
1.44      crook    4017: Its @dfn{interpretation semantics} describe how it will behave when the
                   4018: text interpreter encounters it in @dfn{interpret} state. The
                   4019: interpretation semantics of a word are represented by an @dfn{execution
                   4020: token}.
1.28      crook    4021: @item
1.29      crook    4022: @cindex compilation semantics
1.44      crook    4023: Its @dfn{compilation semantics} describe how it will behave when the
                   4024: text interpreter encounters it in @dfn{compile} state. The compilation
                   4025: semantics of a word are represented in an implementation-dependent way;
                   4026: Gforth uses a @dfn{compilation token}.
1.29      crook    4027: @end itemize
                   4028: 
                   4029: @noindent
                   4030: Numbers are always treated in a fixed way:
                   4031: 
                   4032: @itemize @bullet
1.28      crook    4033: @item
1.44      crook    4034: When the number is @dfn{interpreted}, its behaviour is to push the
                   4035: number onto the stack.
1.28      crook    4036: @item
1.30      anton    4037: When the number is @dfn{compiled}, a piece of code is appended to the
                   4038: current definition that pushes the number when it runs. (In other words,
                   4039: the compilation semantics of a number are to postpone its interpretation
                   4040: semantics until the run-time of the definition that it is being compiled
                   4041: into.)
1.29      crook    4042: @end itemize
                   4043: 
1.44      crook    4044: Words don't behave in such a regular way, but most have @i{default
                   4045: semantics} which means that they behave like this:
1.29      crook    4046: 
                   4047: @itemize @bullet
1.28      crook    4048: @item
1.30      anton    4049: The @dfn{interpretation semantics} of the word are to do something useful.
                   4050: @item
1.29      crook    4051: The @dfn{compilation semantics} of the word are to append its
1.30      anton    4052: @dfn{interpretation semantics} to the current definition (so that its
                   4053: run-time behaviour is to do something useful).
1.28      crook    4054: @end itemize
                   4055: 
1.30      anton    4056: @cindex immediate words
1.44      crook    4057: The actual behaviour of any particular word can be controlled by using
                   4058: the words @code{immediate} and @code{compile-only} when the word is
                   4059: defined. These words set flags in the name dictionary entry of the most
                   4060: recently defined word, and these flags are retrieved by the text
                   4061: interpreter when it finds the word in the name dictionary.
                   4062: 
                   4063: A word that is marked as @dfn{immediate} has compilation semantics that
                   4064: are identical to its interpretation semantics. In other words, it
                   4065: behaves like this:
1.29      crook    4066: 
                   4067: @itemize @bullet
                   4068: @item
1.30      anton    4069: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    4070: @item
1.30      anton    4071: The @dfn{compilation semantics} of the word are to do something useful
                   4072: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    4073: @end itemize
1.28      crook    4074: 
1.44      crook    4075: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   4076: performing the interpretation semantics of the word directly; an attempt
                   4077: to do so will generate an error. It is never necessary to use
                   4078: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   4079: provided by many implementations) but it is good etiquette to apply it
                   4080: to a word that will not behave correctly (and might have unexpected
                   4081: side-effects) in interpret state. For example, it is only legal to use
                   4082: the conditional word @code{IF} within a definition. If you forget this
                   4083: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   4084: @code{compile-only} allows the text interpreter to generate a helpful
                   4085: error message rather than subjecting you to the consequences of your
                   4086: folly.
                   4087: 
1.29      crook    4088: This example shows the difference between an immediate and a
                   4089: non-immediate word:
1.28      crook    4090: 
1.29      crook    4091: @example
                   4092: : show-state state @@ . ;
                   4093: : show-state-now show-state ; immediate
                   4094: : word1 show-state ;
                   4095: : word2 show-state-now ;
1.28      crook    4096: @end example
1.23      crook    4097: 
1.29      crook    4098: The word @code{immediate} after the definition of @code{show-state-now}
                   4099: makes that word an immediate word. These definitions introduce a new
                   4100: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   4101: variable, and leaves it on the stack. Therefore, the behaviour of
                   4102: @code{show-state} is to print a number that represents the current value
                   4103: of @code{state}.
1.28      crook    4104: 
1.29      crook    4105: When you execute @code{word1}, it prints the number 0, indicating that
                   4106: the system is interpreting. When the text interpreter compiled the
                   4107: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    4108: compilation semantics are to append its interpretation semantics to the
1.29      crook    4109: current definition. When you execute @code{word1}, it performs the
1.30      anton    4110: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    4111: (and therefore @code{show-state}) are executed, the system is
                   4112: interpreting.
1.28      crook    4113: 
1.30      anton    4114: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    4115: you should have seen the number -1 printed, followed by ``@code{
                   4116: ok}''. When the text interpreter compiled the definition of
                   4117: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    4118: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4119: semantics. It is executed straight away (even before the text
                   4120: interpreter has moved on to process another group of characters; the
                   4121: @code{;} in this example). The effect of executing it are to display the
                   4122: value of @code{state} @i{at the time that the definition of}
                   4123: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4124: system is compiling at this time. If you execute @code{word2} it does
                   4125: nothing at all.
1.28      crook    4126: 
1.29      crook    4127: @cindex @code{."}, how it works
                   4128: Before leaving the subject of immediate words, consider the behaviour of
                   4129: @code{."} in the definition of @code{greet}, in the previous
                   4130: section. This word is both a parsing word and an immediate word. Notice
                   4131: that there is a space between @code{."} and the start of the text
                   4132: @code{Hello and welcome}, but that there is no space between the last
                   4133: letter of @code{welcome} and the @code{"} character. The reason for this
                   4134: is that @code{."} is a Forth word; it must have a space after it so that
                   4135: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4136: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4137: is displayed, there is neither a space before the @code{H} nor after the
                   4138: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4139: that @code{greet} is defined. When it executes, its behaviour is to
                   4140: search forward in the input line looking for the delimiter. When it
                   4141: finds the delimiter, it updates @code{>IN} to point past the
                   4142: delimiter. It also compiles some magic code into the definition of
                   4143: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4144: compiles the string @code{Hello and welcome} into memory so that it is
                   4145: available to be printed later. When the text interpreter gains control,
                   4146: the next word it finds in the input stream is @code{;} and so it
                   4147: terminates the definition of @code{greet}.
1.28      crook    4148: 
                   4149: 
                   4150: @comment ----------------------------------------------
1.29      crook    4151: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4152: @section Forth is written in Forth
                   4153: @cindex structure of Forth programs
                   4154: 
                   4155: When you start up a Forth compiler, a large number of definitions
                   4156: already exist. In Forth, you develop a new application using bottom-up
                   4157: programming techniques to create new definitions that are defined in
                   4158: terms of existing definitions. As you create each definition you can
                   4159: test and debug it interactively.
                   4160: 
                   4161: If you have tried out the examples in this section, you will probably
                   4162: have typed them in by hand; when you leave Gforth, your definitions will
                   4163: be lost. You can avoid this by using a text editor to enter Forth source
                   4164: code into a file, and then loading code from the file using
1.49      anton    4165: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    4166: processed by the text interpreter, just as though you had typed it in by
                   4167: hand@footnote{Actually, there are some subtle differences -- see
                   4168: @ref{The Text Interpreter}.}.
                   4169: 
                   4170: Gforth also supports the traditional Forth alternative to using text
1.49      anton    4171: files for program entry (@pxref{Blocks}).
1.28      crook    4172: 
1.29      crook    4173: In common with many, if not most, Forth compilers, most of Gforth is
                   4174: actually written in Forth. All of the @file{.fs} files in the
                   4175: installation directory@footnote{For example,
1.30      anton    4176: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4177: study to see examples of Forth programming.
1.28      crook    4178: 
1.29      crook    4179: Gforth maintains a history file that records every line that you type to
                   4180: the text interpreter. This file is preserved between sessions, and is
                   4181: used to provide a command-line recall facility. If you enter long
                   4182: definitions by hand, you can use a text editor to paste them out of the
                   4183: history file into a Forth source file for reuse at a later time
1.49      anton    4184: (for more information @pxref{Command-line editing}).
1.28      crook    4185: 
                   4186: 
                   4187: @comment ----------------------------------------------
1.29      crook    4188: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4189: @section Review - elements of a Forth system
                   4190: @cindex elements of a Forth system
1.28      crook    4191: 
1.29      crook    4192: To summarise this chapter:
1.28      crook    4193: 
                   4194: @itemize @bullet
                   4195: @item
1.29      crook    4196: Forth programs use @dfn{factoring} to break a problem down into small
                   4197: fragments called @dfn{words} or @dfn{definitions}.
                   4198: @item
                   4199: Forth program development is an interactive process.
                   4200: @item
                   4201: The main command loop that accepts input, and controls both
                   4202: interpretation and compilation, is called the @dfn{text interpreter}
                   4203: (also known as the @dfn{outer interpreter}).
                   4204: @item
                   4205: Forth has a very simple syntax, consisting of words and numbers
                   4206: separated by spaces or carriage-return characters. Any additional syntax
                   4207: is imposed by @dfn{parsing words}.
                   4208: @item
                   4209: Forth uses a stack to pass parameters between words. As a result, it
                   4210: uses postfix notation.
                   4211: @item
                   4212: To use a word that has previously been defined, the text interpreter
                   4213: searches for the word in the @dfn{name dictionary}.
                   4214: @item
1.30      anton    4215: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4216: @item
1.29      crook    4217: The text interpreter uses the value of @code{state} to select between
                   4218: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4219: semantics} of a word that it encounters.
1.28      crook    4220: @item
1.30      anton    4221: The relationship between the @dfn{interpretation semantics} and
                   4222: @dfn{compilation semantics} for a word
1.29      crook    4223: depend upon the way in which the word was defined (for example, whether
                   4224: it is an @dfn{immediate} word).
1.28      crook    4225: @item
1.29      crook    4226: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4227: definitions}) or in some other way (usually a lower-level language and
                   4228: as a result often called @dfn{low-level definitions}, @dfn{code
                   4229: definitions} or @dfn{primitives}).
1.28      crook    4230: @item
1.29      crook    4231: Many Forth systems are implemented mainly in Forth.
1.28      crook    4232: @end itemize
                   4233: 
                   4234: 
1.29      crook    4235: @comment ----------------------------------------------
1.48      anton    4236: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4237: @section Where To Go Next
                   4238: @cindex where to go next
1.28      crook    4239: 
1.29      crook    4240: Amazing as it may seem, if you have read (and understood) this far, you
                   4241: know almost all the fundamentals about the inner workings of a Forth
                   4242: system. You certainly know enough to be able to read and understand the
                   4243: rest of this manual and the ANS Forth document, to learn more about the
                   4244: facilities that Forth in general and Gforth in particular provide. Even
                   4245: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4246: However, that's not a good idea just yet... better to try writing some
1.29      crook    4247: programs in Gforth.
1.28      crook    4248: 
1.29      crook    4249: Forth has such a rich vocabulary that it can be hard to know where to
                   4250: start in learning it. This section suggests a few sets of words that are
                   4251: enough to write small but useful programs. Use the word index in this
                   4252: document to learn more about each word, then try it out and try to write
                   4253: small definitions using it. Start by experimenting with these words:
1.28      crook    4254: 
                   4255: @itemize @bullet
                   4256: @item
1.29      crook    4257: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4258: @item
                   4259: Comparison: @code{MIN MAX =}
                   4260: @item
                   4261: Logic: @code{AND OR XOR NOT}
                   4262: @item
                   4263: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4264: @item
1.29      crook    4265: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4266: @item
1.29      crook    4267: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4268: @item
1.29      crook    4269: Defining words: @code{: ; CREATE}
1.28      crook    4270: @item
1.29      crook    4271: Memory allocation words: @code{ALLOT ,}
1.28      crook    4272: @item
1.29      crook    4273: Tools: @code{SEE WORDS .S MARKER}
                   4274: @end itemize
                   4275: 
                   4276: When you have mastered those, go on to:
                   4277: 
                   4278: @itemize @bullet
1.28      crook    4279: @item
1.29      crook    4280: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4281: @item
1.29      crook    4282: Memory access: @code{@@ !}
1.28      crook    4283: @end itemize
1.23      crook    4284: 
1.29      crook    4285: When you have mastered these, there's nothing for it but to read through
                   4286: the whole of this manual and find out what you've missed.
                   4287: 
                   4288: @comment ----------------------------------------------
1.48      anton    4289: @node Exercises,  , Where to go next, Introduction
1.29      crook    4290: @section Exercises
                   4291: @cindex exercises
                   4292: 
                   4293: TODO: provide a set of programming excercises linked into the stuff done
                   4294: already and into other sections of the manual. Provide solutions to all
                   4295: the exercises in a .fs file in the distribution.
                   4296: 
                   4297: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4298: 
                   4299: @c excercises:
                   4300: @c 1. take inches and convert to feet and inches.
                   4301: @c 2. take temperature and convert from fahrenheight to celcius;
                   4302: @c    may need to care about symmetric vs floored??
                   4303: @c 3. take input line and do character substitution
                   4304: @c    to encipher or decipher
                   4305: @c 4. as above but work on a file for in and out
                   4306: @c 5. take input line and convert to pig-latin 
                   4307: @c
                   4308: @c thing of sets of things to exercise then come up with
                   4309: @c problems that need those things.
                   4310: 
                   4311: 
1.26      crook    4312: @c ******************************************************************
1.29      crook    4313: @node Words, Error messages, Introduction, Top
1.1       anton    4314: @chapter Forth Words
1.26      crook    4315: @cindex words
1.1       anton    4316: 
                   4317: @menu
                   4318: * Notation::                    
1.65      anton    4319: * Case insensitivity::          
                   4320: * Comments::                    
                   4321: * Boolean Flags::               
1.1       anton    4322: * Arithmetic::                  
                   4323: * Stack Manipulation::          
1.5       anton    4324: * Memory::                      
1.1       anton    4325: * Control Structures::          
                   4326: * Defining Words::              
1.65      anton    4327: * Interpretation and Compilation Semantics::  
1.47      crook    4328: * Tokens for Words::            
1.65      anton    4329: * The Text Interpreter::        
                   4330: * Word Lists::                  
                   4331: * Environmental Queries::       
1.12      anton    4332: * Files::                       
                   4333: * Blocks::                      
                   4334: * Other I/O::                   
                   4335: * Programming Tools::           
                   4336: * Assembler and Code Words::    
                   4337: * Threading Words::             
1.26      crook    4338: * Locals::                      
                   4339: * Structures::                  
                   4340: * Object-oriented Forth::       
1.65      anton    4341: * Passing Commands to the OS::  
                   4342: * Keeping track of Time::       
                   4343: * Miscellaneous Words::         
1.1       anton    4344: @end menu
                   4345: 
1.65      anton    4346: @node Notation, Case insensitivity, Words, Words
1.1       anton    4347: @section Notation
                   4348: @cindex notation of glossary entries
                   4349: @cindex format of glossary entries
                   4350: @cindex glossary notation format
                   4351: @cindex word glossary entry format
                   4352: 
                   4353: The Forth words are described in this section in the glossary notation
                   4354: that has become a de-facto standard for Forth texts, i.e.,
                   4355: 
                   4356: @format
1.29      crook    4357: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4358: @end format
1.29      crook    4359: @i{Description}
1.1       anton    4360: 
                   4361: @table @var
                   4362: @item word
1.28      crook    4363: The name of the word.
1.1       anton    4364: 
                   4365: @item Stack effect
                   4366: @cindex stack effect
1.29      crook    4367: The stack effect is written in the notation @code{@i{before} --
                   4368: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4369: stack entries before and after the execution of the word. The rest of
                   4370: the stack is not touched by the word. The top of stack is rightmost,
                   4371: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4372: uses a separate floating point stack, but a unified stack
1.29      crook    4373: notation. Also, return stack effects are not shown in @i{stack
                   4374: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4375: the type and/or the function of the item. See below for a discussion of
                   4376: the types.
                   4377: 
                   4378: All words have two stack effects: A compile-time stack effect and a
                   4379: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4380: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4381: this standard behaviour, or the word does other unusual things at
                   4382: compile time, both stack effects are shown; otherwise only the run-time
                   4383: stack effect is shown.
                   4384: 
                   4385: @cindex pronounciation of words
                   4386: @item pronunciation
                   4387: How the word is pronounced.
                   4388: 
                   4389: @cindex wordset
                   4390: @item wordset
1.21      crook    4391: The ANS Forth standard is divided into several word sets. A standard
                   4392: system need not support all of them. Therefore, in theory, the fewer
                   4393: word sets your program uses the more portable it will be. However, we
                   4394: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4395: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4396: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4397: describes words that will work in future releases of Gforth;
                   4398: @code{gforth-internal} words are more volatile. Environmental query
                   4399: strings are also displayed like words; you can recognize them by the
1.21      crook    4400: @code{environment} in the word set field.
1.1       anton    4401: 
                   4402: @item Description
                   4403: A description of the behaviour of the word.
                   4404: @end table
                   4405: 
                   4406: @cindex types of stack items
                   4407: @cindex stack item types
                   4408: The type of a stack item is specified by the character(s) the name
                   4409: starts with:
                   4410: 
                   4411: @table @code
                   4412: @item f
                   4413: @cindex @code{f}, stack item type
                   4414: Boolean flags, i.e. @code{false} or @code{true}.
                   4415: @item c
                   4416: @cindex @code{c}, stack item type
                   4417: Char
                   4418: @item w
                   4419: @cindex @code{w}, stack item type
                   4420: Cell, can contain an integer or an address
                   4421: @item n
                   4422: @cindex @code{n}, stack item type
                   4423: signed integer
                   4424: @item u
                   4425: @cindex @code{u}, stack item type
                   4426: unsigned integer
                   4427: @item d
                   4428: @cindex @code{d}, stack item type
                   4429: double sized signed integer
                   4430: @item ud
                   4431: @cindex @code{ud}, stack item type
                   4432: double sized unsigned integer
                   4433: @item r
                   4434: @cindex @code{r}, stack item type
                   4435: Float (on the FP stack)
1.21      crook    4436: @item a-
1.1       anton    4437: @cindex @code{a_}, stack item type
                   4438: Cell-aligned address
1.21      crook    4439: @item c-
1.1       anton    4440: @cindex @code{c_}, stack item type
                   4441: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4442: @item f-
1.1       anton    4443: @cindex @code{f_}, stack item type
                   4444: Float-aligned address
1.21      crook    4445: @item df-
1.1       anton    4446: @cindex @code{df_}, stack item type
                   4447: Address aligned for IEEE double precision float
1.21      crook    4448: @item sf-
1.1       anton    4449: @cindex @code{sf_}, stack item type
                   4450: Address aligned for IEEE single precision float
                   4451: @item xt
                   4452: @cindex @code{xt}, stack item type
                   4453: Execution token, same size as Cell
                   4454: @item wid
                   4455: @cindex @code{wid}, stack item type
1.21      crook    4456: Word list ID, same size as Cell
1.1       anton    4457: @item f83name
                   4458: @cindex @code{f83name}, stack item type
                   4459: Pointer to a name structure
                   4460: @item "
                   4461: @cindex @code{"}, stack item type
1.12      anton    4462: string in the input stream (not on the stack). The terminating character
                   4463: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4464: quotes.
                   4465: @end table
                   4466: 
1.65      anton    4467: @comment ----------------------------------------------
                   4468: @node Case insensitivity, Comments, Notation, Words
                   4469: @section Case insensitivity
                   4470: @cindex case sensitivity
                   4471: @cindex upper and lower case
                   4472: 
                   4473: Gforth is case-insensitive; you can enter definitions and invoke
                   4474: Standard words using upper, lower or mixed case (however,
                   4475: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   4476: options}).
                   4477: 
                   4478: ANS Forth only @i{requires} implementations to recognise Standard words
                   4479: when they are typed entirely in upper case. Therefore, a Standard
                   4480: program must use upper case for all Standard words. You can use whatever
                   4481: case you like for words that you define, but in a Standard program you
                   4482: have to use the words in the same case that you defined them.
                   4483: 
                   4484: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   4485: wordlists, @pxref{Word Lists}).
                   4486: 
                   4487: Two people have asked how to convert Gforth to be case-sensitive; while
                   4488: we think this is a bad idea, you can change all wordlists into tables
                   4489: like this:
                   4490: 
                   4491: @example
                   4492: ' table-find forth-wordlist wordlist-map @ !
                   4493: @end example
                   4494: 
                   4495: Note that you now have to type the predefined words in the same case
                   4496: that we defined them, which are varying.  You may want to convert them
                   4497: to your favourite case before doing this operation (I won't explain how,
                   4498: because if you are even contemplating doing this, you'd better have
                   4499: enough knowledge of Forth systems to know this already).
                   4500: 
                   4501: @node Comments, Boolean Flags, Case insensitivity, Words
1.21      crook    4502: @section Comments
1.26      crook    4503: @cindex comments
1.21      crook    4504: 
1.29      crook    4505: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4506: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4507: 
1.44      crook    4508: 
1.23      crook    4509: doc-(
1.21      crook    4510: doc-\
1.23      crook    4511: doc-\G
1.21      crook    4512: 
1.44      crook    4513: 
1.21      crook    4514: @node Boolean Flags, Arithmetic, Comments, Words
                   4515: @section Boolean Flags
1.26      crook    4516: @cindex Boolean flags
1.21      crook    4517: 
                   4518: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4519: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4520: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4521: a cell that has @i{any} bit set as @code{true}.
1.21      crook    4522: 
1.44      crook    4523: 
1.21      crook    4524: doc-true
                   4525: doc-false
1.29      crook    4526: doc-on
                   4527: doc-off
1.21      crook    4528: 
1.44      crook    4529: 
1.21      crook    4530: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4531: @section Arithmetic
                   4532: @cindex arithmetic words
                   4533: 
                   4534: @cindex division with potentially negative operands
                   4535: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4536: overflow on addition or multiplication, you may hear about division by
                   4537: zero if you are lucky. The operator is written after the operands, but
                   4538: the operands are still in the original order. I.e., the infix @code{2-1}
                   4539: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4540: operators. If you perform division with potentially negative operands,
                   4541: you do not want to use @code{/} or @code{/mod} with its undefined
                   4542: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4543: former, @pxref{Mixed precision}).
1.26      crook    4544: @comment TODO discuss the different division forms and the std approach
1.1       anton    4545: 
                   4546: @menu
                   4547: * Single precision::            
                   4548: * Bitwise operations::          
1.21      crook    4549: * Double precision::            Double-cell integer arithmetic
                   4550: * Numeric comparison::
1.29      crook    4551: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4552: * Floating Point::              
                   4553: @end menu
                   4554: 
                   4555: @node Single precision, Bitwise operations, Arithmetic, Arithmetic
                   4556: @subsection Single precision
                   4557: @cindex single precision arithmetic words
                   4558: 
1.21      crook    4559: By default, numbers in Forth are single-precision integers that are 1
1.26      crook    4560: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4561: treat them. For the rules used by the text interpreter for recognising
                   4562: single-precision integers see @ref{Number Conversion}.
1.21      crook    4563: 
1.44      crook    4564: 
1.1       anton    4565: doc-+
1.21      crook    4566: doc-1+
1.1       anton    4567: doc--
1.21      crook    4568: doc-1-
1.1       anton    4569: doc-*
                   4570: doc-/
                   4571: doc-mod
                   4572: doc-/mod
                   4573: doc-negate
                   4574: doc-abs
                   4575: doc-min
                   4576: doc-max
1.21      crook    4577: doc-d>s
1.27      crook    4578: doc-floored
1.1       anton    4579: 
1.44      crook    4580: 
1.21      crook    4581: @node Bitwise operations, Double precision, Single precision, Arithmetic
1.1       anton    4582: @subsection Bitwise operations
                   4583: @cindex bitwise operation words
                   4584: 
1.44      crook    4585: 
1.1       anton    4586: doc-and
                   4587: doc-or
                   4588: doc-xor
                   4589: doc-invert
1.21      crook    4590: doc-lshift
                   4591: doc-rshift
1.1       anton    4592: doc-2*
1.21      crook    4593: doc-d2*
1.1       anton    4594: doc-2/
1.21      crook    4595: doc-d2/
                   4596: 
1.44      crook    4597: 
1.21      crook    4598: @node Double precision, Numeric comparison, Bitwise operations, Arithmetic
                   4599: @subsection Double precision
                   4600: @cindex double precision arithmetic words
                   4601: 
1.49      anton    4602: For the rules used by the text interpreter for
                   4603: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4604: 
                   4605: A double precision number is represented by a cell pair, with the most
1.31      anton    4606: significant cell at the TOS. It is trivial to convert an unsigned
1.26      crook    4607: single to an (unsigned) double; simply push a @code{0} onto the
                   4608: TOS. Since numbers are represented by Gforth using 2's complement
                   4609: arithmetic, converting a signed single to a (signed) double requires
1.31      anton    4610: sign-extension across the most significant cell. This can be achieved
1.26      crook    4611: using @code{s>d}. The moral of the story is that you cannot convert a
                   4612: number without knowing whether it represents an unsigned or a
                   4613: signed number.
1.21      crook    4614: 
1.44      crook    4615: 
1.21      crook    4616: doc-s>d
                   4617: doc-d+
                   4618: doc-d-
                   4619: doc-dnegate
                   4620: doc-dabs
                   4621: doc-dmin
                   4622: doc-dmax
                   4623: 
1.44      crook    4624: 
1.21      crook    4625: @node Numeric comparison, Mixed precision, Double precision, Arithmetic
                   4626: @subsection Numeric comparison
                   4627: @cindex numeric comparison words
                   4628: 
1.44      crook    4629: 
1.28      crook    4630: doc-<
                   4631: doc-<=
                   4632: doc-<>
                   4633: doc-=
                   4634: doc->
                   4635: doc->=
                   4636: 
1.21      crook    4637: doc-0<
1.23      crook    4638: doc-0<=
1.21      crook    4639: doc-0<>
                   4640: doc-0=
1.23      crook    4641: doc-0>
                   4642: doc-0>=
1.28      crook    4643: 
                   4644: doc-u<
                   4645: doc-u<=
1.44      crook    4646: @c u<> and u= exist but are the same as <> and =
1.31      anton    4647: @c doc-u<>
                   4648: @c doc-u=
1.28      crook    4649: doc-u>
                   4650: doc-u>=
                   4651: 
                   4652: doc-within
                   4653: 
                   4654: doc-d<
                   4655: doc-d<=
                   4656: doc-d<>
                   4657: doc-d=
                   4658: doc-d>
                   4659: doc-d>=
1.23      crook    4660: 
1.21      crook    4661: doc-d0<
1.23      crook    4662: doc-d0<=
                   4663: doc-d0<>
1.21      crook    4664: doc-d0=
1.23      crook    4665: doc-d0>
                   4666: doc-d0>=
                   4667: 
1.21      crook    4668: doc-du<
1.28      crook    4669: doc-du<=
1.44      crook    4670: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4671: @c doc-du<>
                   4672: @c doc-du=
1.28      crook    4673: doc-du>
                   4674: doc-du>=
1.1       anton    4675: 
1.44      crook    4676: 
1.21      crook    4677: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4678: @subsection Mixed precision
                   4679: @cindex mixed precision arithmetic words
                   4680: 
1.44      crook    4681: 
1.1       anton    4682: doc-m+
                   4683: doc-*/
                   4684: doc-*/mod
                   4685: doc-m*
                   4686: doc-um*
                   4687: doc-m*/
                   4688: doc-um/mod
                   4689: doc-fm/mod
                   4690: doc-sm/rem
                   4691: 
1.44      crook    4692: 
1.21      crook    4693: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4694: @subsection Floating Point
                   4695: @cindex floating point arithmetic words
                   4696: 
1.49      anton    4697: For the rules used by the text interpreter for
                   4698: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4699: 
1.32      anton    4700: Gforth has a separate floating point
1.26      crook    4701: stack, but the documentation uses the unified notation.
1.1       anton    4702: 
                   4703: @cindex floating-point arithmetic, pitfalls
                   4704: Floating point numbers have a number of unpleasant surprises for the
                   4705: unwary (e.g., floating point addition is not associative) and even a few
                   4706: for the wary. You should not use them unless you know what you are doing
                   4707: or you don't care that the results you get are totally bogus. If you
                   4708: want to learn about the problems of floating point numbers (and how to
1.66    ! anton    4709: avoid them), you might start with @cite{David Goldberg,
        !          4710: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
        !          4711: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
        !          4712: Surveys 23(1):5@minus{}48, March 1991}.
1.1       anton    4713: 
1.44      crook    4714: 
1.21      crook    4715: doc-d>f
                   4716: doc-f>d
1.1       anton    4717: doc-f+
                   4718: doc-f-
                   4719: doc-f*
                   4720: doc-f/
                   4721: doc-fnegate
                   4722: doc-fabs
                   4723: doc-fmax
                   4724: doc-fmin
                   4725: doc-floor
                   4726: doc-fround
                   4727: doc-f**
                   4728: doc-fsqrt
                   4729: doc-fexp
                   4730: doc-fexpm1
                   4731: doc-fln
                   4732: doc-flnp1
                   4733: doc-flog
                   4734: doc-falog
1.32      anton    4735: doc-f2*
                   4736: doc-f2/
                   4737: doc-1/f
                   4738: doc-precision
                   4739: doc-set-precision
                   4740: 
                   4741: @cindex angles in trigonometric operations
                   4742: @cindex trigonometric operations
                   4743: Angles in floating point operations are given in radians (a full circle
                   4744: has 2 pi radians).
                   4745: 
1.1       anton    4746: doc-fsin
                   4747: doc-fcos
                   4748: doc-fsincos
                   4749: doc-ftan
                   4750: doc-fasin
                   4751: doc-facos
                   4752: doc-fatan
                   4753: doc-fatan2
                   4754: doc-fsinh
                   4755: doc-fcosh
                   4756: doc-ftanh
                   4757: doc-fasinh
                   4758: doc-facosh
                   4759: doc-fatanh
1.21      crook    4760: doc-pi
1.28      crook    4761: 
1.32      anton    4762: @cindex equality of floats
                   4763: @cindex floating-point comparisons
1.31      anton    4764: One particular problem with floating-point arithmetic is that comparison
                   4765: for equality often fails when you would expect it to succeed.  For this
                   4766: reason approximate equality is often preferred (but you still have to
                   4767: know what you are doing).  The comparison words are:
                   4768: 
                   4769: doc-f~rel
                   4770: doc-f~abs
                   4771: doc-f=
                   4772: doc-f~
                   4773: doc-f<>
                   4774: 
                   4775: doc-f<
                   4776: doc-f<=
                   4777: doc-f>
                   4778: doc-f>=
                   4779: 
1.21      crook    4780: doc-f0<
1.28      crook    4781: doc-f0<=
                   4782: doc-f0<>
1.21      crook    4783: doc-f0=
1.28      crook    4784: doc-f0>
                   4785: doc-f0>=
                   4786: 
1.1       anton    4787: 
                   4788: @node Stack Manipulation, Memory, Arithmetic, Words
                   4789: @section Stack Manipulation
                   4790: @cindex stack manipulation words
                   4791: 
                   4792: @cindex floating-point stack in the standard
1.21      crook    4793: Gforth maintains a number of separate stacks:
                   4794: 
1.29      crook    4795: @cindex data stack
                   4796: @cindex parameter stack
1.21      crook    4797: @itemize @bullet
                   4798: @item
1.29      crook    4799: A data stack (also known as the @dfn{parameter stack}) -- for
                   4800: characters, cells, addresses, and double cells.
1.21      crook    4801: 
1.29      crook    4802: @cindex floating-point stack
1.21      crook    4803: @item
1.44      crook    4804: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4805: 
1.29      crook    4806: @cindex return stack
1.21      crook    4807: @item
1.44      crook    4808: A return stack -- for holding the return addresses of colon
1.32      anton    4809: definitions and other (non-FP) data.
1.21      crook    4810: 
1.29      crook    4811: @cindex locals stack
1.21      crook    4812: @item
1.44      crook    4813: A locals stack -- for holding local variables.
1.21      crook    4814: @end itemize
                   4815: 
1.1       anton    4816: @menu
                   4817: * Data stack::                  
                   4818: * Floating point stack::        
                   4819: * Return stack::                
                   4820: * Locals stack::                
                   4821: * Stack pointer manipulation::  
                   4822: @end menu
                   4823: 
                   4824: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4825: @subsection Data stack
                   4826: @cindex data stack manipulation words
                   4827: @cindex stack manipulations words, data stack
                   4828: 
1.44      crook    4829: 
1.1       anton    4830: doc-drop
                   4831: doc-nip
                   4832: doc-dup
                   4833: doc-over
                   4834: doc-tuck
                   4835: doc-swap
1.21      crook    4836: doc-pick
1.1       anton    4837: doc-rot
                   4838: doc--rot
                   4839: doc-?dup
                   4840: doc-roll
                   4841: doc-2drop
                   4842: doc-2nip
                   4843: doc-2dup
                   4844: doc-2over
                   4845: doc-2tuck
                   4846: doc-2swap
                   4847: doc-2rot
                   4848: 
1.44      crook    4849: 
1.1       anton    4850: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4851: @subsection Floating point stack
                   4852: @cindex floating-point stack manipulation words
                   4853: @cindex stack manipulation words, floating-point stack
                   4854: 
1.32      anton    4855: Whilst every sane Forth has a separate floating-point stack, it is not
                   4856: strictly required; an ANS Forth system could theoretically keep
                   4857: floating-point numbers on the data stack. As an additional difficulty,
                   4858: you don't know how many cells a floating-point number takes. It is
                   4859: reportedly possible to write words in a way that they work also for a
                   4860: unified stack model, but we do not recommend trying it. Instead, just
                   4861: say that your program has an environmental dependency on a separate
                   4862: floating-point stack.
                   4863: 
                   4864: doc-floating-stack
                   4865: 
1.1       anton    4866: doc-fdrop
                   4867: doc-fnip
                   4868: doc-fdup
                   4869: doc-fover
                   4870: doc-ftuck
                   4871: doc-fswap
1.21      crook    4872: doc-fpick
1.1       anton    4873: doc-frot
                   4874: 
1.44      crook    4875: 
1.1       anton    4876: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4877: @subsection Return stack
                   4878: @cindex return stack manipulation words
                   4879: @cindex stack manipulation words, return stack
                   4880: 
1.32      anton    4881: @cindex return stack and locals
                   4882: @cindex locals and return stack
                   4883: A Forth system is allowed to keep local variables on the
                   4884: return stack. This is reasonable, as local variables usually eliminate
                   4885: the need to use the return stack explicitly. So, if you want to produce
                   4886: a standard compliant program and you are using local variables in a
                   4887: word, forget about return stack manipulations in that word (refer to the
                   4888: standard document for the exact rules).
                   4889: 
1.1       anton    4890: doc->r
                   4891: doc-r>
                   4892: doc-r@
                   4893: doc-rdrop
                   4894: doc-2>r
                   4895: doc-2r>
                   4896: doc-2r@
                   4897: doc-2rdrop
                   4898: 
1.44      crook    4899: 
1.1       anton    4900: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4901: @subsection Locals stack
                   4902: 
1.47      crook    4903: Gforth uses an extra locals stack. It is described, along with the
                   4904: reasons for its existence, in @ref{Implementation,Implementation of locals}.
1.21      crook    4905: 
1.1       anton    4906: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4907: @subsection Stack pointer manipulation
                   4908: @cindex stack pointer manipulation words
                   4909: 
1.44      crook    4910: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    4911: doc-sp0
1.1       anton    4912: doc-sp@
                   4913: doc-sp!
1.21      crook    4914: doc-fp0
1.1       anton    4915: doc-fp@
                   4916: doc-fp!
1.21      crook    4917: doc-rp0
1.1       anton    4918: doc-rp@
                   4919: doc-rp!
1.21      crook    4920: doc-lp0
1.1       anton    4921: doc-lp@
                   4922: doc-lp!
                   4923: 
1.44      crook    4924: 
1.1       anton    4925: @node Memory, Control Structures, Stack Manipulation, Words
                   4926: @section Memory
1.26      crook    4927: @cindex memory words
1.1       anton    4928: 
1.32      anton    4929: @menu
                   4930: * Memory model::                
                   4931: * Dictionary allocation::       
                   4932: * Heap Allocation::             
                   4933: * Memory Access::               
                   4934: * Address arithmetic::          
                   4935: * Memory Blocks::               
                   4936: @end menu
                   4937: 
                   4938: @node Memory model, Dictionary allocation, Memory, Memory
                   4939: @subsection ANS Forth and Gforth memory models
                   4940: 
                   4941: @c The ANS Forth description is a mess (e.g., is the heap part of
                   4942: @c the dictionary?), so let's not stick to closely with it.
                   4943: 
                   4944: ANS Forth considers a Forth system as consisting of several memories, of
                   4945: which only @dfn{data space} is managed and accessible with the memory
                   4946: words.  Memory not necessarily in data space includes the stacks, the
                   4947: code (called code space) and the headers (called name space). In Gforth
                   4948: everything is in data space, but the code for the primitives is usually
                   4949: read-only.
                   4950: 
                   4951: Data space is divided into a number of areas: The (data space portion of
                   4952: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   4953: refer to the search data structure embodied in word lists and headers,
                   4954: because it is used for looking up names, just as you would in a
                   4955: conventional dictionary.}, the heap, and a number of system-allocated
                   4956: buffers.
                   4957: 
                   4958: In ANS Forth data space is also divided into contiguous regions.  You
                   4959: can only use address arithmetic within a contiguous region, not between
                   4960: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    4961: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    4962: allocation}).
                   4963: 
                   4964: Gforth provides one big address space, and address arithmetic can be
                   4965: performed between any addresses. However, in the dictionary headers or
                   4966: code are interleaved with data, so almost the only contiguous data space
                   4967: regions there are those described by ANS Forth as contiguous; but you
                   4968: can be sure that the dictionary is allocated towards increasing
                   4969: addresses even between contiguous regions.  The memory order of
                   4970: allocations in the heap is platform-dependent (and possibly different
                   4971: from one run to the next).
                   4972: 
                   4973: @subsubsection ANS Forth dictionary details
                   4974: 
                   4975: This section is just informative, you can skip it if you are in a hurry.
1.27      crook    4976: 
1.29      crook    4977: When you create a colon definition, the text interpreter compiles the
1.32      anton    4978: code for the definition into the code space and compiles the name
                   4979: of the definition into the header space, together with other
1.27      crook    4980: information about the definition (such as its execution token).
                   4981: 
1.44      crook    4982: When you create a variable, the execution of @code{Variable} will
1.32      anton    4983: compile some code, assign one cell in data space, and compile the name
                   4984: of the variable into the header space.
1.27      crook    4985: 
                   4986: @cindex memory regions - relationship between them
                   4987: ANS Forth does not specify the relationship between the three memory
                   4988: regions, and specifies that a Standard program must not access code or
                   4989: data space directly -- it may only access data space directly. In
                   4990: addition, the Standard defines what relationships you may and may not
                   4991: rely on when allocating regions in data space. These constraints are
                   4992: simply a reflection of the many diverse techniques that are used to
                   4993: implement Forth systems; understanding and following the requirements of
                   4994: the Standard allows you to write portable programs -- programs that run
                   4995: in the same way on any of these diverse systems. Another way of looking
                   4996: at this is to say that ANS Forth was designed to permit compliant Forth
                   4997: systems to be implemented in many diverse ways.
                   4998: 
                   4999: @cindex memory regions - how they are assigned
1.29      crook    5000: Here are some examples of ways in which name, code and data spaces
                   5001: might be assigned in different Forth implementations:
1.27      crook    5002: 
                   5003: @itemize @bullet
                   5004: @item
                   5005: For a Forth system that runs from RAM under a general-purpose operating
                   5006: system, it can be convenient to interleave name, code and data spaces in
                   5007: a single contiguous memory region. This organisation can be
                   5008: memory-efficient (for example, because the relationship between the name
1.32      anton    5009: dictionary entry and the associated code space entry can be
1.27      crook    5010: implicit, rather than requiring an explicit memory pointer to reference
1.32      anton    5011: from the header space and the code space). This is the
1.27      crook    5012: organisation used by Gforth, as this example@footnote{The addresses
                   5013: in the example have been truncated to fit it onto the page, and the
                   5014: addresses and data shown will not match the output from your system} shows:
                   5015: @example
                   5016: hex
                   5017: variable fred 123456 fred !
                   5018: variable jim abcd jim !
                   5019: : foo + / - ;
                   5020: ' fred 10 - 50 dump 
                   5021: ..80: 5C 46 0E 40  84 66 72 65 - 64 20 20 20  20 20 20 20  \F.@.fred       
1.50      anton    5022: ..90: D0 9B 04 08  00 00 00 00 - 56 34 12 00  80 46 0E 40  ........V4...F.@@
1.27      crook    5023: ..A0: 83 6A 69 6D  20 20 20 20 - D0 9B 04 08  00 00 00 00  .jim    ........
                   5024: ..B0: CD AB 00 00  9C 46 0E 40 - 83 66 6F 6F  20 20 20 20  .....F.@.foo    
                   5025: ..C0: 80 9B 04 08  00 00 00 00 - E4 2E 05 08  0C 2F 05 08  ............./..
                   5026: @end example
                   5027: 
                   5028: @item
                   5029: For a high-performance system running on a modern RISC processor with a
                   5030: modified Harvard architecture (one that has a unified main memory but
                   5031: separate instruction and data caches), it is desirable to separate
                   5032: processor instructions from processor data. This encourages a high cache
1.32      anton    5033: density and therefore a high cache hit rate. The Forth code space
1.27      crook    5034: is not necessarily made up entirely of processor instructions; its
                   5035: nature is dependent upon the Forth implementation. 
                   5036: 
                   5037: @item
                   5038: A Forth compiler that runs on a segmented 8086 processor could be
                   5039: designed to interleave the name, code and data spaces within a single
                   5040: 64Kbyte segment. A more common implementation choice is to use a
                   5041: separate 64Kbyte segment for each region, which provides more memory
                   5042: overall but provides an address map in which only the data space is
                   5043: accessible.
                   5044: 
                   5045: @item
                   5046: Microprocessors exist that run Forth (or many of the primitives required
                   5047: to implement the Forth virtual machine efficiently) directly. On these
                   5048: processors, the relationship between name, code and data spaces may be
1.32      anton    5049: imposed as a side-effect of the architecture of the processor.
1.27      crook    5050: 
                   5051: @item
                   5052: A Forth compiler that executes from ROM on an embedded system needs its
                   5053: data space separated from the name and code spaces so that the data
                   5054: space can be mapped to a RAM area.
                   5055: 
                   5056: @item 
                   5057: A Forth compiler that runs on an embedded system may have a requirement
                   5058: for a small memory footprint. On such a system it can be useful to
1.32      anton    5059: separate the header space from the data and code spaces; once the
                   5060: application has been compiled, the header space is no longer
1.27      crook    5061: required@footnote{more strictly speaking, most applications can be
1.32      anton    5062: designed so that this is the case}. The header space can be deleted
1.29      crook    5063: entirely, or could be stored in memory on a remote @i{host} system for
1.27      crook    5064: debug and development purposes. In the latter case, the compiler running
1.29      crook    5065: on the @i{target} system could implement a protocol across a
1.32      anton    5066: communication link that would allow it to interrogate the header space.
1.27      crook    5067: @end itemize
                   5068: 
1.32      anton    5069: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   5070: @subsection Dictionary allocation
1.27      crook    5071: @cindex reserving data space
                   5072: @cindex data space - reserving some
                   5073: 
1.32      anton    5074: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   5075: you want to deallocate X, you also deallocate everything
                   5076: allocated after X.
                   5077: 
                   5078: The allocations using the words below are contiguous and grow the region
                   5079: towards increasing addresses.  Other words that allocate dictionary
                   5080: memory of any kind (i.e., defining words including @code{:noname}) end
                   5081: the contiguous region and start a new one.
                   5082: 
                   5083: In ANS Forth only @code{create}d words are guaranteed to produce an
                   5084: address that is the start of the following contiguous region.  In
                   5085: particular, the cell allocated by @code{variable} is not guaranteed to
                   5086: be contiguous with following @code{allot}ed memory.
                   5087: 
                   5088: You can deallocate memory by using @code{allot} with a negative argument
                   5089: (with some restrictions, see @code{allot}). For larger deallocations use
                   5090: @code{marker}.
1.27      crook    5091: 
1.29      crook    5092: 
1.27      crook    5093: doc-here
                   5094: doc-unused
                   5095: doc-allot
                   5096: doc-c,
1.29      crook    5097: doc-f,
1.27      crook    5098: doc-,
                   5099: doc-2,
1.29      crook    5100: @cindex user space
                   5101: doc-udp
                   5102: doc-uallot
1.27      crook    5103: 
1.32      anton    5104: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   5105: course you should allocate memory in an aligned way, too. I.e., before
                   5106: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   5107: The words below align @code{here} if it is not already.  Basically it is
                   5108: only already aligned for a type, if the last allocation was a multiple
                   5109: of the size of this type and if @code{here} was aligned for this type
                   5110: before.
                   5111: 
                   5112: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   5113: ANS Forth (@code{maxalign}ed in Gforth).
                   5114: 
                   5115: doc-align
                   5116: doc-falign
                   5117: doc-sfalign
                   5118: doc-dfalign
                   5119: doc-maxalign
                   5120: doc-cfalign
                   5121: 
                   5122: 
                   5123: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   5124: @subsection Heap allocation
                   5125: @cindex heap allocation
                   5126: @cindex dynamic allocation of memory
                   5127: @cindex memory-allocation word set
                   5128: 
                   5129: Heap allocation supports deallocation of allocated memory in any
                   5130: order. Dictionary allocation is not affected by it (i.e., it does not
                   5131: end a contiguous region). In Gforth, these words are implemented using
                   5132: the standard C library calls malloc(), free() and resize().
                   5133: 
                   5134: doc-allocate
                   5135: doc-free
                   5136: doc-resize
                   5137: 
1.27      crook    5138: 
1.32      anton    5139: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    5140: @subsection Memory Access
                   5141: @cindex memory access words
                   5142: 
1.44      crook    5143: 
1.1       anton    5144: doc-@
                   5145: doc-!
                   5146: doc-+!
                   5147: doc-c@
                   5148: doc-c!
                   5149: doc-2@
                   5150: doc-2!
                   5151: doc-f@
                   5152: doc-f!
                   5153: doc-sf@
                   5154: doc-sf!
                   5155: doc-df@
                   5156: doc-df!
                   5157: 
1.32      anton    5158: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   5159: @subsection Address arithmetic
1.1       anton    5160: @cindex address arithmetic words
                   5161: 
1.32      anton    5162: Address arithmetic is the foundation on which data structures like
                   5163: arrays, records (@pxref{Structures}) and objects (@pxref{Object-oriented
                   5164: Forth}) are built.
                   5165: 
1.1       anton    5166: ANS Forth does not specify the sizes of the data types. Instead, it
                   5167: offers a number of words for computing sizes and doing address
1.29      crook    5168: arithmetic. Address arithmetic is performed in terms of address units
                   5169: (aus); on most systems the address unit is one byte. Note that a
                   5170: character may have more than one au, so @code{chars} is no noop (on
                   5171: systems where it is a noop, it compiles to nothing).
1.1       anton    5172: 
                   5173: @cindex alignment of addresses for types
                   5174: ANS Forth also defines words for aligning addresses for specific
                   5175: types. Many computers require that accesses to specific data types
                   5176: must only occur at specific addresses; e.g., that cells may only be
                   5177: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5178: accesses, it can usually perform aligned accesses faster. 
                   5179: 
                   5180: For the performance-conscious: alignment operations are usually only
                   5181: necessary during the definition of a data structure, not during the
                   5182: (more frequent) accesses to it.
                   5183: 
                   5184: ANS Forth defines no words for character-aligning addresses. This is not
                   5185: an oversight, but reflects the fact that addresses that are not
                   5186: char-aligned have no use in the standard and therefore will not be
                   5187: created.
                   5188: 
                   5189: @cindex @code{CREATE} and alignment
1.29      crook    5190: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5191: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5192: are aligned for all purposes.
                   5193: 
1.26      crook    5194: Note that the ANS Forth word @code{char} has nothing to do with address
                   5195: arithmetic.
1.1       anton    5196: 
1.44      crook    5197: 
1.1       anton    5198: doc-chars
                   5199: doc-char+
                   5200: doc-cells
                   5201: doc-cell+
                   5202: doc-cell
                   5203: doc-aligned
                   5204: doc-floats
                   5205: doc-float+
                   5206: doc-float
                   5207: doc-faligned
                   5208: doc-sfloats
                   5209: doc-sfloat+
                   5210: doc-sfaligned
                   5211: doc-dfloats
                   5212: doc-dfloat+
                   5213: doc-dfaligned
                   5214: doc-maxaligned
                   5215: doc-cfaligned
                   5216: doc-address-unit-bits
                   5217: 
1.44      crook    5218: 
1.32      anton    5219: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5220: @subsection Memory Blocks
                   5221: @cindex memory block words
1.27      crook    5222: @cindex character strings - moving and copying
                   5223: 
1.49      anton    5224: Memory blocks often represent character strings; For ways of storing
                   5225: character strings in memory see @ref{String Formats}.  For other
                   5226: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5227: 
1.32      anton    5228: Some of these words work on address units. Others work on character
                   5229: units (increments of @code{CHAR}), and expect a @code{CHAR}-aligned
                   5230: address. Choose the correct operation depending upon your data type.
1.21      crook    5231: 
                   5232: When copying characters between overlapping memory regions, choose
                   5233: carefully between @code{cmove} and @code{cmove>}.
                   5234: 
1.29      crook    5235: You can only use any of these words @i{portably} to access data space.
1.21      crook    5236: 
1.27      crook    5237: @comment TODO - think the naming of the arguments is wrong for move
1.29      crook    5238: @comment well, really it seems to be the Standard that's wrong; it
                   5239: @comment describes MOVE as a word that requires a CELL-aligned source
                   5240: @comment and destination address but a xtranfer count that need not
                   5241: @comment be a multiple of CELL.
1.44      crook    5242: 
1.1       anton    5243: doc-move
                   5244: doc-erase
                   5245: doc-cmove
                   5246: doc-cmove>
                   5247: doc-fill
                   5248: doc-blank
1.21      crook    5249: doc-compare
                   5250: doc-search
1.27      crook    5251: doc--trailing
                   5252: doc-/string
                   5253: 
1.44      crook    5254: 
1.27      crook    5255: @comment TODO examples
                   5256: 
1.1       anton    5257: 
1.26      crook    5258: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5259: @section Control Structures
                   5260: @cindex control structures
                   5261: 
1.33      anton    5262: Control structures in Forth cannot be used interpretively, only in a
                   5263: colon definition@footnote{To be precise, they have no interpretation
                   5264: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5265: not like this limitation, but have not seen a satisfying way around it
                   5266: yet, although many schemes have been proposed.
1.1       anton    5267: 
                   5268: @menu
1.33      anton    5269: * Selection::                   IF ... ELSE ... ENDIF
                   5270: * Simple Loops::                BEGIN ...
1.29      crook    5271: * Counted Loops::               DO
                   5272: * Arbitrary control structures::
                   5273: * Calls and returns::
1.1       anton    5274: * Exception Handling::          
                   5275: @end menu
                   5276: 
                   5277: @node Selection, Simple Loops, Control Structures, Control Structures
                   5278: @subsection Selection
                   5279: @cindex selection control structures
                   5280: @cindex control structures for selection
                   5281: 
1.33      anton    5282: @c what's the purpose of all these @i? Maybe we should define a macro
                   5283: @c so we can produce logical markup.  - anton
                   5284: 
1.44      crook    5285: @c nac-> When I started working on the manual, a mixture of @i and @var
                   5286: @c were used inconsistently in code examples and \Glossary entries. These
                   5287: @c two behave differently in info format so I decided to standardize on @i.
                   5288: @c Logical markup would be better but texi isn't really upto it, and
                   5289: @c texi2html just ignores macros.
1.47      crook    5290: @c nac02dec1999-> update: the latest texinfo release can spit out html
                   5291: @c and it handles macros, so we could do some logical markup. Unfortunately
                   5292: @c texinfo will not split html output, which would be a big pain if you
                   5293: @c wanted to put the document on the web, which would be nice.
1.44      crook    5294: 
1.1       anton    5295: @cindex @code{IF} control structure
                   5296: @example
1.29      crook    5297: @i{flag}
1.1       anton    5298: IF
1.29      crook    5299:   @i{code}
1.1       anton    5300: ENDIF
                   5301: @end example
1.21      crook    5302: @noindent
1.33      anton    5303: 
1.44      crook    5304: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5305: with any bit set represents truth) @i{code} is executed.
1.33      anton    5306: 
1.1       anton    5307: @example
1.29      crook    5308: @i{flag}
1.1       anton    5309: IF
1.29      crook    5310:   @i{code1}
1.1       anton    5311: ELSE
1.29      crook    5312:   @i{code2}
1.1       anton    5313: ENDIF
                   5314: @end example
                   5315: 
1.44      crook    5316: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5317: executed.
1.33      anton    5318: 
1.1       anton    5319: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5320: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5321: recommend using @code{ENDIF}, because it is less confusing for people
                   5322: who also know other languages (and is not prone to reinforcing negative
                   5323: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5324: system that only supplies @code{THEN} is simple:
                   5325: @example
1.21      crook    5326: : ENDIF   POSTPONE THEN ; immediate
1.1       anton    5327: @end example
                   5328: 
                   5329: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5330: (adv.)}  has the following meanings:
                   5331: @quotation
                   5332: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5333: (if you were there, then you saw them).
                   5334: @end quotation
                   5335: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5336: and many other programming languages has the meaning 3d.]
                   5337: 
1.21      crook    5338: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5339: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5340: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5341: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5342: @file{compat/control.fs}.
                   5343: 
                   5344: @cindex @code{CASE} control structure
                   5345: @example
1.29      crook    5346: @i{n}
1.1       anton    5347: CASE
1.29      crook    5348:   @i{n1} OF @i{code1} ENDOF
                   5349:   @i{n2} OF @i{code2} ENDOF
1.1       anton    5350:   @dots{}
                   5351: ENDCASE
                   5352: @end example
                   5353: 
1.29      crook    5354: Executes the first @i{codei}, where the @i{ni} is equal to
                   5355: @i{n}. A default case can be added by simply writing the code after
                   5356: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
1.1       anton    5357: but must not consume it.
                   5358: 
                   5359: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5360: @subsection Simple Loops
                   5361: @cindex simple loops
                   5362: @cindex loops without count 
                   5363: 
                   5364: @cindex @code{WHILE} loop
                   5365: @example
                   5366: BEGIN
1.29      crook    5367:   @i{code1}
                   5368:   @i{flag}
1.1       anton    5369: WHILE
1.29      crook    5370:   @i{code2}
1.1       anton    5371: REPEAT
                   5372: @end example
                   5373: 
1.29      crook    5374: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5375: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5376: false, execution continues after the @code{REPEAT}.
                   5377: 
                   5378: @cindex @code{UNTIL} loop
                   5379: @example
                   5380: BEGIN
1.29      crook    5381:   @i{code}
                   5382:   @i{flag}
1.1       anton    5383: UNTIL
                   5384: @end example
                   5385: 
1.29      crook    5386: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5387: 
                   5388: @cindex endless loop
                   5389: @cindex loops, endless
                   5390: @example
                   5391: BEGIN
1.29      crook    5392:   @i{code}
1.1       anton    5393: AGAIN
                   5394: @end example
                   5395: 
                   5396: This is an endless loop.
                   5397: 
                   5398: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5399: @subsection Counted Loops
                   5400: @cindex counted loops
                   5401: @cindex loops, counted
                   5402: @cindex @code{DO} loops
                   5403: 
                   5404: The basic counted loop is:
                   5405: @example
1.29      crook    5406: @i{limit} @i{start}
1.1       anton    5407: ?DO
1.29      crook    5408:   @i{body}
1.1       anton    5409: LOOP
                   5410: @end example
                   5411: 
1.29      crook    5412: This performs one iteration for every integer, starting from @i{start}
                   5413: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5414: accessed with @code{i}. For example, the loop:
1.1       anton    5415: @example
                   5416: 10 0 ?DO
                   5417:   i .
                   5418: LOOP
                   5419: @end example
1.21      crook    5420: @noindent
                   5421: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5422: 
1.1       anton    5423: The index of the innermost loop can be accessed with @code{i}, the index
                   5424: of the next loop with @code{j}, and the index of the third loop with
                   5425: @code{k}.
                   5426: 
1.44      crook    5427: 
1.1       anton    5428: doc-i
                   5429: doc-j
                   5430: doc-k
                   5431: 
1.44      crook    5432: 
1.1       anton    5433: The loop control data are kept on the return stack, so there are some
1.21      crook    5434: restrictions on mixing return stack accesses and counted loop words. In
                   5435: particuler, if you put values on the return stack outside the loop, you
                   5436: cannot read them inside the loop@footnote{well, not in a way that is
                   5437: portable.}. If you put values on the return stack within a loop, you
                   5438: have to remove them before the end of the loop and before accessing the
                   5439: index of the loop.
1.1       anton    5440: 
                   5441: There are several variations on the counted loop:
                   5442: 
1.21      crook    5443: @itemize @bullet
                   5444: @item
                   5445: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5446: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5447: 
                   5448: @example
                   5449: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5450: @end example
                   5451: prints @code{0 1 2 3}
                   5452: 
1.1       anton    5453: 
1.21      crook    5454: @item
                   5455: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5456: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5457: return stack so @code{EXIT} can get to its return address. For example:
                   5458: 
                   5459: @example
                   5460: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5461: @end example
                   5462: prints @code{0 1 2 3}
                   5463: 
                   5464: 
                   5465: @item
1.29      crook    5466: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5467: (and @code{LOOP} iterates until they become equal by wrap-around
                   5468: arithmetic). This behaviour is usually not what you want. Therefore,
                   5469: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5470: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5471: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5472: unsigned loop parameters.
                   5473: 
1.21      crook    5474: @item
                   5475: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5476: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5477: if you know that the loop is entered in any case. Such knowledge tends
                   5478: to become invalid during maintenance of a program, and then the
                   5479: @code{DO} will make trouble.
                   5480: 
                   5481: @item
1.29      crook    5482: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5483: index by @i{n} instead of by 1. The loop is terminated when the border
                   5484: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5485: 
1.21      crook    5486: @example
                   5487: 4 0 +DO  i .  2 +LOOP
                   5488: @end example
                   5489: @noindent
                   5490: prints @code{0 2}
                   5491: 
                   5492: @example
                   5493: 4 1 +DO  i .  2 +LOOP
                   5494: @end example
                   5495: @noindent
                   5496: prints @code{1 3}
1.1       anton    5497: 
                   5498: 
                   5499: @cindex negative increment for counted loops
                   5500: @cindex counted loops with negative increment
1.29      crook    5501: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5502: 
1.21      crook    5503: @example
                   5504: -1 0 ?DO  i .  -1 +LOOP
                   5505: @end example
                   5506: @noindent
                   5507: prints @code{0 -1}
1.1       anton    5508: 
1.21      crook    5509: @example
                   5510: 0 0 ?DO  i .  -1 +LOOP
                   5511: @end example
                   5512: prints nothing.
1.1       anton    5513: 
1.29      crook    5514: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5515: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5516: index by @i{u} each iteration. The loop is terminated when the border
                   5517: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5518: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5519: 
1.21      crook    5520: @example
                   5521: -2 0 -DO  i .  1 -LOOP
                   5522: @end example
                   5523: @noindent
                   5524: prints @code{0 -1}
1.1       anton    5525: 
1.21      crook    5526: @example
                   5527: -1 0 -DO  i .  1 -LOOP
                   5528: @end example
                   5529: @noindent
                   5530: prints @code{0}
                   5531: 
                   5532: @example
                   5533: 0 0 -DO  i .  1 -LOOP
                   5534: @end example
                   5535: @noindent
                   5536: prints nothing.
1.1       anton    5537: 
1.21      crook    5538: @end itemize
1.1       anton    5539: 
                   5540: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5541: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5542: for these words that uses only standard words is provided in
                   5543: @file{compat/loops.fs}.
1.1       anton    5544: 
                   5545: 
                   5546: @cindex @code{FOR} loops
1.26      crook    5547: Another counted loop is:
1.1       anton    5548: @example
1.29      crook    5549: @i{n}
1.1       anton    5550: FOR
1.29      crook    5551:   @i{body}
1.1       anton    5552: NEXT
                   5553: @end example
                   5554: This is the preferred loop of native code compiler writers who are too
1.26      crook    5555: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5556: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5557: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5558: Forth systems may behave differently, even if they support @code{FOR}
                   5559: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5560: 
                   5561: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5562: @subsection Arbitrary control structures
                   5563: @cindex control structures, user-defined
                   5564: 
                   5565: @cindex control-flow stack
                   5566: ANS Forth permits and supports using control structures in a non-nested
                   5567: way. Information about incomplete control structures is stored on the
                   5568: control-flow stack. This stack may be implemented on the Forth data
                   5569: stack, and this is what we have done in Gforth.
                   5570: 
                   5571: @cindex @code{orig}, control-flow stack item
                   5572: @cindex @code{dest}, control-flow stack item
                   5573: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5574: entry represents a backward branch target. A few words are the basis for
                   5575: building any control structure possible (except control structures that
                   5576: need storage, like calls, coroutines, and backtracking).
                   5577: 
1.44      crook    5578: 
1.1       anton    5579: doc-if
                   5580: doc-ahead
                   5581: doc-then
                   5582: doc-begin
                   5583: doc-until
                   5584: doc-again
                   5585: doc-cs-pick
                   5586: doc-cs-roll
                   5587: 
1.44      crook    5588: 
1.21      crook    5589: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5590: manipulate the control-flow stack in a portable way. Without them, you
                   5591: would need to know how many stack items are occupied by a control-flow
                   5592: entry (many systems use one cell. In Gforth they currently take three,
                   5593: but this may change in the future).
                   5594: 
1.1       anton    5595: Some standard control structure words are built from these words:
                   5596: 
1.44      crook    5597: 
1.1       anton    5598: doc-else
                   5599: doc-while
                   5600: doc-repeat
                   5601: 
1.44      crook    5602: 
                   5603: @noindent
1.1       anton    5604: Gforth adds some more control-structure words:
                   5605: 
1.44      crook    5606: 
1.1       anton    5607: doc-endif
                   5608: doc-?dup-if
                   5609: doc-?dup-0=-if
                   5610: 
1.44      crook    5611: 
                   5612: @noindent
1.1       anton    5613: Counted loop words constitute a separate group of words:
                   5614: 
1.44      crook    5615: 
1.1       anton    5616: doc-?do
                   5617: doc-+do
                   5618: doc-u+do
                   5619: doc--do
                   5620: doc-u-do
                   5621: doc-do
                   5622: doc-for
                   5623: doc-loop
                   5624: doc-+loop
                   5625: doc--loop
                   5626: doc-next
                   5627: doc-leave
                   5628: doc-?leave
                   5629: doc-unloop
                   5630: doc-done
                   5631: 
1.44      crook    5632: 
1.21      crook    5633: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5634: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5635: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5636: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5637: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5638: resolved (by using one of the loop-ending words or @code{DONE}).
                   5639: 
1.44      crook    5640: @noindent
1.26      crook    5641: Another group of control structure words are:
1.1       anton    5642: 
1.44      crook    5643: 
1.1       anton    5644: doc-case
                   5645: doc-endcase
                   5646: doc-of
                   5647: doc-endof
                   5648: 
1.44      crook    5649: 
1.21      crook    5650: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5651: @code{CS-ROLL}.
1.1       anton    5652: 
                   5653: @subsubsection Programming Style
1.47      crook    5654: @cindex control structures programming style
                   5655: @cindex programming style, arbitrary control structures
1.1       anton    5656: 
                   5657: In order to ensure readability we recommend that you do not create
                   5658: arbitrary control structures directly, but define new control structure
                   5659: words for the control structure you want and use these words in your
1.26      crook    5660: program. For example, instead of writing:
1.1       anton    5661: 
                   5662: @example
1.26      crook    5663: BEGIN
1.1       anton    5664:   ...
1.26      crook    5665: IF [ 1 CS-ROLL ]
1.1       anton    5666:   ...
1.26      crook    5667: AGAIN THEN
1.1       anton    5668: @end example
                   5669: 
1.21      crook    5670: @noindent
1.1       anton    5671: we recommend defining control structure words, e.g.,
                   5672: 
                   5673: @example
1.26      crook    5674: : WHILE ( DEST -- ORIG DEST )
                   5675:  POSTPONE IF
                   5676:  1 CS-ROLL ; immediate
                   5677: 
                   5678: : REPEAT ( orig dest -- )
                   5679:  POSTPONE AGAIN
                   5680:  POSTPONE THEN ; immediate
1.1       anton    5681: @end example
                   5682: 
1.21      crook    5683: @noindent
1.1       anton    5684: and then using these to create the control structure:
                   5685: 
                   5686: @example
1.26      crook    5687: BEGIN
1.1       anton    5688:   ...
1.26      crook    5689: WHILE
1.1       anton    5690:   ...
1.26      crook    5691: REPEAT
1.1       anton    5692: @end example
                   5693: 
                   5694: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5695: @code{WHILE} are predefined, so in this example it would not be
                   5696: necessary to define them.
                   5697: 
                   5698: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5699: @subsection Calls and returns
                   5700: @cindex calling a definition
                   5701: @cindex returning from a definition
                   5702: 
1.3       anton    5703: @cindex recursive definitions
                   5704: A definition can be called simply be writing the name of the definition
1.26      crook    5705: to be called. Normally a definition is invisible during its own
1.3       anton    5706: definition. If you want to write a directly recursive definition, you
1.26      crook    5707: can use @code{recursive} to make the current definition visible, or
                   5708: @code{recurse} to call the current definition directly.
1.3       anton    5709: 
1.44      crook    5710: 
1.3       anton    5711: doc-recursive
                   5712: doc-recurse
                   5713: 
1.44      crook    5714: 
1.21      crook    5715: @comment TODO add example of the two recursion methods
1.12      anton    5716: @quotation
                   5717: @progstyle
                   5718: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5719: definition by name is more descriptive (if the name is well-chosen) than
                   5720: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5721: implementation, it is much better to read (and think) ``now sort the
                   5722: partitions'' than to read ``now do a recursive call''.
                   5723: @end quotation
1.3       anton    5724: 
1.29      crook    5725: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5726: 
                   5727: @example
1.28      crook    5728: Defer foo
1.3       anton    5729: 
                   5730: : bar ( ... -- ... )
                   5731:  ... foo ... ;
                   5732: 
                   5733: :noname ( ... -- ... )
                   5734:  ... bar ... ;
                   5735: IS foo
                   5736: @end example
                   5737: 
1.44      crook    5738: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33      anton    5739: 
1.26      crook    5740: The current definition returns control to the calling definition when
1.33      anton    5741: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5742: 
                   5743: doc-exit
                   5744: doc-;s
                   5745: 
1.44      crook    5746: 
1.1       anton    5747: @node Exception Handling,  , Calls and returns, Control Structures
                   5748: @subsection Exception Handling
1.26      crook    5749: @cindex exceptions
1.1       anton    5750: 
1.26      crook    5751: If your program detects a fatal error condition, the simplest action
                   5752: that it can take is to @code{quit}. This resets the return stack and
                   5753: restarts the text interpreter, but does not print any error message.
1.21      crook    5754: 
1.26      crook    5755: The next stage in severity is to execute @code{abort}, which has the
                   5756: same effect as @code{quit}, with the addition that it resets the data
                   5757: stack.
1.1       anton    5758: 
1.26      crook    5759: A slightly more sophisticated approach is use use @code{abort"}, which
                   5760: compiles a string to be used as an error message and does a conditional
                   5761: @code{abort} at run-time. For example:
1.1       anton    5762: 
1.26      crook    5763: @example
1.30      anton    5764: @kbd{: checker abort" That flag was true" ." A false flag" ;@key{RET}}  ok
                   5765: @kbd{0 checker@key{RET}} A false flag ok
                   5766: @kbd{1 checker@key{RET}}
1.26      crook    5767: :1: That flag was true
                   5768: 1 checker
                   5769:   ^^^^^^^
                   5770: $400D1648 throw 
                   5771: $400E4660
                   5772: @end example
1.1       anton    5773: 
1.26      crook    5774: These simple techniques allow a program to react to a fatal error
                   5775: condition, but they are not exactly user-friendly. The ANS Forth
                   5776: Exception word set provides the pair of words @code{throw} and
                   5777: @code{catch}, which can be used to provide sophisticated error-handling.
1.1       anton    5778: 
1.26      crook    5779: @code{catch} has a similar behaviour to @code{execute}, in that it takes
1.29      crook    5780: an @i{xt} as a parameter and starts execution of the xt. However,
1.26      crook    5781: before passing control to the xt, @code{catch} pushes an
1.29      crook    5782: @dfn{exception frame} onto the @dfn{exception stack}. This exception
1.26      crook    5783: frame is used to restore the system to a known state if a detected error
                   5784: occurs during the execution of the xt. A typical way to use @code{catch}
                   5785: would be:
1.1       anton    5786: 
1.26      crook    5787: @example
                   5788: ... ['] foo catch IF ...
                   5789: @end example
1.1       anton    5790: 
1.33      anton    5791: @c TOS is undefined. - anton
1.44      crook    5792: 
                   5793: @c nac-> TODO -- I need to look at this example again.
                   5794: 
1.26      crook    5795: Whilst @code{foo} executes, it can call other words to any level of
                   5796: nesting, as usual.  If @code{foo} (and all the words that it calls)
1.33      anton    5797: execute successfully, control will ultimately pass to the word following
                   5798: the @code{catch}, and there will be a 0 at TOS.  However, if any word
                   5799: detects an error, it can terminate the execution of @code{foo} by
                   5800: pushing a non-zero error code onto the stack and then performing a
                   5801: @code{throw}. The execution of @code{throw} will pass control to the
                   5802: word following the @code{catch}, but this time the TOS will hold the
                   5803: error code. Therefore, the @code{IF} in the example can be used to
                   5804: determine whether @code{foo} executed successfully.
1.1       anton    5805: 
1.26      crook    5806: This simple example shows how you can use @code{throw} and @code{catch}
                   5807: to ``take over'' exception handling from the system:
1.1       anton    5808: @example
1.26      crook    5809: : my-div ['] / catch if ." DIVIDE ERROR" else ." OK.. " . then ;
1.1       anton    5810: @end example
                   5811: 
1.26      crook    5812: The next example is more sophisticated and shows a multi-level
                   5813: @code{throw} and @code{catch}. To understand this example, start at the
                   5814: definition of @code{top-level} and work backwards:
                   5815: 
1.1       anton    5816: @example
1.26      crook    5817: : lowest-level ( -- c )
                   5818:     key dup 27 = if
1.44      crook    5819:         1 throw \ ESCAPE key pressed
1.26      crook    5820:     else
1.44      crook    5821:         ." lowest-level successful" CR
1.26      crook    5822:     then
                   5823: ;
                   5824: 
                   5825: : lower-level ( -- c )
                   5826:     lowest-level
                   5827:     \ at this level consider a CTRL-U to be a fatal error
                   5828:     dup 21 = if \ CTRL-U
1.44      crook    5829:         2 throw
1.26      crook    5830:     else
1.44      crook    5831:         ." lower-level successful" CR
1.26      crook    5832:     then
                   5833: ;
                   5834: 
                   5835: : low-level ( -- c )
                   5836:     ['] lower-level catch
                   5837:     ?dup if
1.44      crook    5838:         \ error occurred - do we recognise it?
                   5839:         dup 1 = if
                   5840:             \ ESCAPE key pressed.. pretend it was an E
                   5841:             [char] E
                   5842:         else throw \ propogate the error upwards
                   5843:         then
1.26      crook    5844:     then
                   5845:     ." low-level successfull" CR
                   5846: ;
                   5847: 
                   5848: : top-level ( -- )
                   5849:     CR ['] low-level catch \ CATCH is used like EXECUTE
                   5850:     ?dup if \ error occurred..
1.44      crook    5851:         ." Error " . ." occurred - contact your supplier"
1.26      crook    5852:     else
1.44      crook    5853:         ." The '" emit ." ' key was pressed" CR
1.26      crook    5854:     then
                   5855: ;
1.1       anton    5856: @end example
                   5857: 
1.26      crook    5858: The ANS Forth document assigns @code{throw} codes thus:
1.1       anton    5859: 
1.26      crook    5860: @itemize @bullet
                   5861: @item
                   5862: codes in the range -1 -- -255 are reserved to be assigned by the
                   5863: Standard. Assignments for codes in the range -1 -- -58 are currently
                   5864: documented in the Standard. In particular, @code{-1 throw} is equivalent
                   5865: to @code{abort} and @code{-2 throw} is equivalent to @code{abort"}.
                   5866: @item
                   5867: codes in the range -256 -- -4095 are reserved to be assigned by the system.
                   5868: @item
                   5869: all other codes may be assigned by programs.
                   5870: @end itemize
1.1       anton    5871: 
1.26      crook    5872: Gforth provides the word @code{exception} as a mechanism for assigning
                   5873: system throw codes to applications. This allows multiple applications to
                   5874: co-exist in memory without any clash of @code{throw} codes. A definition
                   5875: of @code{exception} in ANS Forth is provided in
                   5876: @file{compat/exception.fs}.
1.1       anton    5877: 
1.44      crook    5878: 
1.26      crook    5879: doc-quit
                   5880: doc-abort
                   5881: doc-abort"
1.1       anton    5882: 
1.26      crook    5883: doc-catch
1.29      crook    5884: doc-throw
                   5885: doc---exception-exception
                   5886: 
                   5887: 
1.44      crook    5888: 
1.29      crook    5889: @c -------------------------------------------------------------
1.47      crook    5890: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    5891: @section Defining Words
                   5892: @cindex defining words
                   5893: 
1.47      crook    5894: Defining words are used to extend Forth by creating new entries in the dictionary.
                   5895: 
1.29      crook    5896: @menu
1.44      crook    5897: * CREATE::
                   5898: * Variables::                   Variables and user variables
                   5899: * Constants::
                   5900: * Values::                      Initialised variables
1.29      crook    5901: * Colon Definitions::
1.44      crook    5902: * Anonymous Definitions::       Definitions without names
1.29      crook    5903: * User-defined Defining Words::
1.44      crook    5904: * Deferred words::              Allow forward references
                   5905: * Aliases::
1.29      crook    5906: * Supplying names::
                   5907: @end menu
                   5908: 
1.44      crook    5909: @node CREATE, Variables, Defining Words, Defining Words
                   5910: @subsection @code{CREATE}
1.29      crook    5911: @cindex simple defining words
                   5912: @cindex defining words, simple
                   5913: 
                   5914: Defining words are used to create new entries in the dictionary. The
                   5915: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   5916: this:
                   5917: 
                   5918: @example
                   5919: CREATE new-word1
                   5920: @end example
                   5921: 
                   5922: @code{CREATE} is a parsing word that generates a dictionary entry for
                   5923: @code{new-word1}. When @code{new-word1} is executed, all that it does is
                   5924: leave an address on the stack. The address represents the value of
                   5925: the data space pointer (@code{HERE}) at the time that @code{new-word1}
                   5926: was defined. Therefore, @code{CREATE} is a way of associating a name
                   5927: with the address of a region of memory.
                   5928: 
1.34      anton    5929: doc-create
                   5930: 
1.29      crook    5931: By extending this example to reserve some memory in data space, we end
                   5932: up with a @i{variable}. Here are two different ways to do it:
                   5933: 
                   5934: @example
                   5935: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   5936: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   5937: @end example
                   5938: 
                   5939: The variable can be examined and modified using @code{@@} (``fetch'') and
                   5940: @code{!} (``store'') like this:
                   5941: 
                   5942: @example
                   5943: new-word2 @@ .      \ get address, fetch from it and display
                   5944: 1234 new-word2 !   \ new value, get address, store to it
                   5945: @end example
                   5946: 
1.44      crook    5947: @cindex arrays
                   5948: A similar mechanism can be used to create arrays. For example, an
                   5949: 80-character text input buffer:
1.29      crook    5950: 
                   5951: @example
1.44      crook    5952: CREATE text-buf 80 chars allot
                   5953: 
                   5954: text-buf 0 chars c@@ \ the 1st character (offset 0)
                   5955: text-buf 3 chars c@@ \ the 4th character (offset 3)
                   5956: @end example
1.29      crook    5957: 
1.44      crook    5958: You can build arbitrarily complex data structures by allocating
1.49      anton    5959: appropriate areas of memory. For further discussions of this, and to
1.66    ! anton    5960: learn about some Gforth tools that make it easier,
1.49      anton    5961: @xref{Structures}.
1.44      crook    5962: 
                   5963: 
                   5964: @node Variables, Constants, CREATE, Defining Words
                   5965: @subsection Variables
                   5966: @cindex variables
                   5967: 
                   5968: The previous section showed how a sequence of commands could be used to
                   5969: generate a variable.  As a final refinement, the whole code sequence can
                   5970: be wrapped up in a defining word (pre-empting the subject of the next
                   5971: section), making it easier to create new variables:
                   5972: 
                   5973: @example
                   5974: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   5975: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   5976: 
                   5977: myvariableX foo \ variable foo starts off with an unknown value
                   5978: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    5979: 
                   5980: 45 3 * foo !   \ set foo to 135
                   5981: 1234 joe !     \ set joe to 1234
                   5982: 3 joe +!       \ increment joe by 3.. to 1237
                   5983: @end example
                   5984: 
                   5985: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    5986: Forth already has a definition @code{Variable}. ANS Forth does not
                   5987: require a @code{Variable} to be initialised when it is created (i.e., it
                   5988: behaves like @code{myvariableX}). In contrast, Gforth's @code{Variable}
                   5989: initialises the variable to 0 (i.e., it behaves exactly like
                   5990: @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    5991: @code{fvariable} for double and floating-point variables, respectively
                   5992: -- both are initialised to 0 in Gforth. If you use a @code{Variable} to
                   5993: store a boolean, you can use @code{on} and @code{off} to toggle its
                   5994: state.
1.29      crook    5995: 
1.34      anton    5996: doc-variable
                   5997: doc-2variable
                   5998: doc-fvariable
                   5999: 
1.29      crook    6000: @cindex user variables
                   6001: @cindex user space
                   6002: The defining word @code{User} behaves in the same way as @code{Variable}.
                   6003: The difference is that it reserves space in @i{user (data) space} rather
                   6004: than normal data space. In a Forth system that has a multi-tasker, each
                   6005: task has its own set of user variables.
                   6006: 
1.34      anton    6007: doc-user
                   6008: 
1.29      crook    6009: @comment TODO is that stuff about user variables strictly correct? Is it
                   6010: @comment just terminal tasks that have user variables?
                   6011: @comment should document tasker.fs (with some examples) elsewhere
                   6012: @comment in this manual, then expand on user space and user variables.
                   6013: 
1.44      crook    6014: 
                   6015: @node Constants, Values, Variables, Defining Words
                   6016: @subsection Constants
                   6017: @cindex constants
                   6018: 
                   6019: @code{Constant} allows you to declare a fixed value and refer to it by
                   6020: name. For example:
1.29      crook    6021: 
                   6022: @example
                   6023: 12 Constant INCHES-PER-FOOT
                   6024: 3E+08 fconstant SPEED-O-LIGHT
                   6025: @end example
                   6026: 
                   6027: A @code{Variable} can be both read and written, so its run-time
                   6028: behaviour is to supply an address through which its current value can be
                   6029: manipulated. In contrast, the value of a @code{Constant} cannot be
                   6030: changed once it has been declared@footnote{Well, often it can be -- but
                   6031: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   6032: on).} so it's not necessary to supply the address -- it is more
                   6033: efficient to return the value of the constant directly. That's exactly
                   6034: what happens; the run-time effect of a constant is to put its value on
1.49      anton    6035: the top of the stack (You can find one
                   6036: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    6037: 
                   6038: Gforth also provides @code{2Constant} and @code{fconstant} for defining
                   6039: double and floating-point constants, respectively.
                   6040: 
1.34      anton    6041: doc-constant
                   6042: doc-2constant
                   6043: doc-fconstant
                   6044: 
                   6045: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    6046: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   6047: @c constant, use it and then delete the definition of the constant..
                   6048: @c I agree that it's rather deep, but IMO it is an important difference
                   6049: @c relative to other programming languages.. often it's annoying: it
                   6050: @c certainly changes my programming style relative to C.
                   6051: 
1.29      crook    6052: Constants in Forth behave differently from their equivalents in other
                   6053: programming languages. In other languages, a constant (such as an EQU in
                   6054: assembler or a #define in C) only exists at compile-time; in the
                   6055: executable program the constant has been translated into an absolute
                   6056: number and, unless you are using a symbolic debugger, it's impossible to
                   6057: know what abstract thing that number represents. In Forth a constant has
1.44      crook    6058: an entry in the header space and remains there after the code that uses
                   6059: it has been defined. In fact, it must remain in the dictionary since it
                   6060: has run-time duties to perform. For example:
1.29      crook    6061: 
                   6062: @example
                   6063: 12 Constant INCHES-PER-FOOT
                   6064: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   6065: @end example
                   6066: 
                   6067: @cindex in-lining of constants
                   6068: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   6069: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   6070: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   6071: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   6072: attempt to optimise constants by in-lining them where they are used. You
                   6073: can force Gforth to in-line a constant like this:
                   6074: 
                   6075: @example
                   6076: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   6077: @end example
                   6078: 
                   6079: If you use @code{see} to decompile @i{this} version of
                   6080: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    6081: longer present. To understand how this works, read
                   6082: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    6083: 
                   6084: In-lining constants in this way might improve execution time
                   6085: fractionally, and can ensure that a constant is now only referenced at
                   6086: compile-time. However, the definition of the constant still remains in
                   6087: the dictionary. Some Forth compilers provide a mechanism for controlling
                   6088: a second dictionary for holding transient words such that this second
                   6089: dictionary can be deleted later in order to recover memory
                   6090: space. However, there is no standard way of doing this.
                   6091: 
                   6092: 
1.44      crook    6093: @node Values, Colon Definitions, Constants, Defining Words
                   6094: @subsection Values
                   6095: @cindex values
1.34      anton    6096: 
1.44      crook    6097: A @code{Value} is like a @code{Variable} but with two important
                   6098: differences:
1.29      crook    6099: 
                   6100: @itemize @bullet
                   6101: @item
1.44      crook    6102: A @code{Value} is initialised when it is declared; like a
                   6103: @code{Constant} but unlike a @code{Variable}.
1.29      crook    6104: @item
1.44      crook    6105: A @code{Value} returns its value rather than its address when it is
                   6106: executed; i.e., it has the same run-time behaviour as @code{Constant}.
1.29      crook    6107: @end itemize
                   6108: 
1.44      crook    6109: A @code{Value} needs an additional word, @code{TO} to allow its value to
                   6110: be changed. Here are some examples:
1.29      crook    6111: 
                   6112: @example
1.44      crook    6113: 12 Value APPLES \ Define APPLES with an initial value of 12
                   6114: 34 TO APPLES    \ Change the value of APPLES. TO is a parsing word
                   6115: APPLES          \ puts 34 on the top of the stack.
1.29      crook    6116: @end example
                   6117: 
1.44      crook    6118: doc-value
                   6119: doc-to
1.29      crook    6120: 
1.35      anton    6121: 
1.44      crook    6122: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   6123: @subsection Colon Definitions
                   6124: @cindex colon definitions
1.35      anton    6125: 
                   6126: @example
1.44      crook    6127: : name ( ... -- ... )
                   6128:     word1 word2 word3 ;
1.29      crook    6129: @end example
                   6130: 
1.44      crook    6131: @noindent
                   6132: Creates a word called @code{name} that, upon execution, executes
                   6133: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    6134: 
1.49      anton    6135: The explanation above is somewhat superficial. For simple examples of
                   6136: colon definitions see @ref{Your first definition}.  For an in-depth
1.66    ! anton    6137: discussion of some of the issues involved, @xref{Interpretation and
1.49      anton    6138: Compilation Semantics}.
1.29      crook    6139: 
1.44      crook    6140: doc-:
                   6141: doc-;
1.1       anton    6142: 
1.34      anton    6143: 
1.44      crook    6144: @node Anonymous Definitions, User-defined Defining Words, Colon Definitions, Defining Words
                   6145: @subsection Anonymous Definitions
                   6146: @cindex colon definitions
                   6147: @cindex defining words without name
1.34      anton    6148: 
1.44      crook    6149: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   6150: name. You can do this with:
1.1       anton    6151: 
1.44      crook    6152: doc-:noname
1.1       anton    6153: 
1.44      crook    6154: This leaves the execution token for the word on the stack after the
                   6155: closing @code{;}. Here's an example in which a deferred word is
                   6156: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6157: 
1.29      crook    6158: @example
1.44      crook    6159: Defer deferred
                   6160: :noname ( ... -- ... )
                   6161:   ... ;
                   6162: IS deferred
1.29      crook    6163: @end example
1.26      crook    6164: 
1.44      crook    6165: @noindent
                   6166: Gforth provides an alternative way of doing this, using two separate
                   6167: words:
1.27      crook    6168: 
1.44      crook    6169: doc-noname
                   6170: @cindex execution token of last defined word
                   6171: doc-lastxt
1.1       anton    6172: 
1.44      crook    6173: @noindent
                   6174: The previous example can be rewritten using @code{noname} and
                   6175: @code{lastxt}:
1.1       anton    6176: 
1.26      crook    6177: @example
1.44      crook    6178: Defer deferred
                   6179: noname : ( ... -- ... )
                   6180:   ... ;
                   6181: lastxt IS deferred
1.26      crook    6182: @end example
1.1       anton    6183: 
1.29      crook    6184: @noindent
1.44      crook    6185: @code{noname} works with any defining word, not just @code{:}.
                   6186: 
                   6187: @code{lastxt} also works when the last word was not defined as
                   6188: @code{noname}. It also has the useful property that is is valid as soon
                   6189: as the header for a definition has been built. Thus:
                   6190: 
                   6191: @example
                   6192: lastxt . : foo [ lastxt . ] ; ' foo .
                   6193: @end example
1.1       anton    6194: 
1.44      crook    6195: @noindent
                   6196: prints 3 numbers; the last two are the same.
1.26      crook    6197: 
1.1       anton    6198: 
1.44      crook    6199: @node User-defined Defining Words, Deferred words, Anonymous Definitions, Defining Words
1.26      crook    6200: @subsection User-defined Defining Words
                   6201: @cindex user-defined defining words
                   6202: @cindex defining words, user-defined
1.1       anton    6203: 
1.29      crook    6204: You can create a new defining word by wrapping defining-time code around
                   6205: an existing defining word and putting the sequence in a colon
                   6206: definition. For example, suppose that you have a word @code{stats} that
                   6207: gathers statistics about colon definitions given the @i{xt} of the
                   6208: definition, and you want every colon definition in your application to
                   6209: make a call to @code{stats}. You can define and use a new version of
                   6210: @code{:} like this:
                   6211: 
                   6212: @example
                   6213: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6214:   ... ;  \ other code
                   6215: 
                   6216: : my: : lastxt postpone literal ['] stats compile, ;
                   6217: 
                   6218: my: foo + - ;
                   6219: @end example
                   6220: 
                   6221: When @code{foo} is defined using @code{my:} these steps occur:
                   6222: 
                   6223: @itemize @bullet
                   6224: @item
                   6225: @code{my:} is executed.
                   6226: @item
                   6227: The @code{:} within the definition (the one between @code{my:} and
                   6228: @code{lastxt}) is executed, and does just what it always does; it parses
                   6229: the input stream for a name, builds a dictionary header for the name
                   6230: @code{foo} and switches @code{state} from interpret to compile.
                   6231: @item
                   6232: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
                   6233: being defined -- @code{foo} -- onto the stack.
                   6234: @item
                   6235: The code that was produced by @code{postpone literal} is executed; this
                   6236: causes the value on the stack to be compiled as a literal in the code
                   6237: area of @code{foo}.
                   6238: @item
                   6239: The code @code{['] stats} compiles a literal into the definition of
                   6240: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6241: execution token for @code{stats} -- is layed down in the code area of
                   6242: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6243: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6244: in the code area is implementation-dependent. A threaded implementation
                   6245: might spit out the execution token directly whilst another
                   6246: implementation might spit out a native code sequence.}.
                   6247: @item
                   6248: At this point, the execution of @code{my:} is complete, and control
                   6249: returns to the text interpreter. The text interpreter is in compile
                   6250: state, so subsequent text @code{+ -} is compiled into the definition of
                   6251: @code{foo} and the @code{;} terminates the definition as always.
                   6252: @end itemize
                   6253: 
                   6254: You can use @code{see} to decompile a word that was defined using
                   6255: @code{my:} and see how it is different from a normal @code{:}
                   6256: definition. For example:
                   6257: 
                   6258: @example
                   6259: : bar + - ;  \ like foo but using : rather than my:
                   6260: see bar
                   6261: : bar
                   6262:   + - ;
                   6263: see foo
                   6264: : foo
                   6265:   107645672 stats + - ;
                   6266: 
                   6267: \ use ' stats . to show that 107645672 is the xt for stats
                   6268: @end example
                   6269: 
                   6270: You can use techniques like this to make new defining words in terms of
                   6271: @i{any} existing defining word.
1.1       anton    6272: 
                   6273: 
1.29      crook    6274: @cindex defining defining words
1.26      crook    6275: @cindex @code{CREATE} ... @code{DOES>}
                   6276: If you want the words defined with your defining words to behave
                   6277: differently from words defined with standard defining words, you can
                   6278: write your defining word like this:
1.1       anton    6279: 
                   6280: @example
1.26      crook    6281: : def-word ( "name" -- )
1.29      crook    6282:     CREATE @i{code1}
1.26      crook    6283: DOES> ( ... -- ... )
1.29      crook    6284:     @i{code2} ;
1.26      crook    6285: 
                   6286: def-word name
1.1       anton    6287: @end example
                   6288: 
1.29      crook    6289: @cindex child words
                   6290: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6291: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6292: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6293: is not executed at this time. The word @code{name} is sometimes called a
                   6294: @dfn{child} of @code{def-word}.
                   6295: 
                   6296: When you execute @code{name}, the address of the body of @code{name} is
                   6297: put on the data stack and @i{code2} is executed (the address of the body
                   6298: of @code{name} is the address @code{HERE} returns immediately after the
                   6299: @code{CREATE}).
                   6300: 
                   6301: @cindex atavism in child words
1.33      anton    6302: You can use @code{def-word} to define a set of child words that behave
1.29      crook    6303: differently, though atavistically; they all have a common run-time
                   6304: behaviour determined by @i{code2}. Typically, the @i{code1} sequence
                   6305: builds a data area in the body of the child word. The structure of the
                   6306: data is common to all children of @code{def-word}, but the data values
                   6307: are specific -- and private -- to each child word. When a child word is
                   6308: executed, the address of its private data area is passed as a parameter
                   6309: on TOS to be used and manipulated@footnote{It is legitimate both to read
                   6310: and write to this data area.} by @i{code2}.
                   6311: 
                   6312: The two fragments of code that make up the defining words act (are
                   6313: executed) at two completely separate times:
1.1       anton    6314: 
1.29      crook    6315: @itemize @bullet
                   6316: @item
                   6317: At @i{define time}, the defining word executes @i{code1} to generate a
                   6318: child word
                   6319: @item
                   6320: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6321: is executed, using parameters (data) that are private and specific to
                   6322: the child word.
                   6323: @end itemize
                   6324: 
1.44      crook    6325: Another way of understanding the behaviour of @code{def-word} and
                   6326: @code{name} is to say that, if you make the following definitions:
1.33      anton    6327: @example
                   6328: : def-word1 ( "name" -- )
                   6329:     CREATE @i{code1} ;
                   6330: 
                   6331: : action1 ( ... -- ... )
                   6332:     @i{code2} ;
                   6333: 
                   6334: def-word1 name1
                   6335: @end example
                   6336: 
1.44      crook    6337: @noindent
                   6338: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6339: 
1.29      crook    6340: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6341: 
1.1       anton    6342: @example
1.29      crook    6343: : CONSTANT ( w "name" -- )
                   6344:     CREATE ,
1.26      crook    6345: DOES> ( -- w )
                   6346:     @@ ;
1.1       anton    6347: @end example
                   6348: 
1.29      crook    6349: @comment There is a beautiful description of how this works and what
                   6350: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6351: @comment commentary on the Counting Fruits problem.
                   6352: 
                   6353: When you create a constant with @code{5 CONSTANT five}, a set of
                   6354: define-time actions take place; first a new word @code{five} is created,
                   6355: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6356: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6357: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6358: no code of its own; it simply contains a data field and a pointer to the
                   6359: code that follows @code{DOES>} in its defining word. That makes words
                   6360: created in this way very compact.
                   6361: 
                   6362: The final example in this section is intended to remind you that space
                   6363: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6364: both read and written by a Standard program@footnote{Exercise: use this
                   6365: example as a starting point for your own implementation of @code{Value}
                   6366: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6367: @code{[']}.}:
                   6368: 
                   6369: @example
                   6370: : foo ( "name" -- )
                   6371:     CREATE -1 ,
                   6372: DOES> ( -- )
1.33      anton    6373:     @@ . ;
1.29      crook    6374: 
                   6375: foo first-word
                   6376: foo second-word
                   6377: 
                   6378: 123 ' first-word >BODY !
                   6379: @end example
                   6380: 
                   6381: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6382: have executed it to get the address of its data field. However, since it
                   6383: was defined to have @code{DOES>} actions, its execution semantics are to
                   6384: perform those @code{DOES>} actions. To get the address of its data field
                   6385: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6386: translate the xt into the address of the data field.  When you execute
                   6387: @code{first-word}, it will display @code{123}. When you execute
                   6388: @code{second-word} it will display @code{-1}.
1.26      crook    6389: 
                   6390: @cindex stack effect of @code{DOES>}-parts
                   6391: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6392: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6393: the stack effect of the defined words, not the stack effect of the
                   6394: following code (the following code expects the address of the body on
                   6395: the top of stack, which is not reflected in the stack comment). This is
                   6396: the convention that I use and recommend (it clashes a bit with using
                   6397: locals declarations for stack effect specification, though).
1.1       anton    6398: 
1.53      anton    6399: @menu
                   6400: * CREATE..DOES> applications::  
                   6401: * CREATE..DOES> details::       
1.63      anton    6402: * Advanced does> usage example::  
1.53      anton    6403: @end menu
                   6404: 
                   6405: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26      crook    6406: @subsubsection Applications of @code{CREATE..DOES>}
                   6407: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6408: 
1.26      crook    6409: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6410: 
1.26      crook    6411: @cindex factoring similar colon definitions
                   6412: When you see a sequence of code occurring several times, and you can
                   6413: identify a meaning, you will factor it out as a colon definition. When
                   6414: you see similar colon definitions, you can factor them using
                   6415: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6416: that look very similar:
1.1       anton    6417: @example
1.26      crook    6418: : ori, ( reg-target reg-source n -- )
                   6419:     0 asm-reg-reg-imm ;
                   6420: : andi, ( reg-target reg-source n -- )
                   6421:     1 asm-reg-reg-imm ;
1.1       anton    6422: @end example
                   6423: 
1.26      crook    6424: @noindent
                   6425: This could be factored with:
                   6426: @example
                   6427: : reg-reg-imm ( op-code -- )
                   6428:     CREATE ,
                   6429: DOES> ( reg-target reg-source n -- )
                   6430:     @@ asm-reg-reg-imm ;
                   6431: 
                   6432: 0 reg-reg-imm ori,
                   6433: 1 reg-reg-imm andi,
                   6434: @end example
1.1       anton    6435: 
1.26      crook    6436: @cindex currying
                   6437: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6438: supply a part of the parameters for a word (known as @dfn{currying} in
                   6439: the functional language community). E.g., @code{+} needs two
                   6440: parameters. Creating versions of @code{+} with one parameter fixed can
                   6441: be done like this:
1.1       anton    6442: @example
1.26      crook    6443: : curry+ ( n1 -- )
                   6444:     CREATE ,
                   6445: DOES> ( n2 -- n1+n2 )
                   6446:     @@ + ;
                   6447: 
                   6448:  3 curry+ 3+
                   6449: -2 curry+ 2-
1.1       anton    6450: @end example
                   6451: 
1.63      anton    6452: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6453: @subsubsection The gory details of @code{CREATE..DOES>}
                   6454: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6455: 
1.26      crook    6456: doc-does>
1.1       anton    6457: 
1.26      crook    6458: @cindex @code{DOES>} in a separate definition
                   6459: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6460: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6461: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6462: @example
                   6463: : does1 
                   6464: DOES> ( ... -- ... )
1.44      crook    6465:     ... ;
                   6466: 
                   6467: : does2
                   6468: DOES> ( ... -- ... )
                   6469:     ... ;
                   6470: 
                   6471: : def-word ( ... -- ... )
                   6472:     create ...
                   6473:     IF
                   6474:        does1
                   6475:     ELSE
                   6476:        does2
                   6477:     ENDIF ;
                   6478: @end example
                   6479: 
                   6480: In this example, the selection of whether to use @code{does1} or
                   6481: @code{does2} is made at compile-time; at the time that the child word is
                   6482: @code{CREATE}d.
                   6483: 
                   6484: @cindex @code{DOES>} in interpretation state
                   6485: In a standard program you can apply a @code{DOES>}-part only if the last
                   6486: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6487: will override the behaviour of the last word defined in any case. In a
                   6488: standard program, you can use @code{DOES>} only in a colon
                   6489: definition. In Gforth, you can also use it in interpretation state, in a
                   6490: kind of one-shot mode; for example:
                   6491: @example
                   6492: CREATE name ( ... -- ... )
                   6493:   @i{initialization}
                   6494: DOES>
                   6495:   @i{code} ;
                   6496: @end example
                   6497: 
                   6498: @noindent
                   6499: is equivalent to the standard:
                   6500: @example
                   6501: :noname
                   6502: DOES>
                   6503:     @i{code} ;
                   6504: CREATE name EXECUTE ( ... -- ... )
                   6505:     @i{initialization}
                   6506: @end example
                   6507: 
1.53      anton    6508: doc->body
                   6509: 
1.63      anton    6510: @node Advanced does> usage example,  , CREATE..DOES> details, User-defined Defining Words
                   6511: @subsubsection Advanced does> usage example
                   6512: 
                   6513: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
                   6514: for disassembling instructions, that follow a very repetetive scheme:
                   6515: 
                   6516: @example
                   6517: :noname @var{disasm-operands} s" @var{inst-name}" type ;
                   6518: @var{entry-num} cells @var{table} + !
                   6519: @end example
                   6520: 
                   6521: Of course, this inspires the idea to factor out the commonalities to
                   6522: allow a definition like
                   6523: 
                   6524: @example
                   6525: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
                   6526: @end example
                   6527: 
                   6528: The parameters @var{disasm-operands} and @var{table} are usually
                   6529: correlated.  Moreover, there existed code defining instructions like
                   6530: this:
                   6531: 
                   6532: @example
                   6533: @var{entry-num} @var{inst-format} @var{inst-name}
                   6534: @end example
                   6535: 
                   6536: This code comes from the assembler and resides in
                   6537: @file{arch/mips/insts.fs}.
                   6538: 
                   6539: So I had to define the @var{inst-format} words that performed the scheme
                   6540: above when executed.  At first I chose to use run-time code-generation:
                   6541: 
                   6542: @example
                   6543: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
                   6544:   :noname Postpone @var{disasm-operands}
                   6545:   name Postpone sliteral Postpone type Postpone ;
                   6546:   swap cells @var{table} + ! ;
                   6547: @end example
                   6548: 
                   6549: Note that this supplies the other two parameters of the scheme above.
1.44      crook    6550: 
1.63      anton    6551: An alternative would have been to write this using
                   6552: @code{create}/@code{does>}:
                   6553: 
                   6554: @example
                   6555: : @var{inst-format} ( entry-num "name" -- )
                   6556:   here name string, ( entry-num c-addr ) \ parse and save "name"
                   6557:   noname create , ( entry-num )
                   6558:   lastxt swap cells @var{table} + !
                   6559: does> ( addr w -- )
                   6560:   \ disassemble instruction w at addr
                   6561:   @@ >r 
                   6562:   @var{disasm-operands}
                   6563:   r> count type ;
                   6564: @end example
                   6565: 
                   6566: Somehow the first solution is simpler, mainly because it's simpler to
                   6567: shift a string from definition-time to use-time with @code{sliteral}
                   6568: than with @code{string,} and friends.
                   6569: 
                   6570: I wrote a lot of words following this scheme and soon thought about
                   6571: factoring out the commonalities among them.  Note that this uses a
                   6572: two-level defining word, i.e., a word that defines ordinary defining
                   6573: words.
                   6574: 
                   6575: This time a solution involving @code{postpone} and friends seemed more
                   6576: difficult (try it as an exercise), so I decided to use a
                   6577: @code{create}/@code{does>} word; since I was already at it, I also used
                   6578: @code{create}/@code{does>} for the lower level (try using
                   6579: @code{postpone} etc. as an exercise), resulting in the following
                   6580: definition:
                   6581: 
                   6582: @example
                   6583: : define-format ( disasm-xt table-xt -- )
                   6584:     \ define an instruction format that uses disasm-xt for
                   6585:     \ disassembling and enters the defined instructions into table
                   6586:     \ table-xt
                   6587:     create 2,
                   6588: does> ( u "inst" -- )
                   6589:     \ defines an anonymous word for disassembling instruction inst,
                   6590:     \ and enters it as u-th entry into table-xt
                   6591:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
                   6592:     noname create 2,      \ define anonymous word
                   6593:     execute lastxt swap ! \ enter xt of defined word into table-xt
                   6594: does> ( addr w -- )
                   6595:     \ disassemble instruction w at addr
                   6596:     2@@ >r ( addr w disasm-xt R: c-addr )
                   6597:     execute ( R: c-addr ) \ disassemble operands
                   6598:     r> count type ; \ print name 
                   6599: @end example
                   6600: 
                   6601: Note that the tables here (in contrast to above) do the @code{cells +}
                   6602: by themselves (that's why you have to pass an xt).  This word is used in
                   6603: the following way:
                   6604: 
                   6605: @example
                   6606: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
                   6607: @end example
                   6608: 
                   6609: In terms of currying, this kind of two-level defining word provides the
                   6610: parameters in three stages: first @var{disasm-operands} and @var{table},
                   6611: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
                   6612: the instruction to be disassembled.  
                   6613: 
                   6614: Of course this did not quite fit all the instruction format names used
                   6615: in @file{insts.fs}, so I had to define a few wrappers that conditioned
                   6616: the parameters into the right form.
                   6617: 
                   6618: If you have trouble following this section, don't worry.  First, this is
                   6619: involved and takes time (and probably some playing around) to
                   6620: understand; second, this is the first two-level
                   6621: @code{create}/@code{does>} word I have written in seventeen years of
                   6622: Forth; and if I did not have @file{insts.fs} to start with, I may well
                   6623: have elected to use just a one-level defining word (with some repeating
                   6624: of parameters when using the defining word). So it is not necessary to
                   6625: understand this, but it may improve your understanding of Forth.
1.44      crook    6626: 
                   6627: 
                   6628: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
                   6629: @subsection Deferred words
                   6630: @cindex deferred words
                   6631: 
                   6632: The defining word @code{Defer} allows you to define a word by name
                   6633: without defining its behaviour; the definition of its behaviour is
                   6634: deferred. Here are two situation where this can be useful:
                   6635: 
                   6636: @itemize @bullet
                   6637: @item
                   6638: Where you want to allow the behaviour of a word to be altered later, and
                   6639: for all precompiled references to the word to change when its behaviour
                   6640: is changed.
                   6641: @item
                   6642: For mutual recursion; @xref{Calls and returns}.
                   6643: @end itemize
                   6644: 
                   6645: In the following example, @code{foo} always invokes the version of
                   6646: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6647: always invokes the version that prints ``@code{Hello}''. There is no way
                   6648: of getting @code{foo} to use the later version without re-ordering the
                   6649: source code and recompiling it.
                   6650: 
                   6651: @example
                   6652: : greet ." Good morning" ;
                   6653: : foo ... greet ... ;
                   6654: : greet ." Hello" ;
                   6655: : bar ... greet ... ;
                   6656: @end example
                   6657: 
                   6658: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6659: word. The behaviour of a @code{Defer}red word can be defined and
                   6660: redefined at any time by using @code{IS} to associate the xt of a
                   6661: previously-defined word with it. The previous example becomes:
                   6662: 
                   6663: @example
                   6664: Defer greet
                   6665: : foo ... greet ... ;
                   6666: : bar ... greet ... ;
                   6667: : greet1 ." Good morning" ;
                   6668: : greet2 ." Hello" ;
                   6669: ' greet2 <IS> greet  \ make greet behave like greet2
                   6670: @end example
                   6671: 
                   6672: A deferred word can be used to improve the statistics-gathering example
                   6673: from @ref{User-defined Defining Words}; rather than edit the
                   6674: application's source code to change every @code{:} to a @code{my:}, do
                   6675: this:
                   6676: 
                   6677: @example
                   6678: : real: : ;     \ retain access to the original
                   6679: defer :         \ redefine as a deferred word
                   6680: ' my: IS :      \ use special version of :
                   6681: \
                   6682: \ load application here
                   6683: \
                   6684: ' real: IS :    \ go back to the original
                   6685: @end example
                   6686: 
                   6687: 
                   6688: One thing to note is that @code{<IS>} consumes its name when it is
                   6689: executed.  If you want to specify the name at compile time, use
                   6690: @code{[IS]}:
                   6691: 
                   6692: @example
                   6693: : set-greet ( xt -- )
                   6694:   [IS] greet ;
                   6695: 
                   6696: ' greet1 set-greet
                   6697: @end example
                   6698: 
                   6699: A deferred word can only inherit default semantics from the xt (because
1.49      anton    6700: that is all that an xt can represent -- for more discussion of this
                   6701: @pxref{Tokens for Words}). However, the semantics of the deferred word
1.44      crook    6702: itself can be modified at the time that it is defined. For example:
                   6703: 
                   6704: @example
                   6705: : bar .... ; compile-only
                   6706: Defer fred immediate
                   6707: Defer jim
                   6708: 
                   6709: ' bar <IS> jim  \ jim has default semantics
                   6710: ' bar <IS> fred \ fred is immediate
                   6711: @end example
                   6712: 
                   6713: doc-defer
                   6714: doc-<is>
                   6715: doc-[is]
                   6716: doc-is
                   6717: @comment TODO document these: what's defers [is]
                   6718: doc-what's
                   6719: doc-defers
                   6720: 
                   6721: @c Use @code{words-deferred} to see a list of deferred words.
                   6722: 
                   6723: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
                   6724: are provided in @file{compat/defer.fs}.
                   6725: 
                   6726: 
                   6727: @node Aliases, Supplying names, Deferred words, Defining Words
                   6728: @subsection Aliases
                   6729: @cindex aliases
1.1       anton    6730: 
1.44      crook    6731: The defining word @code{Alias} allows you to define a word by name that
                   6732: has the same behaviour as some other word. Here are two situation where
                   6733: this can be useful:
1.1       anton    6734: 
1.44      crook    6735: @itemize @bullet
                   6736: @item
                   6737: When you want access to a word's definition from a different word list
                   6738: (for an example of this, see the definition of the @code{Root} word list
                   6739: in the Gforth source).
                   6740: @item
                   6741: When you want to create a synonym; a definition that can be known by
                   6742: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   6743: aliases).
                   6744: @end itemize
1.1       anton    6745: 
1.44      crook    6746: The word whose behaviour the alias is to inherit is represented by an
                   6747: xt. Therefore, the alias only inherits default semantics from its
                   6748: ancestor. The semantics of the alias itself can be modified at the time
                   6749: that it is defined. For example:
1.1       anton    6750: 
                   6751: @example
1.44      crook    6752: : foo ... ; immediate
                   6753: 
                   6754: ' foo Alias bar \ bar is not an immediate word
                   6755: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    6756: @end example
                   6757: 
1.44      crook    6758: Words that are aliases have the same xt, different headers in the
                   6759: dictionary, and consequently different name tokens (@pxref{Tokens for
                   6760: Words}) and possibly different immediate flags.  An alias can only have
                   6761: default or immediate compilation semantics; you can define aliases for
                   6762: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    6763: 
1.44      crook    6764: doc-alias
1.26      crook    6765: 
1.1       anton    6766: 
1.52      anton    6767: @node Supplying names,  , Aliases, Defining Words
1.29      crook    6768: @subsection Supplying the name of a defined word
1.26      crook    6769: @cindex names for defined words
1.44      crook    6770: @cindex defining words, name given in a string
1.1       anton    6771: 
1.29      crook    6772: By default, a defining word takes the name for the defined word from the
1.26      crook    6773: input stream. Sometimes you want to supply the name from a string. You
                   6774: can do this with:
1.1       anton    6775: 
1.26      crook    6776: doc-nextname
1.1       anton    6777: 
1.26      crook    6778: For example:
1.1       anton    6779: 
1.26      crook    6780: @example
                   6781: s" foo" nextname create
                   6782: @end example
1.44      crook    6783: 
1.26      crook    6784: @noindent
                   6785: is equivalent to:
1.44      crook    6786: 
1.26      crook    6787: @example
                   6788: create foo
                   6789: @end example
1.1       anton    6790: 
1.29      crook    6791: @noindent
1.44      crook    6792: @code{nextname} works with any defining word, not just @code{:}.
1.1       anton    6793: 
                   6794: 
1.47      crook    6795: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   6796: @section Interpretation and Compilation Semantics
1.26      crook    6797: @cindex semantics, interpretation and compilation
1.1       anton    6798: 
1.26      crook    6799: @cindex interpretation semantics
                   6800: The @dfn{interpretation semantics} of a word are what the text
                   6801: interpreter does when it encounters the word in interpret state. It also
                   6802: appears in some other contexts, e.g., the execution token returned by
1.29      crook    6803: @code{' @i{word}} identifies the interpretation semantics of
                   6804: @i{word} (in other words, @code{' @i{word} execute} is equivalent to
                   6805: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    6806: 
1.26      crook    6807: @cindex compilation semantics
                   6808: The @dfn{compilation semantics} of a word are what the text interpreter
                   6809: does when it encounters the word in compile state. It also appears in
1.29      crook    6810: other contexts, e.g, @code{POSTPONE @i{word}} compiles@footnote{In
1.26      crook    6811: standard terminology, ``appends to the current definition''.} the
1.29      crook    6812: compilation semantics of @i{word}.
1.1       anton    6813: 
1.26      crook    6814: @cindex execution semantics
                   6815: The standard also talks about @dfn{execution semantics}. They are used
                   6816: only for defining the interpretation and compilation semantics of many
                   6817: words. By default, the interpretation semantics of a word are to
                   6818: @code{execute} its execution semantics, and the compilation semantics of
                   6819: a word are to @code{compile,} its execution semantics.@footnote{In
                   6820: standard terminology: The default interpretation semantics are its
                   6821: execution semantics; the default compilation semantics are to append its
                   6822: execution semantics to the execution semantics of the current
                   6823: definition.}
                   6824: 
                   6825: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   6826: 
                   6827: @cindex immediate words
                   6828: @cindex compile-only words
                   6829: You can change the semantics of the most-recently defined word:
                   6830: 
1.44      crook    6831: 
1.26      crook    6832: doc-immediate
                   6833: doc-compile-only
                   6834: doc-restrict
                   6835: 
1.44      crook    6836: 
1.26      crook    6837: Note that ticking (@code{'}) a compile-only word gives an error
                   6838: (``Interpreting a compile-only word'').
1.1       anton    6839: 
1.47      crook    6840: @menu
                   6841: * Combined words::
                   6842: @end menu
1.44      crook    6843: 
1.48      anton    6844: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    6845: @subsection Combined Words
                   6846: @cindex combined words
                   6847: 
                   6848: Gforth allows you to define @dfn{combined words} -- words that have an
                   6849: arbitrary combination of interpretation and compilation semantics.
                   6850: 
1.1       anton    6851: 
1.26      crook    6852: doc-interpret/compile:
1.1       anton    6853: 
1.44      crook    6854: 
1.26      crook    6855: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   6856: recommend that you do not define such words, as cute as they may be:
                   6857: they make it hard to get at both parts of the word in some contexts.
                   6858: E.g., assume you want to get an execution token for the compilation
                   6859: part. Instead, define two words, one that embodies the interpretation
                   6860: part, and one that embodies the compilation part.  Once you have done
                   6861: that, you can define a combined word with @code{interpret/compile:} for
                   6862: the convenience of your users.
1.1       anton    6863: 
1.26      crook    6864: You might try to use this feature to provide an optimizing
                   6865: implementation of the default compilation semantics of a word. For
                   6866: example, by defining:
1.1       anton    6867: @example
1.26      crook    6868: :noname
                   6869:    foo bar ;
                   6870: :noname
                   6871:    POSTPONE foo POSTPONE bar ;
1.29      crook    6872: interpret/compile: opti-foobar
1.1       anton    6873: @end example
1.26      crook    6874: 
1.23      crook    6875: @noindent
1.26      crook    6876: as an optimizing version of:
                   6877: 
1.1       anton    6878: @example
1.26      crook    6879: : foobar
                   6880:     foo bar ;
1.1       anton    6881: @end example
                   6882: 
1.26      crook    6883: Unfortunately, this does not work correctly with @code{[compile]},
                   6884: because @code{[compile]} assumes that the compilation semantics of all
                   6885: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    6886: opti-foobar} would compile compilation semantics, whereas
                   6887: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    6888: 
1.26      crook    6889: @cindex state-smart words (are a bad idea)
1.29      crook    6890: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    6891: by @code{interpret/compile:} (words are state-smart if they check
                   6892: @code{STATE} during execution). E.g., they would try to code
                   6893: @code{foobar} like this:
1.1       anton    6894: 
1.26      crook    6895: @example
                   6896: : foobar
                   6897:   STATE @@
                   6898:   IF ( compilation state )
                   6899:     POSTPONE foo POSTPONE bar
                   6900:   ELSE
                   6901:     foo bar
                   6902:   ENDIF ; immediate
                   6903: @end example
1.1       anton    6904: 
1.26      crook    6905: Although this works if @code{foobar} is only processed by the text
                   6906: interpreter, it does not work in other contexts (like @code{'} or
                   6907: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   6908: for a state-smart word, not for the interpretation semantics of the
                   6909: original @code{foobar}; when you execute this execution token (directly
                   6910: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   6911: state, the result will not be what you expected (i.e., it will not
                   6912: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   6913: write them@footnote{For a more detailed discussion of this topic, see
1.66    ! anton    6914: M. Anton Ertl,
        !          6915: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
        !          6916: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1       anton    6917: 
1.26      crook    6918: @cindex defining words with arbitrary semantics combinations
                   6919: It is also possible to write defining words that define words with
                   6920: arbitrary combinations of interpretation and compilation semantics. In
                   6921: general, they look like this:
1.1       anton    6922: 
1.26      crook    6923: @example
                   6924: : def-word
                   6925:     create-interpret/compile
1.29      crook    6926:     @i{code1}
1.26      crook    6927: interpretation>
1.29      crook    6928:     @i{code2}
1.26      crook    6929: <interpretation
                   6930: compilation>
1.29      crook    6931:     @i{code3}
1.26      crook    6932: <compilation ;
                   6933: @end example
1.1       anton    6934: 
1.29      crook    6935: For a @i{word} defined with @code{def-word}, the interpretation
                   6936: semantics are to push the address of the body of @i{word} and perform
                   6937: @i{code2}, and the compilation semantics are to push the address of
                   6938: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    6939: can also be defined like this (except that the defined constants don't
                   6940: behave correctly when @code{[compile]}d):
1.1       anton    6941: 
1.26      crook    6942: @example
                   6943: : constant ( n "name" -- )
                   6944:     create-interpret/compile
                   6945:     ,
                   6946: interpretation> ( -- n )
                   6947:     @@
                   6948: <interpretation
                   6949: compilation> ( compilation. -- ; run-time. -- n )
                   6950:     @@ postpone literal
                   6951: <compilation ;
                   6952: @end example
1.1       anton    6953: 
1.44      crook    6954: 
1.26      crook    6955: doc-create-interpret/compile
                   6956: doc-interpretation>
                   6957: doc-<interpretation
                   6958: doc-compilation>
                   6959: doc-<compilation
1.1       anton    6960: 
1.44      crook    6961: 
1.29      crook    6962: Words defined with @code{interpret/compile:} and
1.26      crook    6963: @code{create-interpret/compile} have an extended header structure that
                   6964: differs from other words; however, unless you try to access them with
                   6965: plain address arithmetic, you should not notice this. Words for
                   6966: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    6967: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   6968: with @code{create-interpret/compile}.
1.1       anton    6969: 
1.44      crook    6970: 
1.27      crook    6971: doc-postpone
1.44      crook    6972: 
1.29      crook    6973: @comment TODO -- expand glossary text for POSTPONE
1.27      crook    6974: 
1.47      crook    6975: 
                   6976: @c -------------------------------------------------------------
                   6977: @node Tokens for Words, The Text Interpreter, Interpretation and Compilation Semantics, Words
                   6978: @section Tokens for Words
                   6979: @cindex tokens for words
                   6980: 
                   6981: This section describes the creation and use of tokens that represent
                   6982: words.
                   6983: 
                   6984: Named words have information stored in their header space entries to
                   6985: indicate any non-default semantics (@pxref{Interpretation and
                   6986: Compilation Semantics}). The semantics can be modified, using
                   6987: @code{immediate} and/or @code{compile-only}, at the time that the words
                   6988: are defined. Unnamed words have (by definition) no header space
                   6989: entry, and therefore must have default semantics.
                   6990: 
                   6991: Named words have interpretation and compilation semantics. Unnamed words
                   6992: just have execution semantics.
                   6993: 
                   6994: @cindex xt
                   6995: @cindex execution token
                   6996: The execution semantics of an unnamed word are represented by an
                   6997: @dfn{execution token} (@i{xt}). As explained in @ref{Supplying names},
                   6998: the execution token of the last word defined can be produced with
                   6999: @code{lastxt}.
                   7000: 
                   7001: The interpretation semantics of a named word are also represented by an
                   7002: execution token. You can produce the execution token using @code{'} or
                   7003: @code{[']}. A simple example shows the difference between the two:
                   7004: 
                   7005: @example
                   7006: : greet ( -- )   ." Hello" ;
                   7007: : foo ( -- xt )  ['] greet execute ; \ ['] parses greet at compile-time
                   7008: : bar ( -- )     ' execute ; \  '  parses at run-time
                   7009: 
                   7010: \ the next four lines all do the same thing
                   7011: foo
                   7012: bar greet
                   7013: greet
                   7014: ' greet EXECUTE
                   7015: @end example
                   7016: 
                   7017: An execution token occupies one cell.
                   7018: @cindex code field address
                   7019: @cindex CFA
                   7020: In Gforth, the abstract data type @i{execution token} is implemented
                   7021: as a code field address (CFA).
                   7022: @comment TODO note that the standard does not say what it represents..
                   7023: @comment and you cannot necessarily compile it in all Forths (eg native
                   7024: @comment compilers?).
                   7025: 
                   7026: For literals, use @code{'} in interpreted code and @code{[']} in
                   7027: compiled code. Gforth's @code{'} and @code{[']} behave somewhat
                   7028: unusually by complaining about compile-only words. To get the execution
                   7029: token for a compile-only word @i{name}, use @code{COMP' @i{name} DROP}
                   7030: or @code{[COMP'] @i{name} DROP}.
                   7031: 
                   7032: @cindex compilation token
                   7033: The compilation semantics of a named word are represented by a
                   7034: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   7035: @i{xt} is an execution token. The compilation semantics represented by
                   7036: the compilation token can be performed with @code{execute}, which
                   7037: consumes the whole compilation token, with an additional stack effect
                   7038: determined by the represented compilation semantics.
                   7039: 
                   7040: At present, the @i{w} part of a compilation token is an execution token,
                   7041: and the @i{xt} part represents either @code{execute} or
                   7042: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   7043: word. If the word has default compilation semantics, the @i{xt} will
                   7044: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   7045: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   7046: knowledge, unless necessary; future versions of Gforth may introduce
                   7047: unusual compilation tokens (e.g., a compilation token that represents
                   7048: the compilation semantics of a literal).
                   7049: 
                   7050: You can compile the compilation semantics with @code{postpone,}. I.e.,
                   7051: @code{COMP' @i{word} postpone,} is equivalent to @code{postpone
                   7052: @i{word}}.
                   7053: 
                   7054: @cindex name token
                   7055: @cindex name field address
                   7056: @cindex NFA
                   7057: Named words are also represented by the @dfn{name token}, (@i{nt}). In
                   7058: Gforth, the abstract data type @emph{name token} is implemented as a
                   7059: name field address (NFA).
                   7060: 
                   7061: 
                   7062: doc-execute
                   7063: doc-perform
                   7064: doc-compile,
                   7065: doc-[']
                   7066: doc-'
                   7067: doc-[comp']
                   7068: doc-comp'
                   7069: doc-postpone,
                   7070: 
                   7071: doc-find-name
                   7072: doc-name>int
                   7073: doc-name?int
                   7074: doc-name>comp
                   7075: doc-name>string
                   7076: 
                   7077: 
1.26      crook    7078: @c ----------------------------------------------------------
1.47      crook    7079: @node The Text Interpreter, Word Lists, Tokens for Words, Words
1.26      crook    7080: @section  The Text Interpreter
                   7081: @cindex interpreter - outer
                   7082: @cindex text interpreter
                   7083: @cindex outer interpreter
1.1       anton    7084: 
1.34      anton    7085: @c Should we really describe all these ugly details?  IMO the text
                   7086: @c interpreter should be much cleaner, but that may not be possible within
                   7087: @c ANS Forth. - anton
1.44      crook    7088: @c nac-> I wanted to explain how it works to show how you can exploit
                   7089: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   7090: @c some of these gory details was very helpful to me. None of the textbooks
                   7091: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   7092: @c seems to positively avoid going into too much detail for some of
                   7093: @c the internals.
1.34      anton    7094: 
1.29      crook    7095: The text interpreter@footnote{This is an expanded version of the
                   7096: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    7097: that processes input from the current input device. It is also called
                   7098: the outer interpreter, in contrast to the inner interpreter
                   7099: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   7100: implementations.
1.27      crook    7101: 
1.29      crook    7102: @cindex interpret state
                   7103: @cindex compile state
                   7104: The text interpreter operates in one of two states: @dfn{interpret
                   7105: state} and @dfn{compile state}. The current state is defined by the
                   7106: aptly-named variable, @code{state}.
                   7107: 
                   7108: This section starts by describing how the text interpreter behaves when
                   7109: it is in interpret state, processing input from the user input device --
                   7110: the keyboard. This is the mode that a Forth system is in after it starts
                   7111: up.
                   7112: 
                   7113: @cindex input buffer
                   7114: @cindex terminal input buffer
                   7115: The text interpreter works from an area of memory called the @dfn{input
                   7116: buffer}@footnote{When the text interpreter is processing input from the
                   7117: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   7118: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   7119: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    7120: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    7121: leading spaces (called @dfn{delimiters}) then parses a string (a
                   7122: sequence of non-space characters) until it reaches either a space
                   7123: character or the end of the buffer. Having parsed a string, it makes two
                   7124: attempts to process it:
1.27      crook    7125: 
1.29      crook    7126: @cindex dictionary
1.27      crook    7127: @itemize @bullet
                   7128: @item
1.29      crook    7129: It looks for the string in a @dfn{dictionary} of definitions. If the
                   7130: string is found, the string names a @dfn{definition} (also known as a
                   7131: @dfn{word}) and the dictionary search returns information that allows
                   7132: the text interpreter to perform the word's @dfn{interpretation
                   7133: semantics}. In most cases, this simply means that the word will be
                   7134: executed.
1.27      crook    7135: @item
                   7136: If the string is not found in the dictionary, the text interpreter
1.29      crook    7137: attempts to treat it as a number, using the rules described in
                   7138: @ref{Number Conversion}. If the string represents a legal number in the
                   7139: current radix, the number is pushed onto a parameter stack (the data
                   7140: stack for integers, the floating-point stack for floating-point
                   7141: numbers).
                   7142: @end itemize
                   7143: 
                   7144: If both attempts fail, or if the word is found in the dictionary but has
                   7145: no interpretation semantics@footnote{This happens if the word was
                   7146: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   7147: remainder of the input buffer, issues an error message and waits for
                   7148: more input. If one of the attempts succeeds, the text interpreter
                   7149: repeats the parsing process until the whole of the input buffer has been
                   7150: processed, at which point it prints the status message ``@code{ ok}''
                   7151: and waits for more input.
                   7152: 
                   7153: @cindex parse area
                   7154: The text interpreter keeps track of its position in the input buffer by
                   7155: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   7156: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   7157: of the input buffer. The region from offset @code{>IN @@} to the end of
                   7158: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   7159: the text interpreter processes the contents of the input buffer by
                   7160: parsing strings from the parse area until the parse area is empty.}.
                   7161: This example shows how @code{>IN} changes as the text interpreter parses
                   7162: the input buffer:
                   7163: 
                   7164: @example
                   7165: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   7166:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   7167: 
                   7168: 1 2 3 remaining + remaining . 
                   7169: 
                   7170: : foo 1 2 3 remaining SWAP remaining ;
                   7171: @end example
                   7172: 
                   7173: @noindent
                   7174: The result is:
                   7175: 
                   7176: @example
                   7177: ->+ remaining .<-
                   7178: ->.<-5  ok
                   7179: 
                   7180: ->SWAP remaining ;-<
                   7181: ->;<-  ok
                   7182: @end example
                   7183: 
                   7184: @cindex parsing words
                   7185: The value of @code{>IN} can also be modified by a word in the input
                   7186: buffer that is executed by the text interpreter.  This means that a word
                   7187: can ``trick'' the text interpreter into either skipping a section of the
                   7188: input buffer@footnote{This is how parsing words work.} or into parsing a
                   7189: section twice. For example:
1.27      crook    7190: 
1.29      crook    7191: @example
                   7192: : lat ." <<lat>>" ;
                   7193: : flat ." <<flat>>" >IN DUP @@ 3 - SWAP ! ;
                   7194: @end example
                   7195: 
                   7196: @noindent
                   7197: When @code{flat} is executed, this output is produced@footnote{Exercise
                   7198: for the reader: what would happen if the @code{3} were replaced with
                   7199: @code{4}?}:
                   7200: 
                   7201: @example
                   7202: <<flat>><<lat>>
                   7203: @end example
                   7204: 
                   7205: @noindent
                   7206: Two important notes about the behaviour of the text interpreter:
1.27      crook    7207: 
                   7208: @itemize @bullet
                   7209: @item
                   7210: It processes each input string to completion before parsing additional
1.29      crook    7211: characters from the input buffer.
                   7212: @item
                   7213: It treats the input buffer as a read-only region (and so must your code).
                   7214: @end itemize
                   7215: 
                   7216: @noindent
                   7217: When the text interpreter is in compile state, its behaviour changes in
                   7218: these ways:
                   7219: 
                   7220: @itemize @bullet
                   7221: @item
                   7222: If a parsed string is found in the dictionary, the text interpreter will
                   7223: perform the word's @dfn{compilation semantics}. In most cases, this
                   7224: simply means that the execution semantics of the word will be appended
                   7225: to the current definition.
1.27      crook    7226: @item
1.29      crook    7227: When a number is encountered, it is compiled into the current definition
                   7228: (as a literal) rather than being pushed onto a parameter stack.
                   7229: @item
                   7230: If an error occurs, @code{state} is modified to put the text interpreter
                   7231: back into interpret state.
                   7232: @item
                   7233: Each time a line is entered from the keyboard, Gforth prints
                   7234: ``@code{ compiled}'' rather than `` @code{ok}''.
                   7235: @end itemize
                   7236: 
                   7237: @cindex text interpreter - input sources
                   7238: When the text interpreter is using an input device other than the
                   7239: keyboard, its behaviour changes in these ways:
                   7240: 
                   7241: @itemize @bullet
                   7242: @item
                   7243: When the parse area is empty, the text interpreter attempts to refill
                   7244: the input buffer from the input source. When the input source is
                   7245: exhausted, the input source is set back to the user input device.
                   7246: @item
                   7247: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7248: time the parse area is emptied.
                   7249: @item
                   7250: If an error occurs, the input source is set back to the user input
                   7251: device.
1.27      crook    7252: @end itemize
1.21      crook    7253: 
1.49      anton    7254: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7255: 
1.26      crook    7256: doc->in
1.27      crook    7257: doc-source
                   7258: 
1.26      crook    7259: doc-tib
                   7260: doc-#tib
1.1       anton    7261: 
1.44      crook    7262: 
1.26      crook    7263: @menu
1.29      crook    7264: * Input Sources::
1.26      crook    7265: * Number Conversion::
                   7266: * Interpret/Compile states::
                   7267: * Literals::
                   7268: * Interpreter Directives::
                   7269: @end menu
1.1       anton    7270: 
1.29      crook    7271: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7272: @subsection Input Sources
                   7273: @cindex input sources
                   7274: @cindex text interpreter - input sources
                   7275: 
1.44      crook    7276: By default, the text interpreter processes input from the user input
1.29      crook    7277: device (the keyboard) when Forth starts up. The text interpreter can
                   7278: process input from any of these sources:
                   7279: 
                   7280: @itemize @bullet
                   7281: @item
                   7282: The user input device -- the keyboard.
                   7283: @item
                   7284: A file, using the words described in @ref{Forth source files}.
                   7285: @item
                   7286: A block, using the words described in @ref{Blocks}.
                   7287: @item
                   7288: A text string, using @code{evaluate}.
                   7289: @end itemize
                   7290: 
                   7291: A program can identify the current input device from the values of
                   7292: @code{source-id} and @code{blk}.
                   7293: 
1.44      crook    7294: 
1.29      crook    7295: doc-source-id
                   7296: doc-blk
                   7297: 
                   7298: doc-save-input
                   7299: doc-restore-input
                   7300: 
                   7301: doc-evaluate
1.1       anton    7302: 
1.29      crook    7303: 
1.44      crook    7304: 
1.29      crook    7305: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7306: @subsection Number Conversion
                   7307: @cindex number conversion
                   7308: @cindex double-cell numbers, input format
                   7309: @cindex input format for double-cell numbers
                   7310: @cindex single-cell numbers, input format
                   7311: @cindex input format for single-cell numbers
                   7312: @cindex floating-point numbers, input format
                   7313: @cindex input format for floating-point numbers
1.1       anton    7314: 
1.29      crook    7315: This section describes the rules that the text interpreter uses when it
                   7316: tries to convert a string into a number.
1.1       anton    7317: 
1.26      crook    7318: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7319: number base@footnote{For example, 0-9 when the number base is decimal or
                   7320: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7321: 
1.26      crook    7322: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7323: 
1.29      crook    7324: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7325: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7326: 
1.26      crook    7327: Let * represent any number of instances of the previous character
                   7328: (including none).
1.1       anton    7329: 
1.26      crook    7330: Let any other character represent itself.
1.1       anton    7331: 
1.29      crook    7332: @noindent
1.26      crook    7333: Now, the conversion rules are:
1.21      crook    7334: 
1.26      crook    7335: @itemize @bullet
                   7336: @item
                   7337: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7338: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7339: @item
                   7340: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7341: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7342: arithmetic. Examples are -45 -5681 -0
                   7343: @item
                   7344: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7345: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7346: (all three of these represent the same number).
1.26      crook    7347: @item
                   7348: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7349: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7350: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7351: -34.65 (all three of these represent the same number).
1.26      crook    7352: @item
1.29      crook    7353: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7354: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7355: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7356: number) +12.E-4
1.26      crook    7357: @end itemize
1.1       anton    7358: 
1.26      crook    7359: By default, the number base used for integer number conversion is given
1.35      anton    7360: by the contents of the variable @code{base}.  Note that a lot of
                   7361: confusion can result from unexpected values of @code{base}.  If you
                   7362: change @code{base} anywhere, make sure to save the old value and restore
                   7363: it afterwards.  In general I recommend keeping @code{base} decimal, and
                   7364: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7365: 
1.29      crook    7366: doc-dpl
1.26      crook    7367: doc-base
                   7368: doc-hex
                   7369: doc-decimal
1.1       anton    7370: 
1.44      crook    7371: 
1.26      crook    7372: @cindex '-prefix for character strings
                   7373: @cindex &-prefix for decimal numbers
                   7374: @cindex %-prefix for binary numbers
                   7375: @cindex $-prefix for hexadecimal numbers
1.35      anton    7376: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7377: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7378: implementing @code{$} etc. as parsing words that process the subsequent
                   7379: number in the input stream and push it onto the stack. For example, see
                   7380: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7381: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7382: is required between the prefix and the number.} before the first digit
                   7383: of an (integer) number. Four prefixes are supported:
1.1       anton    7384: 
1.26      crook    7385: @itemize @bullet
                   7386: @item
1.35      anton    7387: @code{&} -- decimal
1.26      crook    7388: @item
1.35      anton    7389: @code{%} -- binary
1.26      crook    7390: @item
1.35      anton    7391: @code{$} -- hexadecimal
1.26      crook    7392: @item
1.35      anton    7393: @code{'} -- base @code{max-char+1}
1.26      crook    7394: @end itemize
1.1       anton    7395: 
1.26      crook    7396: Here are some examples, with the equivalent decimal number shown after
                   7397: in braces:
1.1       anton    7398: 
1.26      crook    7399: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
                   7400: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
                   7401: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
                   7402: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    7403: 
1.26      crook    7404: @cindex number conversion - traps for the unwary
1.29      crook    7405: @noindent
1.26      crook    7406: Number conversion has a number of traps for the unwary:
1.1       anton    7407: 
1.26      crook    7408: @itemize @bullet
                   7409: @item
                   7410: You cannot determine the current number base using the code sequence
1.35      anton    7411: @code{base @@ .} -- the number base is always 10 in the current number
                   7412: base. Instead, use something like @code{base @@ dec.}
1.26      crook    7413: @item
                   7414: If the number base is set to a value greater than 14 (for example,
                   7415: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   7416: it to be intepreted as either a single-precision integer or a
                   7417: floating-point number (Gforth treats it as an integer). The ambiguity
                   7418: can be resolved by explicitly stating the sign of the mantissa and/or
                   7419: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   7420: ambiguity arises; either representation will be treated as a
                   7421: floating-point number.
                   7422: @item
1.29      crook    7423: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    7424: It is used to specify file types.
                   7425: @item
                   7426: ANS Forth requires the @code{.} of a double-precision number to
                   7427: be the final character in the string. Allowing the @code{.} to be
                   7428: anywhere after the first digit is a Gforth extension.
                   7429: @item
                   7430: The number conversion process does not check for overflow.
                   7431: @item
                   7432: In Gforth, number conversion to floating-point numbers always use base
1.35      anton    7433: 10, irrespective of the value of @code{base}. In ANS Forth,
1.26      crook    7434: conversion to floating-point numbers whilst the value of
1.35      anton    7435: @code{base} is not 10 is an ambiguous condition.
1.26      crook    7436: @end itemize
1.1       anton    7437: 
1.49      anton    7438: You can read numbers into your programs with the words described in
                   7439: @ref{Input}.
1.1       anton    7440: 
1.26      crook    7441: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
                   7442: @subsection Interpret/Compile states
                   7443: @cindex Interpret/Compile states
1.1       anton    7444: 
1.29      crook    7445: A standard program is not permitted to change @code{state}
                   7446: explicitly. However, it can change @code{state} implicitly, using the
                   7447: words @code{[} and @code{]}. When @code{[} is executed it switches
                   7448: @code{state} to interpret state, and therefore the text interpreter
                   7449: starts interpreting. When @code{]} is executed it switches @code{state}
                   7450: to compile state and therefore the text interpreter starts
1.44      crook    7451: compiling. The most common usage for these words is for switching into
                   7452: interpret state and back from within a colon definition; this technique
1.49      anton    7453: can be used to compile a literal (for an example, @pxref{Literals}) or
                   7454: for conditional compilation (for an example, @pxref{Interpreter
                   7455: Directives}).
1.44      crook    7456: 
1.35      anton    7457: 
                   7458: @c This is a bad example: It's non-standard, and it's not necessary.
                   7459: @c However, I can't think of a good example for switching into compile
                   7460: @c state when there is no current word (@code{state}-smart words are not a
                   7461: @c good reason).  So maybe we should use an example for switching into
                   7462: @c interpret @code{state} in a colon def. - anton
1.44      crook    7463: @c nac-> I agree. I started out by putting in the example, then realised
                   7464: @c that it was non-ANS, so wrote more words around it. I hope this
                   7465: @c re-written version is acceptable to you. I do want to keep the example
                   7466: @c as it is helpful for showing what is and what is not portable, particularly
                   7467: @c where it outlaws a style in common use.
                   7468: 
1.35      anton    7469: 
1.44      crook    7470: @code{[} and @code{]} also give you the ability to switch into compile
                   7471: state and back, but we cannot think of any useful Standard application
                   7472: for this ability. Pre-ANS Forth textbooks have examples like this:
1.29      crook    7473: 
                   7474: @example
                   7475: : AA ." this is A" ;
                   7476: : BB ." this is B" ;
                   7477: : CC ." this is C" ;
                   7478: 
1.44      crook    7479: create table ] aa bb cc [
                   7480: 
1.29      crook    7481: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   7482:   cells table + @ execute ;
                   7483: @end example
                   7484: 
1.44      crook    7485: This example builds a jump table; @code{0 go} will display ``@code{this
                   7486: is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   7487: defining @code{table} like this:
1.29      crook    7488: 
                   7489: @example
1.44      crook    7490: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
1.29      crook    7491: @end example
                   7492: 
1.44      crook    7493: The problem with this code is that the definition of @code{table} is not
                   7494: portable -- it @i{compile}s execution tokens into code space. Whilst it
                   7495: @i{may} work on systems where code space and data space co-incide, the
1.29      crook    7496: Standard only allows data space to be assigned for a @code{CREATE}d
                   7497: word. In addition, the Standard only allows @code{@@} to access data
                   7498: space, whilst this example is using it to access code space. The only
                   7499: portable, Standard way to build this table is to build it in data space,
                   7500: like this:
                   7501: 
                   7502: @example
                   7503: create table ' aa , ' bb , ' cc ,
                   7504: @end example
                   7505: 
1.26      crook    7506: doc-state
                   7507: doc-[
                   7508: doc-]
1.1       anton    7509: 
1.44      crook    7510: 
1.26      crook    7511: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
                   7512: @subsection Literals
                   7513: @cindex Literals
1.21      crook    7514: 
1.29      crook    7515: Often, you want to use a number within a colon definition. When you do
                   7516: this, the text interpreter automatically compiles the number as a
                   7517: @i{literal}. A literal is a number whose run-time effect is to be pushed
                   7518: onto the stack.  If you had to do some maths to generate the number, you
                   7519: might write it like this:
                   7520: 
                   7521: @example
                   7522: : HOUR-TO-SEC ( n1 -- n2 )
                   7523:   60 *      \ to minutes
                   7524:   60 * ;    \ to seconds
                   7525: @end example
                   7526: 
                   7527: It is very clear what this definition is doing, but it's inefficient
                   7528: since it is performing 2 multiples at run-time. An alternative would be
                   7529: to write:
                   7530: 
                   7531: @example
                   7532: : HOUR-TO-SEC ( n1 -- n2 )
                   7533:   3600 * ;  \ to seconds
                   7534: @end example
                   7535: 
                   7536: Which does the same thing, and has the advantage of using a single
                   7537: multiply. Ideally, we'd like the efficiency of the second with the
                   7538: readability of the first.
                   7539: 
                   7540: @code{Literal} allows us to achieve that. It takes a number from the
                   7541: stack and lays it down in the current definition just as though the
                   7542: number had been typed directly into the definition. Our first attempt
                   7543: might look like this:
                   7544: 
                   7545: @example
                   7546: 60          \ mins per hour
                   7547: 60 *        \ seconds per minute
                   7548: : HOUR-TO-SEC ( n1 -- n2 )
                   7549:   Literal * ;  \ to seconds
                   7550: @end example
                   7551: 
                   7552: But this produces the error message @code{unstructured}. What happened?
                   7553: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
                   7554: @i{colon-sys} is implementation-defined. In other words, once we start a
                   7555: colon definition we can't portably access anything that was on the stack
                   7556: before the definition began@footnote{@cite{Two Problems in ANS Forth},
                   7557: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
                   7558: some situations where you might want to access stack items above
                   7559: colon-sys, and provides a solution to the problem.}. The correct way of
                   7560: solving this problem in this instance is to use @code{[ ]} like this:
                   7561: 
                   7562: @example
                   7563: : HOUR-TO-SEC ( n1 -- n2 )
                   7564:   [ 60          \ minutes per hour
                   7565:     60 * ]      \ seconds per minute
                   7566:   LITERAL * ;   \ to seconds
                   7567: @end example
1.23      crook    7568: 
1.44      crook    7569: 
1.26      crook    7570: doc-literal
                   7571: doc-]L
                   7572: doc-2literal
                   7573: doc-fliteral
1.1       anton    7574: 
1.44      crook    7575: 
1.48      anton    7576: @node Interpreter Directives,  , Literals, The Text Interpreter
1.26      crook    7577: @subsection Interpreter Directives
                   7578: @cindex interpreter directives
1.1       anton    7579: 
1.29      crook    7580: These words are usually used in interpret state; typically to control
                   7581: which parts of a source file are processed by the text
1.26      crook    7582: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   7583: supplements these with a rich set of immediate control structure words
                   7584: to compensate for the fact that the non-immediate versions can only be
1.29      crook    7585: used in compile state (@pxref{Control Structures}). Typical usages:
                   7586: 
                   7587: @example
                   7588: FALSE Constant ASSEMBLER
                   7589: .
                   7590: .
                   7591: ASSEMBLER [IF]
                   7592: : ASSEMBLER-FEATURE
                   7593:   ...
                   7594: ;
                   7595: [ENDIF]
                   7596: .
                   7597: .
                   7598: : SEE
                   7599:   ... \ general-purpose SEE code
                   7600:   [ ASSEMBLER [IF] ]
                   7601:   ... \ assembler-specific SEE code
                   7602:   [ [ENDIF] ]
                   7603: ;
                   7604: @end example
1.1       anton    7605: 
1.44      crook    7606: 
1.26      crook    7607: doc-[IF]
                   7608: doc-[ELSE]
                   7609: doc-[THEN]
                   7610: doc-[ENDIF]
1.1       anton    7611: 
1.26      crook    7612: doc-[IFDEF]
                   7613: doc-[IFUNDEF]
1.1       anton    7614: 
1.26      crook    7615: doc-[?DO]
                   7616: doc-[DO]
                   7617: doc-[FOR]
                   7618: doc-[LOOP]
                   7619: doc-[+LOOP]
                   7620: doc-[NEXT]
1.1       anton    7621: 
1.26      crook    7622: doc-[BEGIN]
                   7623: doc-[UNTIL]
                   7624: doc-[AGAIN]
                   7625: doc-[WHILE]
                   7626: doc-[REPEAT]
1.1       anton    7627: 
1.27      crook    7628: 
1.26      crook    7629: @c -------------------------------------------------------------
1.47      crook    7630: @node Word Lists, Environmental Queries, The Text Interpreter, Words
1.26      crook    7631: @section Word Lists
                   7632: @cindex word lists
1.32      anton    7633: @cindex header space
1.1       anton    7634: 
1.36      anton    7635: A wordlist is a list of named words; you can add new words and look up
                   7636: words by name (and you can remove words in a restricted way with
                   7637: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   7638: 
                   7639: @cindex search order stack
                   7640: The text interpreter searches the wordlists present in the search order
                   7641: (a stack of wordlists), from the top to the bottom.  Within each
                   7642: wordlist, the search starts conceptually at the newest word; i.e., if
                   7643: two words in a wordlist have the same name, the newer word is found.
1.1       anton    7644: 
1.26      crook    7645: @cindex compilation word list
1.36      anton    7646: New words are added to the @dfn{compilation wordlist} (aka current
                   7647: wordlist).
1.1       anton    7648: 
1.36      anton    7649: @cindex wid
                   7650: A word list is identified by a cell-sized word list identifier (@i{wid})
                   7651: in much the same way as a file is identified by a file handle. The
                   7652: numerical value of the wid has no (portable) meaning, and might change
                   7653: from session to session.
1.1       anton    7654: 
1.29      crook    7655: The ANS Forth ``Search order'' word set is intended to provide a set of
                   7656: low-level tools that allow various different schemes to be
1.26      crook    7657: implemented. Gforth provides @code{vocabulary}, a traditional Forth
                   7658: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    7659: Forth.
1.1       anton    7660: 
1.27      crook    7661: @comment TODO: locals section refers to here, saying that every word list (aka
                   7662: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.1       anton    7663: 
1.45      crook    7664: @comment TODO: document markers, reveal, tables, mappedwordlist
                   7665: 
                   7666: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    7667: @comment word from the source files, rather than some alias.
1.44      crook    7668: 
1.26      crook    7669: doc-forth-wordlist
                   7670: doc-definitions
                   7671: doc-get-current
                   7672: doc-set-current
                   7673: doc-get-order
1.45      crook    7674: doc---gforthman-set-order
1.26      crook    7675: doc-wordlist
1.30      anton    7676: doc-table
1.36      anton    7677: doc-push-order
                   7678: doc-previous
1.26      crook    7679: doc-also
1.45      crook    7680: doc---gforthman-forth
1.26      crook    7681: doc-only
1.45      crook    7682: doc---gforthman-order
1.15      anton    7683: 
1.26      crook    7684: doc-find
                   7685: doc-search-wordlist
1.15      anton    7686: 
1.26      crook    7687: doc-words
                   7688: doc-vlist
1.44      crook    7689: @c doc-words-deferred
1.1       anton    7690: 
1.26      crook    7691: doc-mappedwordlist
                   7692: doc-root
                   7693: doc-vocabulary
                   7694: doc-seal
                   7695: doc-vocs
                   7696: doc-current
                   7697: doc-context
1.1       anton    7698: 
1.44      crook    7699: 
1.26      crook    7700: @menu
                   7701: * Why use word lists?::
                   7702: * Word list examples::
                   7703: @end menu
                   7704: 
                   7705: @node Why use word lists?, Word list examples, Word Lists, Word Lists
                   7706: @subsection Why use word lists?
                   7707: @cindex word lists - why use them?
                   7708: 
1.29      crook    7709: Here are some reasons for using multiple word lists:
1.26      crook    7710: 
                   7711: @itemize @bullet
                   7712: @item
1.32      anton    7713: To improve compilation speed by reducing the number of header space
1.26      crook    7714: entries that must be searched. This is achieved by creating a new
                   7715: word list that contains all of the definitions that are used in the
                   7716: definition of a Forth system but which would not usually be used by
                   7717: programs running on that system. That word list would be on the search
                   7718: list when the Forth system was compiled but would be removed from the
                   7719: search list for normal operation. This can be a useful technique for
                   7720: low-performance systems (for example, 8-bit processors in embedded
                   7721: systems) but is unlikely to be necessary in high-performance desktop
                   7722: systems.
                   7723: @item
                   7724: To prevent a set of words from being used outside the context in which
                   7725: they are valid. Two classic examples of this are an integrated editor
                   7726: (all of the edit commands are defined in a separate word list; the
                   7727: search order is set to the editor word list when the editor is invoked;
                   7728: the old search order is restored when the editor is terminated) and an
                   7729: integrated assembler (the op-codes for the machine are defined in a
                   7730: separate word list which is used when a @code{CODE} word is defined).
                   7731: @item
                   7732: To prevent a name-space clash between multiple definitions with the same
                   7733: name. For example, when building a cross-compiler you might have a word
                   7734: @code{IF} that generates conditional code for your target system. By
                   7735: placing this definition in a different word list you can control whether
                   7736: the host system's @code{IF} or the target system's @code{IF} get used in
                   7737: any particular context by controlling the order of the word lists on the
                   7738: search order stack.
                   7739: @end itemize
1.1       anton    7740: 
1.48      anton    7741: @node Word list examples,  , Why use word lists?, Word Lists
1.26      crook    7742: @subsection Word list examples
                   7743: @cindex word lists - examples
1.1       anton    7744: 
1.26      crook    7745: Here is an example of creating and using a new wordlist using ANS
                   7746: Forth Standard words:
1.1       anton    7747: 
                   7748: @example
1.26      crook    7749: wordlist constant my-new-words-wordlist
                   7750: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
1.21      crook    7751: 
1.26      crook    7752: \ add it to the search order
                   7753: also my-new-words
1.21      crook    7754: 
1.26      crook    7755: \ alternatively, add it to the search order and make it
                   7756: \ the compilation word list
                   7757: also my-new-words definitions
                   7758: \ type "order" to see the problem
1.21      crook    7759: @end example
                   7760: 
1.26      crook    7761: The problem with this example is that @code{order} has no way to
                   7762: associate the name @code{my-new-words} with the wid of the word list (in
                   7763: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   7764: that has no associated name). There is no Standard way of associating a
                   7765: name with a wid.
                   7766: 
                   7767: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   7768: associates a name with a wid:
1.21      crook    7769: 
1.26      crook    7770: @example
                   7771: vocabulary my-new-words
1.21      crook    7772: 
1.26      crook    7773: \ add it to the search order
1.45      crook    7774: also my-new-words
1.21      crook    7775: 
1.26      crook    7776: \ alternatively, add it to the search order and make it
                   7777: \ the compilation word list
                   7778: my-new-words definitions
                   7779: \ type "order" to see that the problem is solved
                   7780: @end example
1.23      crook    7781: 
1.26      crook    7782: @c -------------------------------------------------------------
                   7783: @node Environmental Queries, Files, Word Lists, Words
                   7784: @section Environmental Queries
                   7785: @cindex environmental queries
1.21      crook    7786: 
1.26      crook    7787: ANS Forth introduced the idea of ``environmental queries'' as a way
                   7788: for a program running on a system to determine certain characteristics of the system.
                   7789: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    7790: 
1.32      anton    7791: The Standard requires that the header space used for environmental queries
                   7792: be distinct from the header space used for definitions.
1.21      crook    7793: 
1.26      crook    7794: Typically, environmental queries are supported by creating a set of
1.29      crook    7795: definitions in a word list that is @i{only} used during environmental
1.26      crook    7796: queries; that is what Gforth does. There is no Standard way of adding
                   7797: definitions to the set of recognised environmental queries, but any
                   7798: implementation that supports the loading of optional word sets must have
                   7799: some mechanism for doing this (after loading the word set, the
                   7800: associated environmental query string must return @code{true}). In
                   7801: Gforth, the word list used to honour environmental queries can be
                   7802: manipulated just like any other word list.
1.21      crook    7803: 
1.44      crook    7804: 
1.26      crook    7805: doc-environment?
                   7806: doc-environment-wordlist
1.21      crook    7807: 
1.26      crook    7808: doc-gforth
                   7809: doc-os-class
1.21      crook    7810: 
1.44      crook    7811: 
1.26      crook    7812: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   7813: returning two items on the stack, querying it using @code{environment?}
                   7814: will return an additional item; the @code{true} flag that shows that the
                   7815: string was recognised.
1.21      crook    7816: 
1.26      crook    7817: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    7818: 
1.26      crook    7819: Here are some examples of using environmental queries:
1.21      crook    7820: 
1.26      crook    7821: @example
                   7822: s" address-unit-bits" environment? 0=
                   7823: [IF]
                   7824:      cr .( environmental attribute address-units-bits unknown... ) cr
                   7825: [THEN]
1.21      crook    7826: 
1.26      crook    7827: s" block" environment? [IF] DROP include block.fs [THEN]
1.21      crook    7828: 
1.26      crook    7829: s" gforth" environment? [IF] 2DROP include compat/vocabulary.fs [THEN]
1.21      crook    7830: 
1.26      crook    7831: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   7832:                         [ELSE] .( Not Gforth..) [THEN]
                   7833: @end example
1.21      crook    7834: 
                   7835: 
1.26      crook    7836: Here is an example of adding a definition to the environment word list:
1.21      crook    7837: 
1.26      crook    7838: @example
                   7839: get-current environment-wordlist set-current
                   7840: true constant block
                   7841: true constant block-ext
                   7842: set-current
                   7843: @end example
1.21      crook    7844: 
1.26      crook    7845: You can see what definitions are in the environment word list like this:
1.21      crook    7846: 
1.26      crook    7847: @example
                   7848: get-order 1+ environment-wordlist swap set-order words previous
                   7849: @end example
1.21      crook    7850: 
                   7851: 
1.26      crook    7852: @c -------------------------------------------------------------
                   7853: @node Files, Blocks, Environmental Queries, Words
                   7854: @section Files
1.28      crook    7855: @cindex files
                   7856: @cindex I/O - file-handling
1.21      crook    7857: 
1.26      crook    7858: Gforth provides facilities for accessing files that are stored in the
                   7859: host operating system's file-system. Files that are processed by Gforth
                   7860: can be divided into two categories:
1.21      crook    7861: 
1.23      crook    7862: @itemize @bullet
                   7863: @item
1.29      crook    7864: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    7865: @item
1.29      crook    7866: Files that are processed by some other program (@dfn{general files}).
1.26      crook    7867: @end itemize
                   7868: 
1.45      crook    7869: doc-loadfilename
                   7870: doc-sourcefilename
                   7871: doc-sourceline#
                   7872: 
1.26      crook    7873: @menu
1.48      anton    7874: * Forth source files::          
                   7875: * General files::               
                   7876: * Search Paths::                
1.26      crook    7877: @end menu
                   7878: 
1.21      crook    7879: 
1.26      crook    7880: @c -------------------------------------------------------------
                   7881: @node Forth source files, General files, Files, Files
                   7882: @subsection Forth source files
                   7883: @cindex including files
                   7884: @cindex Forth source files
1.21      crook    7885: 
1.26      crook    7886: The simplest way to interpret the contents of a file is to use one of
                   7887: these two formats:
1.21      crook    7888: 
1.26      crook    7889: @example
                   7890: include mysource.fs
                   7891: s" mysource.fs" included
                   7892: @end example
1.21      crook    7893: 
1.26      crook    7894: Sometimes you want to include a file only if it is not included already
                   7895: (by, say, another source file). In that case, you can use one of these
1.45      crook    7896: three formats:
1.21      crook    7897: 
1.26      crook    7898: @example
                   7899: require mysource.fs
                   7900: needs mysource.fs
                   7901: s" mysource.fs" required
                   7902: @end example
1.21      crook    7903: 
1.26      crook    7904: @cindex stack effect of included files
                   7905: @cindex including files, stack effect
1.45      crook    7906: It is good practice to write your source files such that interpreting them
                   7907: does not change the stack. Source files designed in this way can be used with
1.26      crook    7908: @code{required} and friends without complications. For example:
1.21      crook    7909: 
1.26      crook    7910: @example
                   7911: 1 require foo.fs drop
                   7912: @end example
1.21      crook    7913: 
1.44      crook    7914: 
1.26      crook    7915: doc-include-file
                   7916: doc-included
1.28      crook    7917: doc-included?
1.26      crook    7918: doc-include
                   7919: doc-required
                   7920: doc-require
                   7921: doc-needs
1.28      crook    7922: doc-init-included-files
1.21      crook    7923: 
1.44      crook    7924: 
1.26      crook    7925: A definition in ANS Forth for @code{required} is provided in
                   7926: @file{compat/required.fs}.
1.21      crook    7927: 
1.26      crook    7928: @c -------------------------------------------------------------
                   7929: @node General files, Search Paths, Forth source files, Files
                   7930: @subsection General files
                   7931: @cindex general files
                   7932: @cindex file-handling
1.21      crook    7933: 
1.26      crook    7934: Files are opened/created by name and type. The following types are
                   7935: recognised:
1.1       anton    7936: 
1.44      crook    7937: 
1.26      crook    7938: doc-r/o
                   7939: doc-r/w
                   7940: doc-w/o
                   7941: doc-bin
1.1       anton    7942: 
1.44      crook    7943: 
1.26      crook    7944: When a file is opened/created, it returns a file identifier,
1.29      crook    7945: @i{wfileid} that is used for all other file commands. All file
                   7946: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    7947: successful operation and an implementation-defined non-zero value in the
                   7948: case of an error.
1.21      crook    7949: 
1.44      crook    7950: 
1.26      crook    7951: doc-open-file
                   7952: doc-create-file
1.21      crook    7953: 
1.26      crook    7954: doc-close-file
                   7955: doc-delete-file
                   7956: doc-rename-file
                   7957: doc-read-file
                   7958: doc-read-line
                   7959: doc-write-file
                   7960: doc-write-line
                   7961: doc-emit-file
                   7962: doc-flush-file
1.21      crook    7963: 
1.26      crook    7964: doc-file-status
                   7965: doc-file-position
                   7966: doc-reposition-file
                   7967: doc-file-size
                   7968: doc-resize-file
1.21      crook    7969: 
1.44      crook    7970: 
1.26      crook    7971: @c ---------------------------------------------------------
1.48      anton    7972: @node Search Paths,  , General files, Files
1.26      crook    7973: @subsection Search Paths
                   7974: @cindex path for @code{included}
                   7975: @cindex file search path
                   7976: @cindex @code{include} search path
                   7977: @cindex search path for files
1.21      crook    7978: 
1.26      crook    7979: If you specify an absolute filename (i.e., a filename starting with
                   7980: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   7981: @samp{C:...})) for @code{included} and friends, that file is included
                   7982: just as you would expect.
1.21      crook    7983: 
1.26      crook    7984: For relative filenames, Gforth uses a search path similar to Forth's
                   7985: search order (@pxref{Word Lists}). It tries to find the given filename
                   7986: in the directories present in the path, and includes the first one it
                   7987: finds. There are separate search paths for Forth source files and
                   7988: general files.
1.21      crook    7989: 
1.26      crook    7990: If the search path contains the directory @file{.} (as it should), this
                   7991: refers to the directory that the present file was @code{included}
                   7992: from. This allows files to include other files relative to their own
                   7993: position (irrespective of the current working directory or the absolute
                   7994: position).  This feature is essential for libraries consisting of
                   7995: several files, where a file may include other files from the library.
                   7996: It corresponds to @code{#include "..."} in C. If the current input
                   7997: source is not a file, @file{.} refers to the directory of the innermost
                   7998: file being included, or, if there is no file being included, to the
                   7999: current working directory.
1.21      crook    8000: 
1.26      crook    8001: Use @file{~+} to refer to the current working directory (as in the
                   8002: @code{bash}).
1.1       anton    8003: 
1.26      crook    8004: If the filename starts with @file{./}, the search path is not searched
                   8005: (just as with absolute filenames), and the @file{.} has the same meaning
                   8006: as described above.
1.1       anton    8007: 
1.48      anton    8008: @menu
                   8009: * Forth Search Paths::          
                   8010: * General Search Paths::        
                   8011: @end menu
                   8012: 
1.26      crook    8013: @c ---------------------------------------------------------
1.48      anton    8014: @node Forth Search Paths, General Search Paths, Search Paths, Search Paths
1.26      crook    8015: @subsubsection Forth Search Paths
1.28      crook    8016: @cindex search path control - Forth
1.5       anton    8017: 
1.26      crook    8018: The search path is initialized when you start Gforth (@pxref{Invoking
                   8019: Gforth}). You can display it and change it using these words:
1.5       anton    8020: 
1.44      crook    8021: 
1.26      crook    8022: doc-.fpath
                   8023: doc-fpath+
                   8024: doc-fpath=
                   8025: doc-open-fpath-file
1.5       anton    8026: 
1.44      crook    8027: 
                   8028: @noindent
1.26      crook    8029: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    8030: 
1.26      crook    8031: @example
                   8032: fpath= /usr/lib/forth/|./
                   8033: require timer.fs
                   8034: @end example
1.5       anton    8035: 
1.26      crook    8036: @c ---------------------------------------------------------
1.48      anton    8037: @node General Search Paths,  , Forth Search Paths, Search Paths
1.26      crook    8038: @subsubsection General Search Paths
                   8039: @cindex search path control - for user applications
1.5       anton    8040: 
1.26      crook    8041: Your application may need to search files in several directories, like
                   8042: @code{included} does. To facilitate this, Gforth allows you to define
                   8043: and use your own search paths, by providing generic equivalents of the
                   8044: Forth search path words:
1.5       anton    8045: 
1.44      crook    8046: 
1.26      crook    8047: doc-.path
                   8048: doc-path+
                   8049: doc-path=
                   8050: doc-open-path-file
1.5       anton    8051: 
1.44      crook    8052: 
1.26      crook    8053: Here's an example of creating a search path:
1.5       anton    8054: 
1.26      crook    8055: @example
                   8056: \ Make a buffer for the path:
                   8057: create mypath   100 chars ,     \ maximum length (is checked)
                   8058:                 0 ,             \ real len
                   8059:                 100 chars allot \ space for path
                   8060: @end example
1.5       anton    8061: 
1.26      crook    8062: @c -------------------------------------------------------------
                   8063: @node Blocks, Other I/O, Files, Words
                   8064: @section Blocks
1.28      crook    8065: @cindex I/O - blocks
                   8066: @cindex blocks
                   8067: 
                   8068: When you run Gforth on a modern desk-top computer, it runs under the
                   8069: control of an operating system which provides certain services.  One of
                   8070: these services is @var{file services}, which allows Forth source code
                   8071: and data to be stored in files and read into Gforth (@pxref{Files}).
                   8072: 
                   8073: Traditionally, Forth has been an important programming language on
                   8074: systems where it has interfaced directly to the underlying hardware with
                   8075: no intervening operating system. Forth provides a mechanism, called
1.29      crook    8076: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    8077: 
                   8078: A block is a 1024-byte data area, which can be used to hold data or
                   8079: Forth source code. No structure is imposed on the contents of the
                   8080: block. A block is identified by its number; blocks are numbered
                   8081: contiguously from 1 to an implementation-defined maximum.
                   8082: 
                   8083: A typical system that used blocks but no operating system might use a
                   8084: single floppy-disk drive for mass storage, with the disks formatted to
                   8085: provide 256-byte sectors. Blocks would be implemented by assigning the
                   8086: first four sectors of the disk to block 1, the second four sectors to
                   8087: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   8088: would not contain any file system information, just the set of blocks.
                   8089: 
1.29      crook    8090: @cindex blocks file
1.28      crook    8091: On systems that do provide file services, blocks are typically
1.29      crook    8092: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    8093: file}.  The size of the blocks file will be an exact multiple of 1024
                   8094: bytes, corresponding to the number of blocks it contains. This is the
                   8095: mechanism that Gforth uses.
                   8096: 
1.29      crook    8097: @cindex @file{blocks.fb}
1.28      crook    8098: Only 1 blocks file can be open at a time. If you use block words without
                   8099: having specified a blocks file, Gforth defaults to the blocks file
                   8100: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
                   8101: locate a blocks file (@pxref{Forth Search Paths}).
                   8102: 
1.29      crook    8103: @cindex block buffers
1.28      crook    8104: When you read and write blocks under program control, Gforth uses a
1.29      crook    8105: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    8106: not used when you use @code{load} to interpret the contents of a block.
                   8107: 
                   8108: The behaviour of the block buffers is directly analagous to that of a
                   8109: cache. Each block buffer has three states:
                   8110: 
                   8111: @itemize @bullet
                   8112: @item
                   8113: Unassigned
                   8114: @item
                   8115: Assigned-clean
                   8116: @item
                   8117: Assigned-dirty
                   8118: @end itemize
                   8119: 
1.29      crook    8120: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    8121: block, the block (specified by its block number) must be assigned to a
                   8122: block buffer.
                   8123: 
                   8124: The assignment of a block to a block buffer is performed by @code{block}
                   8125: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   8126: contents of a block. Use @code{buffer} when you don't care about the
                   8127: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    8128: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    8129: with the particular block is already stored in a block buffer due to an
                   8130: earlier @code{block} command, @code{buffer} will return that block
                   8131: buffer and the existing contents of the block will be
                   8132: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    8133: block buffer for the block.}.
1.28      crook    8134: 
1.47      crook    8135: Once a block has been assigned to a block buffer using @code{block} or
                   8136: @code{buffer}, that block buffer becomes the @i{current block buffer}
                   8137: and its state changes to @i{assigned-clean}. Data may only be
                   8138: manipulated (read or written) within the current block buffer.
                   8139: 
                   8140: When the contents of the current block buffer has been modified it is
1.48      anton    8141: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
                   8142: either abandon the changes (by doing nothing) or commit the changes,
                   8143: using @code{update}. Using @code{update} does not change the blocks
                   8144: file; it simply changes a block buffer's state to @i{assigned-dirty}.
1.28      crook    8145: 
1.29      crook    8146: The word @code{flush} causes all @i{assigned-dirty} blocks to be
1.28      crook    8147: written back to the blocks file on disk. Leaving Gforth using @code{bye}
                   8148: also causes a @code{flush} to be performed.
                   8149: 
1.29      crook    8150: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    8151: algorithm to assign a block buffer to a block. That means that any
                   8152: particular block can only be assigned to one specific block buffer,
1.29      crook    8153: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    8154: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   8155: the new block immediately. If it is @i{assigned-dirty} its current
                   8156: contents are written back to the blocks file on disk before it is
1.28      crook    8157: allocated to the new block.
                   8158: 
                   8159: Although no structure is imposed on the contents of a block, it is
                   8160: traditional to display the contents as 16 lines each of 64 characters.  A
                   8161: block provides a single, continuous stream of input (for example, it
                   8162: acts as a single parse area) -- there are no end-of-line characters
                   8163: within a block, and no end-of-file character at the end of a
                   8164: block. There are two consequences of this:
1.26      crook    8165: 
1.28      crook    8166: @itemize @bullet
                   8167: @item
                   8168: The last character of one line wraps straight into the first character
                   8169: of the following line
                   8170: @item
                   8171: The word @code{\} -- comment to end of line -- requires special
                   8172: treatment; in the context of a block it causes all characters until the
                   8173: end of the current 64-character ``line'' to be ignored.
                   8174: @end itemize
                   8175: 
                   8176: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    8177: the current blocks file will be extended to the appropriate size and the
1.28      crook    8178: block buffer will be initialised with spaces.
                   8179: 
1.47      crook    8180: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   8181: for details) but doesn't encourage the use of blocks; the mechanism is
                   8182: only provided for backward compatibility -- ANS Forth requires blocks to
                   8183: be available when files are.
1.28      crook    8184: 
                   8185: Common techniques that are used when working with blocks include:
                   8186: 
                   8187: @itemize @bullet
                   8188: @item
                   8189: A screen editor that allows you to edit blocks without leaving the Forth
                   8190: environment.
                   8191: @item
                   8192: Shadow screens; where every code block has an associated block
                   8193: containing comments (for example: code in odd block numbers, comments in
                   8194: even block numbers). Typically, the block editor provides a convenient
                   8195: mechanism to toggle between code and comments.
                   8196: @item
                   8197: Load blocks; a single block (typically block 1) contains a number of
                   8198: @code{thru} commands which @code{load} the whole of the application.
                   8199: @end itemize
1.26      crook    8200: 
1.29      crook    8201: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   8202: integrated into a Forth programming environment.
1.26      crook    8203: 
                   8204: @comment TODO what about errors on open-blocks?
1.44      crook    8205: 
1.26      crook    8206: doc-open-blocks
                   8207: doc-use
                   8208: doc-get-block-fid
                   8209: doc-block-position
1.28      crook    8210: 
                   8211: doc-scr
                   8212: doc-list
                   8213: 
1.45      crook    8214: doc---gforthman-block
1.28      crook    8215: doc-buffer
                   8216: 
1.26      crook    8217: doc-update
1.28      crook    8218: doc-updated?
1.26      crook    8219: doc-save-buffers
                   8220: doc-empty-buffers
                   8221: doc-empty-buffer
                   8222: doc-flush
1.28      crook    8223: 
1.26      crook    8224: doc-load
                   8225: doc-thru
                   8226: doc-+load
                   8227: doc-+thru
1.45      crook    8228: doc---gforthman--->
1.26      crook    8229: doc-block-included
                   8230: 
1.44      crook    8231: 
1.26      crook    8232: @c -------------------------------------------------------------
                   8233: @node Other I/O, Programming Tools, Blocks, Words
                   8234: @section Other I/O
1.28      crook    8235: @cindex I/O - keyboard and display
1.26      crook    8236: 
                   8237: @menu
                   8238: * Simple numeric output::       Predefined formats
                   8239: * Formatted numeric output::    Formatted (pictured) output
                   8240: * String Formats::              How Forth stores strings in memory
                   8241: * Displaying characters and strings:: Other stuff
                   8242: * Input::                       Input
                   8243: @end menu
                   8244: 
                   8245: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8246: @subsection Simple numeric output
1.28      crook    8247: @cindex numeric output - simple/free-format
1.5       anton    8248: 
1.26      crook    8249: The simplest output functions are those that display numbers from the
                   8250: data or floating-point stacks. Floating-point output is always displayed
                   8251: using base 10. Numbers displayed from the data stack use the value stored
                   8252: in @code{base}.
1.5       anton    8253: 
1.44      crook    8254: 
1.26      crook    8255: doc-.
                   8256: doc-dec.
                   8257: doc-hex.
                   8258: doc-u.
                   8259: doc-.r
                   8260: doc-u.r
                   8261: doc-d.
                   8262: doc-ud.
                   8263: doc-d.r
                   8264: doc-ud.r
                   8265: doc-f.
                   8266: doc-fe.
                   8267: doc-fs.
1.5       anton    8268: 
1.44      crook    8269: 
1.26      crook    8270: Examples of printing the number 1234.5678E23 in the different floating-point output
                   8271: formats are shown below:
1.5       anton    8272: 
                   8273: @example
1.26      crook    8274: f. 123456779999999000000000000.
                   8275: fe. 123.456779999999E24
                   8276: fs. 1.23456779999999E26
1.5       anton    8277: @end example
                   8278: 
                   8279: 
1.26      crook    8280: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   8281: @subsection Formatted numeric output
1.28      crook    8282: @cindex formatted numeric output
1.26      crook    8283: @cindex pictured numeric output
1.28      crook    8284: @cindex numeric output - formatted
1.26      crook    8285: 
1.29      crook    8286: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    8287: output} for formatted printing of integers.  In this technique, digits
                   8288: are extracted from the number (using the current output radix defined by
                   8289: @code{base}), converted to ASCII codes and appended to a string that is
                   8290: built in a scratch-pad area of memory (@pxref{core-idef,
                   8291: Implementation-defined options, Implementation-defined
                   8292: options}). Arbitrary characters can be appended to the string during the
                   8293: extraction process. The completed string is specified by an address
                   8294: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   8295: under program control.
1.5       anton    8296: 
1.26      crook    8297: All of the words described in the previous section for simple numeric
                   8298: output are implemented in Gforth using pictured numeric output.
1.5       anton    8299: 
1.47      crook    8300: Three important things to remember about pictured numeric output:
1.5       anton    8301: 
1.26      crook    8302: @itemize @bullet
                   8303: @item
1.28      crook    8304: It always operates on double-precision numbers; to display a
1.49      anton    8305: single-precision number, convert it first (for ways of doing this
                   8306: @pxref{Double precision}).
1.26      crook    8307: @item
1.28      crook    8308: It always treats the double-precision number as though it were
                   8309: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    8310: @item
                   8311: The string is built up from right to left; least significant digit first.
                   8312: @end itemize
1.5       anton    8313: 
1.44      crook    8314: 
1.26      crook    8315: doc-<#
1.47      crook    8316: doc-<<#
1.26      crook    8317: doc-#
                   8318: doc-#s
                   8319: doc-hold
                   8320: doc-sign
                   8321: doc-#>
1.47      crook    8322: doc-#>>
1.5       anton    8323: 
1.26      crook    8324: doc-represent
1.5       anton    8325: 
1.44      crook    8326: 
                   8327: @noindent
1.26      crook    8328: Here are some examples of using pictured numeric output:
1.5       anton    8329: 
                   8330: @example
1.26      crook    8331: : my-u. ( u -- )
                   8332:   \ Simplest use of pns.. behaves like Standard u. 
                   8333:   0              \ convert to unsigned double
                   8334:   <#             \ start conversion
                   8335:   #s             \ convert all digits
                   8336:   #>             \ complete conversion
                   8337:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8338: 
1.26      crook    8339: : cents-only ( u -- )
                   8340:   0              \ convert to unsigned double
                   8341:   <#             \ start conversion
                   8342:   # #            \ convert two least-significant digits
                   8343:   #>             \ complete conversion, discard other digits
                   8344:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8345: 
1.26      crook    8346: : dollars-and-cents ( u -- )
                   8347:   0              \ convert to unsigned double
                   8348:   <#             \ start conversion
                   8349:   # #            \ convert two least-significant digits
                   8350:   [char] . hold  \ insert decimal point
                   8351:   #s             \ convert remaining digits
                   8352:   [char] $ hold  \ append currency symbol
                   8353:   #>             \ complete conversion
                   8354:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8355: 
1.26      crook    8356: : my-. ( n -- )
                   8357:   \ handling negatives.. behaves like Standard .
                   8358:   s>d            \ convert to signed double
                   8359:   swap over dabs \ leave sign byte followed by unsigned double
                   8360:   <#             \ start conversion
                   8361:   #s             \ convert all digits
                   8362:   rot sign       \ get at sign byte, append "-" if needed
                   8363:   #>             \ complete conversion
                   8364:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8365: 
1.26      crook    8366: : account. ( n -- )
                   8367:   \ accountants don't like minus signs, they use braces
                   8368:   \ for negative numbers
                   8369:   s>d            \ convert to signed double
                   8370:   swap over dabs \ leave sign byte followed by unsigned double
                   8371:   <#             \ start conversion
                   8372:   2 pick         \ get copy of sign byte
                   8373:   0< IF [char] ) hold THEN \ right-most character of output
                   8374:   #s             \ convert all digits
                   8375:   rot            \ get at sign byte
                   8376:   0< IF [char] ( hold THEN
                   8377:   #>             \ complete conversion
                   8378:   TYPE SPACE ;   \ display, with trailing space
1.5       anton    8379: @end example
                   8380: 
1.26      crook    8381: Here are some examples of using these words:
1.5       anton    8382: 
                   8383: @example
1.26      crook    8384: 1 my-u. 1
                   8385: hex -1 my-u. decimal FFFFFFFF
                   8386: 1 cents-only 01
                   8387: 1234 cents-only 34
                   8388: 2 dollars-and-cents $0.02
                   8389: 1234 dollars-and-cents $12.34
                   8390: 123 my-. 123
                   8391: -123 my. -123
                   8392: 123 account. 123
                   8393: -456 account. (456)
1.5       anton    8394: @end example
                   8395: 
                   8396: 
1.26      crook    8397: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   8398: @subsection String Formats
1.27      crook    8399: @cindex strings - see character strings
                   8400: @cindex character strings - formats
1.28      crook    8401: @cindex I/O - see character strings
1.26      crook    8402: 
1.27      crook    8403: Forth commonly uses two different methods for representing character
                   8404: strings:
1.26      crook    8405: 
                   8406: @itemize @bullet
                   8407: @item
                   8408: @cindex address of counted string
1.45      crook    8409: @cindex counted string
1.29      crook    8410: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   8411: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   8412: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    8413: memory.
                   8414: @item
1.29      crook    8415: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   8416: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    8417: first byte of the string.
                   8418: @end itemize
                   8419: 
                   8420: ANS Forth encourages the use of the second format when representing
                   8421: strings on the stack, whilst conceeding that the counted string format
                   8422: remains useful as a way of storing strings in memory.
                   8423: 
1.44      crook    8424: 
1.26      crook    8425: doc-count
                   8426: 
1.44      crook    8427: 
1.49      anton    8428: For words that move, copy and search for strings see @ref{Memory
                   8429: Blocks}. For words that display characters and strings see
                   8430: @ref{Displaying characters and strings}.
1.26      crook    8431: 
                   8432: @node Displaying characters and strings, Input, String Formats, Other I/O
                   8433: @subsection Displaying characters and strings
1.27      crook    8434: @cindex characters - compiling and displaying
                   8435: @cindex character strings - compiling and displaying
1.26      crook    8436: 
                   8437: This section starts with a glossary of Forth words and ends with a set
                   8438: of examples.
                   8439: 
1.44      crook    8440: 
1.26      crook    8441: doc-bl
                   8442: doc-space
                   8443: doc-spaces
                   8444: doc-emit
                   8445: doc-toupper
                   8446: doc-."
                   8447: doc-.(
                   8448: doc-type
1.44      crook    8449: doc-typewhite
1.26      crook    8450: doc-cr
1.27      crook    8451: @cindex cursor control
1.26      crook    8452: doc-at-xy
                   8453: doc-page
                   8454: doc-s"
                   8455: doc-c"
                   8456: doc-char
                   8457: doc-[char]
                   8458: doc-sliteral
                   8459: 
1.44      crook    8460: 
                   8461: @noindent
1.26      crook    8462: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    8463: 
                   8464: @example
1.26      crook    8465: .( text-1)
                   8466: : my-word
                   8467:   ." text-2" cr
                   8468:   .( text-3)
                   8469: ;
                   8470: 
                   8471: ." text-4"
                   8472: 
                   8473: : my-char
                   8474:   [char] ALPHABET emit
                   8475:   char emit
                   8476: ;
1.5       anton    8477: @end example
                   8478: 
1.26      crook    8479: When you load this code into Gforth, the following output is generated:
1.5       anton    8480: 
1.26      crook    8481: @example
1.30      anton    8482: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    8483: @end example
1.5       anton    8484: 
1.26      crook    8485: @itemize @bullet
                   8486: @item
                   8487: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   8488: is an immediate word; it behaves in the same way whether it is used inside
                   8489: or outside a colon definition.
                   8490: @item
                   8491: Message @code{text-4} is displayed because of Gforth's added interpretation
                   8492: semantics for @code{."}.
                   8493: @item
1.29      crook    8494: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    8495: performs the compilation semantics for @code{."} within the definition of
                   8496: @code{my-word}.
                   8497: @end itemize
1.5       anton    8498: 
1.26      crook    8499: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    8500: 
1.26      crook    8501: @example
1.30      anton    8502: @kbd{my-word @key{RET}} text-2
1.26      crook    8503:  ok
1.30      anton    8504: @kbd{my-char fred @key{RET}} Af ok
                   8505: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    8506: @end example
1.5       anton    8507: 
                   8508: @itemize @bullet
                   8509: @item
1.26      crook    8510: Message @code{text-2} is displayed because of the run-time behaviour of
                   8511: @code{."}.
                   8512: @item
                   8513: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   8514: on the stack at run-time. @code{emit} always displays the character
                   8515: when @code{my-char} is executed.
                   8516: @item
                   8517: @code{char} parses a string at run-time and the second @code{emit} displays
                   8518: the first character of the string.
1.5       anton    8519: @item
1.26      crook    8520: If you type @code{see my-char} you can see that @code{[char]} discarded
                   8521: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   8522: definition of @code{my-char}.
1.5       anton    8523: @end itemize
                   8524: 
                   8525: 
                   8526: 
1.48      anton    8527: @node Input,  , Displaying characters and strings, Other I/O
1.26      crook    8528: @subsection Input
                   8529: @cindex input
1.28      crook    8530: @cindex I/O - see input
                   8531: @cindex parsing a string
1.5       anton    8532: 
1.49      anton    8533: For ways of storing character strings in memory see @ref{String Formats}.
1.5       anton    8534: 
1.27      crook    8535: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29      crook    8536: @comment then index them
1.27      crook    8537: 
1.44      crook    8538: 
1.27      crook    8539: doc-key
                   8540: doc-key?
1.45      crook    8541: doc-ekey
                   8542: doc-ekey?
                   8543: doc-ekey>char
1.26      crook    8544: doc->number
                   8545: doc->float
                   8546: doc-accept
1.27      crook    8547: doc-pad
                   8548: doc-parse
                   8549: doc-word
                   8550: doc-sword
1.44      crook    8551: doc-(name)
1.27      crook    8552: doc-refill
                   8553: @comment obsolescent words..
                   8554: doc-convert
1.26      crook    8555: doc-query
                   8556: doc-expect
1.27      crook    8557: doc-span
1.5       anton    8558: 
                   8559: 
1.44      crook    8560: 
1.5       anton    8561: @c -------------------------------------------------------------
1.26      crook    8562: @node Programming Tools, Assembler and Code Words, Other I/O, Words
                   8563: @section Programming Tools
                   8564: @cindex programming tools
1.12      anton    8565: 
                   8566: @menu
1.26      crook    8567: * Debugging::                   Simple and quick.
                   8568: * Assertions::                  Making your programs self-checking.
1.46      pazsan   8569: * Singlestep Debugger::         Executing your program word by word.
1.5       anton    8570: @end menu
                   8571: 
1.26      crook    8572: @node Debugging, Assertions, Programming Tools, Programming Tools
                   8573: @subsection Debugging
                   8574: @cindex debugging
1.5       anton    8575: 
1.26      crook    8576: Languages with a slow edit/compile/link/test development loop tend to
                   8577: require sophisticated tracing/stepping debuggers to facilate
                   8578: productive debugging.
1.5       anton    8579: 
1.26      crook    8580: A much better (faster) way in fast-compiling languages is to add
                   8581: printing code at well-selected places, let the program run, look at
                   8582: the output, see where things went wrong, add more printing code, etc.,
                   8583: until the bug is found.
1.5       anton    8584: 
1.26      crook    8585: The simple debugging aids provided in @file{debugs.fs}
                   8586: are meant to support this style of debugging. In addition, there are
                   8587: words for non-destructively inspecting the stack and memory:
1.5       anton    8588: 
1.44      crook    8589: 
1.26      crook    8590: doc-.s
                   8591: doc-f.s
1.5       anton    8592: 
1.44      crook    8593: 
1.29      crook    8594: There is a word @code{.r} but it does @i{not} display the return
1.26      crook    8595: stack! It is used for formatted numeric output.
1.5       anton    8596: 
1.44      crook    8597: 
1.26      crook    8598: doc-depth
                   8599: doc-fdepth
                   8600: doc-clearstack
                   8601: doc-?
                   8602: doc-dump
1.5       anton    8603: 
1.44      crook    8604: 
1.26      crook    8605: The word @code{~~} prints debugging information (by default the source
                   8606: location and the stack contents). It is easy to insert. If you use Emacs
                   8607: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   8608: query-replace them with nothing). The deferred words
                   8609: @code{printdebugdata} and @code{printdebugline} control the output of
                   8610: @code{~~}. The default source location output format works well with
                   8611: Emacs' compilation mode, so you can step through the program at the
                   8612: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   8613: is that you can step in any direction and you know where the crash has
                   8614: happened or where the strange data has occurred).
1.5       anton    8615: 
1.26      crook    8616: The default actions of @code{~~} clobber the contents of the pictured
                   8617: numeric output string, so you should not use @code{~~}, e.g., between
                   8618: @code{<#} and @code{#>}.
1.5       anton    8619: 
1.44      crook    8620: 
1.26      crook    8621: doc-~~
                   8622: doc-printdebugdata
                   8623: doc-printdebugline
1.5       anton    8624: 
1.26      crook    8625: doc-see
                   8626: doc-marker
1.5       anton    8627: 
1.44      crook    8628: 
1.26      crook    8629: Here's an example of using @code{marker} at the start of a source file
                   8630: that you are debugging; it ensures that you only ever have one copy of
                   8631: the file's definitions compiled at any time:
1.5       anton    8632: 
1.26      crook    8633: @example
                   8634: [IFDEF] my-code
                   8635:     my-code
                   8636: [ENDIF]
1.5       anton    8637: 
1.26      crook    8638: marker my-code
1.28      crook    8639: init-included-files
1.5       anton    8640: 
1.26      crook    8641: \ .. definitions start here
                   8642: \ .
                   8643: \ .
                   8644: \ end
                   8645: @end example
1.5       anton    8646: 
                   8647: 
                   8648: 
1.26      crook    8649: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   8650: @subsection Assertions
                   8651: @cindex assertions
1.5       anton    8652: 
1.26      crook    8653: It is a good idea to make your programs self-checking, especially if you
                   8654: make an assumption that may become invalid during maintenance (for
                   8655: example, that a certain field of a data structure is never zero). Gforth
1.29      crook    8656: supports @dfn{assertions} for this purpose. They are used like this:
1.23      crook    8657: 
1.26      crook    8658: @example
1.29      crook    8659: assert( @i{flag} )
1.26      crook    8660: @end example
1.23      crook    8661: 
1.26      crook    8662: The code between @code{assert(} and @code{)} should compute a flag, that
                   8663: should be true if everything is alright and false otherwise. It should
                   8664: not change anything else on the stack. The overall stack effect of the
                   8665: assertion is @code{( -- )}. E.g.
1.23      crook    8666: 
1.26      crook    8667: @example
                   8668: assert( 1 1 + 2 = ) \ what we learn in school
                   8669: assert( dup 0<> ) \ assert that the top of stack is not zero
                   8670: assert( false ) \ this code should not be reached
                   8671: @end example
1.23      crook    8672: 
1.26      crook    8673: The need for assertions is different at different times. During
                   8674: debugging, we want more checking, in production we sometimes care more
                   8675: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   8676: becomes a comment. Depending on the importance of an assertion and the
                   8677: time it takes to check it, you may want to turn off some assertions and
                   8678: keep others turned on. Gforth provides several levels of assertions for
                   8679: this purpose:
1.23      crook    8680: 
1.44      crook    8681: 
1.26      crook    8682: doc-assert0(
                   8683: doc-assert1(
                   8684: doc-assert2(
                   8685: doc-assert3(
                   8686: doc-assert(
                   8687: doc-)
1.23      crook    8688: 
1.44      crook    8689: 
1.26      crook    8690: The variable @code{assert-level} specifies the highest assertions that
                   8691: are turned on. I.e., at the default @code{assert-level} of one,
                   8692: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   8693: @code{assert2(} and @code{assert3(} assertions are treated as comments.
                   8694: 
                   8695: The value of @code{assert-level} is evaluated at compile-time, not at
                   8696: run-time. Therefore you cannot turn assertions on or off at run-time;
                   8697: you have to set the @code{assert-level} appropriately before compiling a
                   8698: piece of code. You can compile different pieces of code at different
                   8699: @code{assert-level}s (e.g., a trusted library at level 1 and
                   8700: newly-written code at level 3).
1.23      crook    8701: 
1.44      crook    8702: 
1.26      crook    8703: doc-assert-level
1.23      crook    8704: 
1.44      crook    8705: 
1.26      crook    8706: If an assertion fails, a message compatible with Emacs' compilation mode
                   8707: is produced and the execution is aborted (currently with @code{ABORT"}.
                   8708: If there is interest, we will introduce a special throw code. But if you
                   8709: intend to @code{catch} a specific condition, using @code{throw} is
                   8710: probably more appropriate than an assertion).
1.23      crook    8711: 
1.26      crook    8712: Definitions in ANS Forth for these assertion words are provided
                   8713: in @file{compat/assert.fs}.
1.23      crook    8714: 
                   8715: 
1.48      anton    8716: @node Singlestep Debugger,  , Assertions, Programming Tools
1.26      crook    8717: @subsection Singlestep Debugger
                   8718: @cindex singlestep Debugger
                   8719: @cindex debugging Singlestep
1.23      crook    8720: 
1.26      crook    8721: When you create a new word there's often the need to check whether it
                   8722: behaves correctly or not. You can do this by typing @code{dbg
                   8723: badword}. A debug session might look like this:
1.23      crook    8724: 
1.26      crook    8725: @example
                   8726: : badword 0 DO i . LOOP ;  ok
                   8727: 2 dbg badword 
                   8728: : badword  
                   8729: Scanning code...
1.23      crook    8730: 
1.26      crook    8731: Nesting debugger ready!
1.23      crook    8732: 
1.26      crook    8733: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   8734: 400D4740  8049F68 DO             -> [ 0 ] 
                   8735: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   8736: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   8737: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   8738: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   8739: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   8740: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   8741: 400D4758  804B384 ;              ->  ok
                   8742: @end example
1.23      crook    8743: 
1.26      crook    8744: Each line displayed is one step. You always have to hit return to
                   8745: execute the next word that is displayed. If you don't want to execute
                   8746: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   8747: an overview what keys are available:
1.23      crook    8748: 
1.26      crook    8749: @table @i
1.23      crook    8750: 
1.30      anton    8751: @item @key{RET}
1.26      crook    8752: Next; Execute the next word.
1.23      crook    8753: 
1.26      crook    8754: @item n
                   8755: Nest; Single step through next word.
1.5       anton    8756: 
1.26      crook    8757: @item u
                   8758: Unnest; Stop debugging and execute rest of word. If we got to this word
                   8759: with nest, continue debugging with the calling word.
1.5       anton    8760: 
1.26      crook    8761: @item d
                   8762: Done; Stop debugging and execute rest.
1.5       anton    8763: 
1.26      crook    8764: @item s
                   8765: Stop; Abort immediately.
1.5       anton    8766: 
1.26      crook    8767: @end table
1.5       anton    8768: 
1.26      crook    8769: Debugging large application with this mechanism is very difficult, because
                   8770: you have to nest very deeply into the program before the interesting part
                   8771: begins. This takes a lot of time. 
1.5       anton    8772: 
1.26      crook    8773: To do it more directly put a @code{BREAK:} command into your source code.
                   8774: When program execution reaches @code{BREAK:} the single step debugger is
                   8775: invoked and you have all the features described above.
1.23      crook    8776: 
1.26      crook    8777: If you have more than one part to debug it is useful to know where the
                   8778: program has stopped at the moment. You can do this by the 
                   8779: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   8780: string is typed out when the ``breakpoint'' is reached.
                   8781: 
1.44      crook    8782: 
1.26      crook    8783: doc-dbg
1.45      crook    8784: doc-break:
                   8785: doc-break"
1.26      crook    8786: 
                   8787: 
1.44      crook    8788: 
1.26      crook    8789: @c -------------------------------------------------------------
                   8790: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   8791: @section Assembler and Code Words
                   8792: @cindex assembler
                   8793: @cindex code words
1.5       anton    8794: 
1.52      anton    8795: @menu
1.53      anton    8796: * Code and ;code::              
                   8797: * Common Assembler::            Assembler Syntax
1.52      anton    8798: * Common Disassembler::         
                   8799: * 386 Assembler::               Deviations and special cases
                   8800: * Alpha Assembler::             Deviations and special cases
                   8801: * MIPS assembler::              Deviations and special cases
1.53      anton    8802: * Other assemblers::            How to write them
1.52      anton    8803: @end menu
                   8804: 
1.53      anton    8805: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
                   8806: @subsection @code{Code} and @code{;code}
1.52      anton    8807: 
1.26      crook    8808: Gforth provides some words for defining primitives (words written in
1.29      crook    8809: machine code), and for defining the machine-code equivalent of
1.26      crook    8810: @code{DOES>}-based defining words. However, the machine-independent
                   8811: nature of Gforth poses a few problems: First of all, Gforth runs on
                   8812: several architectures, so it can provide no standard assembler. What's
                   8813: worse is that the register allocation not only depends on the processor,
                   8814: but also on the @code{gcc} version and options used.
1.5       anton    8815: 
1.29      crook    8816: The words that Gforth offers encapsulate some system dependences (e.g.,
                   8817: the header structure), so a system-independent assembler may be used in
1.26      crook    8818: Gforth. If you do not have an assembler, you can compile machine code
1.29      crook    8819: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   8820: because these words emit stuff in @i{data} space; it works because
                   8821: Gforth has unified code/data spaces. Assembler isn't likely to be
                   8822: portable anyway.}.
1.5       anton    8823: 
1.44      crook    8824: 
1.26      crook    8825: doc-assembler
1.45      crook    8826: doc-init-asm
1.26      crook    8827: doc-code
                   8828: doc-end-code
                   8829: doc-;code
                   8830: doc-flush-icache
1.5       anton    8831: 
1.44      crook    8832: 
1.26      crook    8833: If @code{flush-icache} does not work correctly, @code{code} words
                   8834: etc. will not work (reliably), either.
1.5       anton    8835: 
1.29      crook    8836: The typical usage of these @code{code} words can be shown most easily by
                   8837: analogy to the equivalent high-level defining words:
                   8838: 
                   8839: @example
1.53      anton    8840: : foo                              code foo
                   8841:    <high-level Forth words>              <assembler>
                   8842: ;                                  end-code
                   8843:                                 
                   8844: : bar                              : bar
                   8845:    <high-level Forth words>           <high-level Forth words>
                   8846:    CREATE                             CREATE
                   8847:       <high-level Forth words>           <high-level Forth words>
                   8848:    DOES>                              ;code
                   8849:       <high-level Forth words>           <assembler>
                   8850: ;                                  end-code
1.29      crook    8851: @end example
                   8852: 
1.26      crook    8853: @code{flush-icache} is always present. The other words are rarely used
                   8854: and reside in @code{code.fs}, which is usually not loaded. You can load
                   8855: it with @code{require code.fs}.
1.5       anton    8856: 
1.26      crook    8857: @cindex registers of the inner interpreter
                   8858: In the assembly code you will want to refer to the inner interpreter's
                   8859: registers (e.g., the data stack pointer) and you may want to use other
                   8860: registers for temporary storage. Unfortunately, the register allocation
                   8861: is installation-dependent.
1.5       anton    8862: 
1.26      crook    8863: The easiest solution is to use explicit register declarations
                   8864: (@pxref{Explicit Reg Vars, , Variables in Specified Registers, gcc.info,
                   8865: GNU C Manual}) for all of the inner interpreter's registers: You have to
                   8866: compile Gforth with @code{-DFORCE_REG} (configure option
                   8867: @code{--enable-force-reg}) and the appropriate declarations must be
                   8868: present in the @code{machine.h} file (see @code{mips.h} for an example;
                   8869: you can find a full list of all declarable register symbols with
                   8870: @code{grep register engine.c}). If you give explicit registers to all
                   8871: variables that are declared at the beginning of @code{engine()}, you
                   8872: should be able to use the other caller-saved registers for temporary
                   8873: storage. Alternatively, you can use the @code{gcc} option
                   8874: @code{-ffixed-REG} (@pxref{Code Gen Options, , Options for Code
                   8875: Generation Conventions, gcc.info, GNU C Manual}) to reserve a register
                   8876: (however, this restriction on register allocation may slow Gforth
                   8877: significantly).
1.5       anton    8878: 
1.26      crook    8879: If this solution is not viable (e.g., because @code{gcc} does not allow
                   8880: you to explicitly declare all the registers you need), you have to find
                   8881: out by looking at the code where the inner interpreter's registers
                   8882: reside and which registers can be used for temporary storage. You can
                   8883: get an assembly listing of the engine's code with @code{make engine.s}.
1.5       anton    8884: 
1.26      crook    8885: In any case, it is good practice to abstract your assembly code from the
                   8886: actual register allocation. E.g., if the data stack pointer resides in
                   8887: register @code{$17}, create an alias for this register called @code{sp},
                   8888: and use that in your assembly code.
1.5       anton    8889: 
1.26      crook    8890: @cindex code words, portable
                   8891: Another option for implementing normal and defining words efficiently
                   8892: is to add the desired functionality to the source of Gforth. For normal
                   8893: words you just have to edit @file{primitives} (@pxref{Automatic
                   8894: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   8895: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   8896: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.5       anton    8897: 
1.53      anton    8898: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
                   8899: @subsection Common Assembler
                   8900: 
                   8901: The assemblers in Gforth generally use a postfix syntax, i.e., the
                   8902: instruction name follows the operands.
                   8903: 
                   8904: The operands are passed in the usual order (the same that is used in the
                   8905: manual of the architecture).  Since they all are Forth words, they have
                   8906: to be separated by spaces; you can also use Forth words to compute the
                   8907: operands.
                   8908: 
                   8909: The instruction names usually end with a @code{,}.  This makes it easier
                   8910: to visually separate instructions if you put several of them on one
                   8911: line; it also avoids shadowing other Forth words (e.g., @code{and}).
                   8912: 
1.55      anton    8913: Registers are usually specified by number; e.g., (decimal) @code{11}
                   8914: specifies registers R11 and F11 on the Alpha architecture (which one,
                   8915: depends on the instruction).  The usual names are also available, e.g.,
                   8916: @code{s2} for R11 on Alpha.
                   8917: 
1.53      anton    8918: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
                   8919: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
                   8920: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
                   8921: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
                   8922: conditions are specified in a way specific to each assembler.
                   8923: 
1.57      anton    8924: Note that the register assignments of the Gforth engine can change
                   8925: between Gforth versions, or even between different compilations of the
                   8926: same Gforth version (e.g., if you use a different GCC version).  So if
                   8927: you want to refer to Gforth's registers (e.g., the stack pointer or
                   8928: TOS), I recommend defining your own words for refering to these
                   8929: registers, and using them later on; then you can easily adapt to a
                   8930: changed register assignment.  The stability of the register assignment
                   8931: is usually better if you build Gforth with @code{--enable-force-reg}.
                   8932: 
                   8933: In particular, the resturn stack pointer and the instruction pointer are
                   8934: in memory in @code{gforth}, and usually in registers in
                   8935: @code{gforth-fast}.  The most common use of these registers is to
                   8936: dispatch to the next word (the @code{next} routine).  A portable way to
                   8937: do this is to jump to @code{' noop >code-address} (of course, this is
                   8938: less efficient than integrating the @code{next} code and scheduling it
                   8939: well).
                   8940: 
1.52      anton    8941: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
                   8942: @subsection Common Disassembler
                   8943: 
                   8944: You can disassemble a @code{code} word with @code{see}
                   8945: (@pxref{Debugging}).  You can disassemble a section of memory with
                   8946: 
                   8947: doc-disasm
                   8948: 
                   8949: The disassembler generally produces output that can be fed into the
                   8950: assembler (i.e., same syntax, etc.).  It also includes additional
1.53      anton    8951: information in comments.  In particular, the address of the instruction
                   8952: is given in a comment before the instruction.
                   8953: 
                   8954: @code{See} may display more or less than the actual code of the word,
                   8955: because the recognition of the end of the code is unreliable.  You can
                   8956: use @code{disasm} if it did not display enough.  It may display more, if
                   8957: the code word is not immediately followed by a named word.  If you have
                   8958: something else there, you can follow the word with @code{align last @ ,}
                   8959: to ensure that the end is recognized.
1.52      anton    8960: 
                   8961: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
                   8962: @subsection 386 Assembler
                   8963: 
1.64      pazsan   8964: The 386 assembler included in Gforth was written by Bernd Paysan, it's
                   8965: available under GPL, and originally part of bigFORTH.
                   8966: 
                   8967: The 386 disassembler included in Gforth was written by Andrew McKewan
                   8968: and is in the public domain.
1.57      anton    8969: 
                   8970: The disassembler displays code in prefix Intel syntax.
                   8971: 
1.64      pazsan   8972: The assembler uses a postfix syntax with reversed parameters.
                   8973: 
                   8974: The assembler includes all instruction of the Athlon, i.e. 486 core
                   8975: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
                   8976: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
                   8977: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
                   8978: 
                   8979: There are several prefixes to switch between different operation sizes,
                   8980: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
                   8981: double-word accesses. Addressing modes can be switched with @code{.wa}
                   8982: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
                   8983: need a prefix for byte register names (@code{AL} et al).
                   8984: 
                   8985: For floating point operations, the prefixes are @code{.fs} (IEEE
                   8986: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
                   8987: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
                   8988: 
                   8989: The MMX opcodes don't have size prefixes, they are spelled out like in
                   8990: the Intel assembler. Instead of move from and to memory, there are
                   8991: PLDQ/PLDD and PSTQ/PSTD.
                   8992: 
                   8993: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
                   8994: ax.  Immediate values are indicated by postfixing them with @code{#},
                   8995: e.g., @code{3 #}.  Here are some examples of addressing modes:
1.57      anton    8996: 
                   8997: @example
1.65      anton    8998: 3 #          \ immediate
                   8999: ax           \ register
                   9000: 100 di d)    \ 100[edi]
                   9001: 4 bx cx di)  \ 4[ebx][ecx]
                   9002: di ax *4 i)  \ [edi][eax*4]
                   9003: 20 ax *4 i#) \ 20[eax*4]
1.57      anton    9004: @end example
                   9005: 
                   9006: Some example of instructions are:
                   9007: 
                   9008: @example
1.64      pazsan   9009: ax bx mov             \ move ebx,eax
                   9010: 3 # ax mov            \ mov eax,3
                   9011: 100 di ) ax mov       \ mov eax,100[edi]
                   9012: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
                   9013: .w ax bx mov          \ mov bx,ax
1.57      anton    9014: @end example
                   9015: 
1.64      pazsan   9016: The following forms are supported for binary instructions:
1.57      anton    9017: 
                   9018: @example
                   9019: <reg> <reg> <inst>
                   9020: <n> # <reg> <inst>
                   9021: <mem> <reg> <inst>
                   9022: <reg> <mem> <inst>
                   9023: @end example
                   9024: 
                   9025: Immediate to memory is not supported.  The shift/rotate syntax is:
                   9026: 
                   9027: @example
1.64      pazsan   9028: <reg/mem> 1 # shl \ shortens to shift without immediate
                   9029: <reg/mem> 4 # shl
                   9030: <reg/mem> cl shl
1.57      anton    9031: @end example
                   9032: 
1.64      pazsan   9033: Precede string instructions (@code{movs} etc.) with @code{.b} to get
1.57      anton    9034: the byte version.
                   9035: 
1.65      anton    9036: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
                   9037: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
                   9038: pc < >= <= >}. (Note that most of these words shadow some Forth words
                   9039: when @code{assembler} is in front of @code{forth} in the search path,
                   9040: e.g., in @code{code} words).  Currently the control structure words use
                   9041: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
                   9042: to shuffle them (you can also use @code{swap} etc.).
                   9043: 
                   9044: Here is an example of a @code{code} word (assumes that the stack pointer
                   9045: is in esi and the TOS is in ebx):
                   9046: 
                   9047: @example
                   9048: code my+ ( n1 n2 -- n )
                   9049:     4 si D) bx add
                   9050:     4 # si add
                   9051:     Next
                   9052: end-code
                   9053: @end example
1.52      anton    9054: 
                   9055: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
                   9056: @subsection Alpha Assembler
                   9057: 
1.55      anton    9058: The Alpha assembler and disassembler were originally written by Bernd
                   9059: Thallner.
                   9060: 
                   9061: The register names @code{a0}--@code{a5} are not available to avoid
                   9062: shadowing hex numbers.
                   9063: 
                   9064: Immediate forms of arithmetic instructions are distinguished by a
                   9065: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
                   9066: does not count as arithmetic instruction).
                   9067: 
                   9068: You have to specify all operands to an instruction, even those that
                   9069: other assemblers consider optional, e.g., the destination register for
                   9070: @code{br,}, or the destination register and hint for @code{jmp,}.
                   9071: 
                   9072: You can specify conditions for @code{if,} by removing the first @code{b}
                   9073: and the trailing @code{,} from a branch with a corresponding name; e.g.,
                   9074: 
                   9075: @example
                   9076: 11 fgt if, \ if F11>0e
                   9077:   ...
                   9078: endif,
1.56      anton    9079: @end example
1.55      anton    9080: 
                   9081: @code{fbgt,} gives @code{fgt}.  
1.52      anton    9082: 
1.53      anton    9083: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
1.52      anton    9084: @subsection MIPS assembler
                   9085: 
                   9086: The MIPS assembler was originally written by Christian Pirker.
                   9087: 
                   9088: Currently the assembler and disassembler only cover the MIPS-I
                   9089: architecture (R3000), and don't support FP instructions.
                   9090: 
1.55      anton    9091: The register names @code{$a0}--@code{$a3} are not available to avoid
                   9092: shadowing hex numbers.
1.52      anton    9093: 
                   9094: Because there is no way to distinguish registers from immediate values,
                   9095: you have to explicitly use the immediate forms of instructions, i.e.,
                   9096: @code{addiu,}, not just @code{addu,} (@command{as} does this
                   9097: implicitly).
                   9098: 
                   9099: If the architecture manual specifies several formats for the instruction
                   9100: (e.g., for @code{jalr,}), you usually have to use the one with more
                   9101: arguments (i.e., two for @code{jalr,}).  When in doubt, see
                   9102: @code{arch/mips/testasm.fs} for an example of correct use.
                   9103: 
1.53      anton    9104: Branches and jumps in the MIPS architecture have a delay slot.  You have
                   9105: to fill it yourself (the simplest way is to use @code{nop,}), the
                   9106: assembler does not do it for you (unlike @command{as}).  Even
                   9107: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
                   9108: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
                   9109: and @code{then,} just specify branch targets, they are not affected.
                   9110: 
                   9111: Note that you must not put branches, jumps, or @code{li,} into the delay
                   9112: slot: @code{li,} may expand to several instructions, and control flow
                   9113: instructions may not be put into the branch delay slot in any case.
1.52      anton    9114: 
                   9115: For branches the argument specifying the target is a relative address;
                   9116: You have to add the address of the delay slot to get the absolute
                   9117: address.
1.53      anton    9118: 
                   9119: The MIPS architecture also has load delay slots and restrictions on
                   9120: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
                   9121: yourself to satisfy these restrictions, the assembler does not do it for
                   9122: you.
                   9123: 
                   9124: You can specify the conditions for @code{if,} etc. by taking a
                   9125: conditional branch and leaving away the @code{b} at the start and the
                   9126: @code{,} at the end.  E.g.,
                   9127: 
                   9128: @example
                   9129: 4 5 eq if,
                   9130:   ... \ do something if $4 equals $5
                   9131: then,
                   9132: @end example
                   9133: 
                   9134: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
                   9135: @subsection Other assemblers
                   9136: 
                   9137: If you want to contribute another assembler/disassembler, please contact
                   9138: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
                   9139: already.  If you are writing them from scratch, please use a similar
                   9140: syntax style as the one we use (i.e., postfix, commas at the end of the
                   9141: instruction names, @pxref{Common Assembler}); make the output of the
                   9142: disassembler be valid input for the assembler, and keep the style
                   9143: similar to the style we used.
                   9144: 
                   9145: Hints on implementation: The most important part is to have a good test
                   9146: suite that contains all instructions.  Once you have that, the rest is
                   9147: easy.  For actual coding you can take a look at
                   9148: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
                   9149: the assembler and disassembler, avoiding redundancy and some potential
1.63      anton    9150: bugs.  You can also look at that file (and @pxref{Advanced does> usage
                   9151: example}) to get ideas how to factor a disassembler.
1.5       anton    9152: 
1.54      anton    9153: Start with the disassembler, because it's easier to reuse data from the
                   9154: disassembler for the assembler than the other way round.
                   9155: 
                   9156: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
                   9157: how simple it can be.
                   9158: 
1.26      crook    9159: @c -------------------------------------------------------------
                   9160: @node Threading Words, Locals, Assembler and Code Words, Words
                   9161: @section Threading Words
                   9162: @cindex threading words
1.5       anton    9163: 
1.26      crook    9164: @cindex code address
                   9165: These words provide access to code addresses and other threading stuff
                   9166: in Gforth (and, possibly, other interpretive Forths). It more or less
                   9167: abstracts away the differences between direct and indirect threading
                   9168: (and, for direct threading, the machine dependences). However, at
                   9169: present this wordset is still incomplete. It is also pretty low-level;
                   9170: some day it will hopefully be made unnecessary by an internals wordset
                   9171: that abstracts implementation details away completely.
1.5       anton    9172: 
1.44      crook    9173: 
1.26      crook    9174: doc-threading-method
                   9175: doc->code-address
                   9176: doc->does-code
                   9177: doc-code-address!
                   9178: doc-does-code!
                   9179: doc-does-handler!
                   9180: doc-/does-handler
1.5       anton    9181: 
1.44      crook    9182: 
1.26      crook    9183: The code addresses produced by various defining words are produced by
                   9184: the following words:
1.5       anton    9185: 
1.44      crook    9186: 
1.26      crook    9187: doc-docol:
                   9188: doc-docon:
                   9189: doc-dovar:
                   9190: doc-douser:
                   9191: doc-dodefer:
                   9192: doc-dofield:
1.5       anton    9193: 
1.44      crook    9194: 
1.26      crook    9195: You can recognize words defined by a @code{CREATE}...@code{DOES>} word
                   9196: with @code{>does-code}. If the word was defined in that way, the value
                   9197: returned is non-zero and identifies the @code{DOES>} used by the
                   9198: defining word.
                   9199: @comment TODO should that be ``identifies the xt of the DOES> ??''
1.5       anton    9200: 
1.26      crook    9201: @c -------------------------------------------------------------
                   9202: @node Locals, Structures, Threading Words, Words
                   9203: @section Locals
                   9204: @cindex locals
1.5       anton    9205: 
1.26      crook    9206: Local variables can make Forth programming more enjoyable and Forth
                   9207: programs easier to read. Unfortunately, the locals of ANS Forth are
                   9208: laden with restrictions. Therefore, we provide not only the ANS Forth
                   9209: locals wordset, but also our own, more powerful locals wordset (we
                   9210: implemented the ANS Forth locals wordset through our locals wordset).
1.5       anton    9211: 
1.66    ! anton    9212: The ideas in this section have also been published in M. Anton Ertl,
        !          9213: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
        !          9214: Automatic Scoping of Local Variables}}, EuroForth '94.
1.5       anton    9215: 
1.26      crook    9216: @menu
                   9217: * Gforth locals::               
                   9218: * ANS Forth locals::            
                   9219: @end menu
1.5       anton    9220: 
1.26      crook    9221: @node Gforth locals, ANS Forth locals, Locals, Locals
                   9222: @subsection Gforth locals
                   9223: @cindex Gforth locals
                   9224: @cindex locals, Gforth style
1.5       anton    9225: 
1.26      crook    9226: Locals can be defined with
1.5       anton    9227: 
                   9228: @example
1.26      crook    9229: @{ local1 local2 ... -- comment @}
                   9230: @end example
                   9231: or
                   9232: @example
                   9233: @{ local1 local2 ... @}
1.5       anton    9234: @end example
                   9235: 
1.26      crook    9236: E.g.,
1.5       anton    9237: @example
1.26      crook    9238: : max @{ n1 n2 -- n3 @}
                   9239:  n1 n2 > if
                   9240:    n1
                   9241:  else
                   9242:    n2
                   9243:  endif ;
1.5       anton    9244: @end example
                   9245: 
1.26      crook    9246: The similarity of locals definitions with stack comments is intended. A
                   9247: locals definition often replaces the stack comment of a word. The order
                   9248: of the locals corresponds to the order in a stack comment and everything
                   9249: after the @code{--} is really a comment.
1.5       anton    9250: 
1.26      crook    9251: This similarity has one disadvantage: It is too easy to confuse locals
                   9252: declarations with stack comments, causing bugs and making them hard to
                   9253: find. However, this problem can be avoided by appropriate coding
                   9254: conventions: Do not use both notations in the same program. If you do,
                   9255: they should be distinguished using additional means, e.g. by position.
                   9256: 
                   9257: @cindex types of locals
                   9258: @cindex locals types
                   9259: The name of the local may be preceded by a type specifier, e.g.,
                   9260: @code{F:} for a floating point value:
                   9261: 
                   9262: @example
                   9263: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   9264: \ complex multiplication
                   9265:  Ar Br f* Ai Bi f* f-
                   9266:  Ar Bi f* Ai Br f* f+ ;
                   9267: @end example
                   9268: 
                   9269: @cindex flavours of locals
                   9270: @cindex locals flavours
                   9271: @cindex value-flavoured locals
                   9272: @cindex variable-flavoured locals
                   9273: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   9274: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   9275: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   9276: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   9277: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   9278: produces its address (which becomes invalid when the variable's scope is
                   9279: left). E.g., the standard word @code{emit} can be defined in terms of
                   9280: @code{type} like this:
1.5       anton    9281: 
                   9282: @example
1.26      crook    9283: : emit @{ C^ char* -- @}
                   9284:     char* 1 type ;
1.5       anton    9285: @end example
                   9286: 
1.26      crook    9287: @cindex default type of locals
                   9288: @cindex locals, default type
                   9289: A local without type specifier is a @code{W:} local. Both flavours of
                   9290: locals are initialized with values from the data or FP stack.
1.5       anton    9291: 
1.26      crook    9292: Currently there is no way to define locals with user-defined data
                   9293: structures, but we are working on it.
1.5       anton    9294: 
1.26      crook    9295: Gforth allows defining locals everywhere in a colon definition. This
                   9296: poses the following questions:
1.5       anton    9297: 
1.26      crook    9298: @menu
                   9299: * Where are locals visible by name?::  
                   9300: * How long do locals live?::    
                   9301: * Programming Style::           
                   9302: * Implementation::              
                   9303: @end menu
1.5       anton    9304: 
1.26      crook    9305: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   9306: @subsubsection Where are locals visible by name?
                   9307: @cindex locals visibility
                   9308: @cindex visibility of locals
                   9309: @cindex scope of locals
1.5       anton    9310: 
1.26      crook    9311: Basically, the answer is that locals are visible where you would expect
                   9312: it in block-structured languages, and sometimes a little longer. If you
                   9313: want to restrict the scope of a local, enclose its definition in
                   9314: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    9315: 
1.44      crook    9316: 
1.26      crook    9317: doc-scope
                   9318: doc-endscope
1.5       anton    9319: 
1.44      crook    9320: 
1.26      crook    9321: These words behave like control structure words, so you can use them
                   9322: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   9323: arbitrary ways.
1.5       anton    9324: 
1.26      crook    9325: If you want a more exact answer to the visibility question, here's the
                   9326: basic principle: A local is visible in all places that can only be
                   9327: reached through the definition of the local@footnote{In compiler
                   9328: construction terminology, all places dominated by the definition of the
                   9329: local.}. In other words, it is not visible in places that can be reached
                   9330: without going through the definition of the local. E.g., locals defined
                   9331: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   9332: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   9333: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.5       anton    9334: 
1.26      crook    9335: The reasoning behind this solution is: We want to have the locals
                   9336: visible as long as it is meaningful. The user can always make the
                   9337: visibility shorter by using explicit scoping. In a place that can
                   9338: only be reached through the definition of a local, the meaning of a
                   9339: local name is clear. In other places it is not: How is the local
                   9340: initialized at the control flow path that does not contain the
                   9341: definition? Which local is meant, if the same name is defined twice in
                   9342: two independent control flow paths?
1.5       anton    9343: 
1.26      crook    9344: This should be enough detail for nearly all users, so you can skip the
                   9345: rest of this section. If you really must know all the gory details and
                   9346: options, read on.
1.5       anton    9347: 
1.26      crook    9348: In order to implement this rule, the compiler has to know which places
                   9349: are unreachable. It knows this automatically after @code{AHEAD},
                   9350: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   9351: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   9352: compiler that the control flow never reaches that place. If
                   9353: @code{UNREACHABLE} is not used where it could, the only consequence is
                   9354: that the visibility of some locals is more limited than the rule above
                   9355: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   9356: lie to the compiler), buggy code will be produced.
1.5       anton    9357: 
1.44      crook    9358: 
1.26      crook    9359: doc-unreachable
1.5       anton    9360: 
1.44      crook    9361: 
1.26      crook    9362: Another problem with this rule is that at @code{BEGIN}, the compiler
                   9363: does not know which locals will be visible on the incoming
                   9364: back-edge. All problems discussed in the following are due to this
                   9365: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   9366: loops as examples; the discussion also applies to @code{?DO} and other
                   9367: loops). Perhaps the most insidious example is:
1.5       anton    9368: @example
1.26      crook    9369: AHEAD
                   9370: BEGIN
                   9371:   x
                   9372: [ 1 CS-ROLL ] THEN
                   9373:   @{ x @}
                   9374:   ...
                   9375: UNTIL
                   9376: @end example
1.5       anton    9377: 
1.26      crook    9378: This should be legal according to the visibility rule. The use of
                   9379: @code{x} can only be reached through the definition; but that appears
                   9380: textually below the use.
1.5       anton    9381: 
1.26      crook    9382: From this example it is clear that the visibility rules cannot be fully
                   9383: implemented without major headaches. Our implementation treats common
                   9384: cases as advertised and the exceptions are treated in a safe way: The
                   9385: compiler makes a reasonable guess about the locals visible after a
                   9386: @code{BEGIN}; if it is too pessimistic, the
                   9387: user will get a spurious error about the local not being defined; if the
                   9388: compiler is too optimistic, it will notice this later and issue a
                   9389: warning. In the case above the compiler would complain about @code{x}
                   9390: being undefined at its use. You can see from the obscure examples in
                   9391: this section that it takes quite unusual control structures to get the
                   9392: compiler into trouble, and even then it will often do fine.
1.5       anton    9393: 
1.26      crook    9394: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   9395: is that all locals visible before the @code{BEGIN} will also be
                   9396: visible after the @code{BEGIN}. This guess is valid for all loops that
                   9397: are entered only through the @code{BEGIN}, in particular, for normal
                   9398: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   9399: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   9400: compiler. When the branch to the @code{BEGIN} is finally generated by
                   9401: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   9402: warns the user if it was too optimistic:
                   9403: @example
                   9404: IF
                   9405:   @{ x @}
                   9406: BEGIN
                   9407:   \ x ? 
                   9408: [ 1 cs-roll ] THEN
                   9409:   ...
                   9410: UNTIL
1.5       anton    9411: @end example
                   9412: 
1.26      crook    9413: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   9414: optimistically assumes that it lives until the @code{THEN}. It notices
                   9415: this difference when it compiles the @code{UNTIL} and issues a
                   9416: warning. The user can avoid the warning, and make sure that @code{x}
                   9417: is not used in the wrong area by using explicit scoping:
                   9418: @example
                   9419: IF
                   9420:   SCOPE
                   9421:   @{ x @}
                   9422:   ENDSCOPE
                   9423: BEGIN
                   9424: [ 1 cs-roll ] THEN
                   9425:   ...
                   9426: UNTIL
                   9427: @end example
1.5       anton    9428: 
1.26      crook    9429: Since the guess is optimistic, there will be no spurious error messages
                   9430: about undefined locals.
1.5       anton    9431: 
1.26      crook    9432: If the @code{BEGIN} is not reachable from above (e.g., after
                   9433: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   9434: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   9435: defined later. Therefore, the compiler assumes that no locals are
                   9436: visible after the @code{BEGIN}. However, the user can use
                   9437: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   9438: visible at the BEGIN as at the point where the top control-flow stack
                   9439: item was created.
1.5       anton    9440: 
1.44      crook    9441: 
1.26      crook    9442: doc-assume-live
1.5       anton    9443: 
1.44      crook    9444: 
                   9445: @noindent
1.26      crook    9446: E.g.,
1.5       anton    9447: @example
1.26      crook    9448: @{ x @}
                   9449: AHEAD
                   9450: ASSUME-LIVE
                   9451: BEGIN
                   9452:   x
                   9453: [ 1 CS-ROLL ] THEN
                   9454:   ...
                   9455: UNTIL
1.5       anton    9456: @end example
                   9457: 
1.26      crook    9458: Other cases where the locals are defined before the @code{BEGIN} can be
                   9459: handled by inserting an appropriate @code{CS-ROLL} before the
                   9460: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   9461: behind the @code{ASSUME-LIVE}).
1.5       anton    9462: 
1.26      crook    9463: Cases where locals are defined after the @code{BEGIN} (but should be
                   9464: visible immediately after the @code{BEGIN}) can only be handled by
                   9465: rearranging the loop. E.g., the ``most insidious'' example above can be
                   9466: arranged into:
1.5       anton    9467: @example
1.26      crook    9468: BEGIN
                   9469:   @{ x @}
                   9470:   ... 0=
                   9471: WHILE
                   9472:   x
                   9473: REPEAT
1.5       anton    9474: @end example
                   9475: 
1.26      crook    9476: @node How long do locals live?, Programming Style, Where are locals visible by name?, Gforth locals
                   9477: @subsubsection How long do locals live?
                   9478: @cindex locals lifetime
                   9479: @cindex lifetime of locals
1.5       anton    9480: 
1.26      crook    9481: The right answer for the lifetime question would be: A local lives at
                   9482: least as long as it can be accessed. For a value-flavoured local this
                   9483: means: until the end of its visibility. However, a variable-flavoured
                   9484: local could be accessed through its address far beyond its visibility
                   9485: scope. Ultimately, this would mean that such locals would have to be
                   9486: garbage collected. Since this entails un-Forth-like implementation
                   9487: complexities, I adopted the same cowardly solution as some other
                   9488: languages (e.g., C): The local lives only as long as it is visible;
                   9489: afterwards its address is invalid (and programs that access it
                   9490: afterwards are erroneous).
1.5       anton    9491: 
1.26      crook    9492: @node Programming Style, Implementation, How long do locals live?, Gforth locals
                   9493: @subsubsection Programming Style
                   9494: @cindex locals programming style
                   9495: @cindex programming style, locals
1.5       anton    9496: 
1.26      crook    9497: The freedom to define locals anywhere has the potential to change
                   9498: programming styles dramatically. In particular, the need to use the
                   9499: return stack for intermediate storage vanishes. Moreover, all stack
                   9500: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9501: determined arguments) can be eliminated: If the stack items are in the
                   9502: wrong order, just write a locals definition for all of them; then
                   9503: write the items in the order you want.
1.5       anton    9504: 
1.26      crook    9505: This seems a little far-fetched and eliminating stack manipulations is
                   9506: unlikely to become a conscious programming objective. Still, the number
                   9507: of stack manipulations will be reduced dramatically if local variables
1.49      anton    9508: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
1.26      crook    9509: a traditional implementation of @code{max}).
1.5       anton    9510: 
1.26      crook    9511: This shows one potential benefit of locals: making Forth programs more
                   9512: readable. Of course, this benefit will only be realized if the
                   9513: programmers continue to honour the principle of factoring instead of
                   9514: using the added latitude to make the words longer.
1.5       anton    9515: 
1.26      crook    9516: @cindex single-assignment style for locals
                   9517: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9518: every value-flavoured local has only a single assignment and many
                   9519: advantages of functional languages apply to Forth. I.e., programs are
                   9520: easier to analyse, to optimize and to read: It is clear from the
                   9521: definition what the local stands for, it does not turn into something
                   9522: different later.
1.5       anton    9523: 
1.26      crook    9524: E.g., a definition using @code{TO} might look like this:
1.5       anton    9525: @example
1.26      crook    9526: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9527:  u1 u2 min 0
                   9528:  ?do
                   9529:    addr1 c@@ addr2 c@@ -
                   9530:    ?dup-if
                   9531:      unloop exit
                   9532:    then
                   9533:    addr1 char+ TO addr1
                   9534:    addr2 char+ TO addr2
                   9535:  loop
                   9536:  u1 u2 - ;
1.5       anton    9537: @end example
1.26      crook    9538: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9539: every loop iteration. @code{strcmp} is a typical example of the
                   9540: readability problems of using @code{TO}. When you start reading
                   9541: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9542: string. Only near the end of the loop you realize that it is something
                   9543: else.
1.5       anton    9544: 
1.26      crook    9545: This can be avoided by defining two locals at the start of the loop that
                   9546: are initialized with the right value for the current iteration.
1.5       anton    9547: @example
1.26      crook    9548: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9549:  addr1 addr2
                   9550:  u1 u2 min 0 
                   9551:  ?do @{ s1 s2 @}
                   9552:    s1 c@@ s2 c@@ -
                   9553:    ?dup-if
                   9554:      unloop exit
                   9555:    then
                   9556:    s1 char+ s2 char+
                   9557:  loop
                   9558:  2drop
                   9559:  u1 u2 - ;
1.5       anton    9560: @end example
1.26      crook    9561: Here it is clear from the start that @code{s1} has a different value
                   9562: in every loop iteration.
1.5       anton    9563: 
1.26      crook    9564: @node Implementation,  , Programming Style, Gforth locals
                   9565: @subsubsection Implementation
                   9566: @cindex locals implementation
                   9567: @cindex implementation of locals
1.5       anton    9568: 
1.26      crook    9569: @cindex locals stack
                   9570: Gforth uses an extra locals stack. The most compelling reason for
                   9571: this is that the return stack is not float-aligned; using an extra stack
                   9572: also eliminates the problems and restrictions of using the return stack
                   9573: as locals stack. Like the other stacks, the locals stack grows toward
                   9574: lower addresses. A few primitives allow an efficient implementation:
1.5       anton    9575: 
1.44      crook    9576: 
1.26      crook    9577: doc-@local#
                   9578: doc-f@local#
                   9579: doc-laddr#
                   9580: doc-lp+!#
                   9581: doc-lp!
                   9582: doc->l
                   9583: doc-f>l
1.5       anton    9584: 
1.44      crook    9585: 
1.26      crook    9586: In addition to these primitives, some specializations of these
                   9587: primitives for commonly occurring inline arguments are provided for
                   9588: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9589: @code{@@local#} for the inline argument 0. The following compiling words
                   9590: compile the right specialized version, or the general version, as
                   9591: appropriate:
1.6       pazsan   9592: 
1.44      crook    9593: 
1.26      crook    9594: doc-compile-@local
                   9595: doc-compile-f@local
                   9596: doc-compile-lp+!
1.12      anton    9597: 
1.44      crook    9598: 
1.26      crook    9599: Combinations of conditional branches and @code{lp+!#} like
                   9600: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9601: is taken) are provided for efficiency and correctness in loops.
1.6       pazsan   9602: 
1.26      crook    9603: A special area in the dictionary space is reserved for keeping the
                   9604: local variable names. @code{@{} switches the dictionary pointer to this
                   9605: area and @code{@}} switches it back and generates the locals
                   9606: initializing code. @code{W:} etc.@ are normal defining words. This
                   9607: special area is cleared at the start of every colon definition.
1.6       pazsan   9608: 
1.26      crook    9609: @cindex word list for defining locals
                   9610: A special feature of Gforth's dictionary is used to implement the
                   9611: definition of locals without type specifiers: every word list (aka
                   9612: vocabulary) has its own methods for searching
                   9613: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   9614: with a special search method: When it is searched for a word, it
                   9615: actually creates that word using @code{W:}. @code{@{} changes the search
                   9616: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   9617: and then the word list for defining locals without type specifiers.
1.12      anton    9618: 
1.26      crook    9619: The lifetime rules support a stack discipline within a colon
                   9620: definition: The lifetime of a local is either nested with other locals
                   9621: lifetimes or it does not overlap them.
1.6       pazsan   9622: 
1.26      crook    9623: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   9624: pointer manipulation is generated. Between control structure words
                   9625: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   9626: is the simplest of the other three control flow words. It has to
                   9627: restore the locals stack depth of the corresponding @code{BEGIN}
                   9628: before branching. The code looks like this:
                   9629: @format
                   9630: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   9631: @code{branch} <begin>
                   9632: @end format
1.6       pazsan   9633: 
1.26      crook    9634: @code{UNTIL} is a little more complicated: If it branches back, it
                   9635: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   9636: the locals stack must not be changed. The compiler generates the
                   9637: following code:
                   9638: @format
                   9639: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   9640: @end format
                   9641: The locals stack pointer is only adjusted if the branch is taken.
1.6       pazsan   9642: 
1.26      crook    9643: @code{THEN} can produce somewhat inefficient code:
                   9644: @format
                   9645: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   9646: <orig target>:
                   9647: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   9648: @end format
                   9649: The second @code{lp+!#} adjusts the locals stack pointer from the
1.29      crook    9650: level at the @i{orig} point to the level after the @code{THEN}. The
1.26      crook    9651: first @code{lp+!#} adjusts the locals stack pointer from the current
                   9652: level to the level at the orig point, so the complete effect is an
                   9653: adjustment from the current level to the right level after the
                   9654: @code{THEN}.
1.6       pazsan   9655: 
1.26      crook    9656: @cindex locals information on the control-flow stack
                   9657: @cindex control-flow stack items, locals information
                   9658: In a conventional Forth implementation a dest control-flow stack entry
                   9659: is just the target address and an orig entry is just the address to be
                   9660: patched. Our locals implementation adds a word list to every orig or dest
                   9661: item. It is the list of locals visible (or assumed visible) at the point
                   9662: described by the entry. Our implementation also adds a tag to identify
                   9663: the kind of entry, in particular to differentiate between live and dead
                   9664: (reachable and unreachable) orig entries.
1.6       pazsan   9665: 
1.26      crook    9666: A few unusual operations have to be performed on locals word lists:
1.6       pazsan   9667: 
1.44      crook    9668: 
1.26      crook    9669: doc-common-list
                   9670: doc-sub-list?
                   9671: doc-list-size
1.6       pazsan   9672: 
1.44      crook    9673: 
1.26      crook    9674: Several features of our locals word list implementation make these
                   9675: operations easy to implement: The locals word lists are organised as
                   9676: linked lists; the tails of these lists are shared, if the lists
                   9677: contain some of the same locals; and the address of a name is greater
                   9678: than the address of the names behind it in the list.
1.6       pazsan   9679: 
1.26      crook    9680: Another important implementation detail is the variable
                   9681: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   9682: determine if they can be reached directly or only through the branch
                   9683: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   9684: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   9685: definition, by @code{BEGIN} and usually by @code{THEN}.
1.6       pazsan   9686: 
1.26      crook    9687: Counted loops are similar to other loops in most respects, but
                   9688: @code{LEAVE} requires special attention: It performs basically the same
                   9689: service as @code{AHEAD}, but it does not create a control-flow stack
                   9690: entry. Therefore the information has to be stored elsewhere;
                   9691: traditionally, the information was stored in the target fields of the
                   9692: branches created by the @code{LEAVE}s, by organizing these fields into a
                   9693: linked list. Unfortunately, this clever trick does not provide enough
                   9694: space for storing our extended control flow information. Therefore, we
                   9695: introduce another stack, the leave stack. It contains the control-flow
                   9696: stack entries for all unresolved @code{LEAVE}s.
1.6       pazsan   9697: 
1.26      crook    9698: Local names are kept until the end of the colon definition, even if
                   9699: they are no longer visible in any control-flow path. In a few cases
                   9700: this may lead to increased space needs for the locals name area, but
                   9701: usually less than reclaiming this space would cost in code size.
1.6       pazsan   9702: 
                   9703: 
1.26      crook    9704: @node ANS Forth locals,  , Gforth locals, Locals
                   9705: @subsection ANS Forth locals
                   9706: @cindex locals, ANS Forth style
1.6       pazsan   9707: 
1.26      crook    9708: The ANS Forth locals wordset does not define a syntax for locals, but
                   9709: words that make it possible to define various syntaxes. One of the
                   9710: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   9711: wordset, i.e.:
1.6       pazsan   9712: 
                   9713: @example
1.26      crook    9714: @{ local1 local2 ... -- comment @}
1.6       pazsan   9715: @end example
1.23      crook    9716: @noindent
1.26      crook    9717: or
1.6       pazsan   9718: @example
1.26      crook    9719: @{ local1 local2 ... @}
1.6       pazsan   9720: @end example
                   9721: 
1.26      crook    9722: The order of the locals corresponds to the order in a stack comment. The
                   9723: restrictions are:
1.6       pazsan   9724: 
                   9725: @itemize @bullet
                   9726: @item
1.26      crook    9727: Locals can only be cell-sized values (no type specifiers are allowed).
1.6       pazsan   9728: @item
1.26      crook    9729: Locals can be defined only outside control structures.
1.6       pazsan   9730: @item
1.26      crook    9731: Locals can interfere with explicit usage of the return stack. For the
                   9732: exact (and long) rules, see the standard. If you don't use return stack
                   9733: accessing words in a definition using locals, you will be all right. The
                   9734: purpose of this rule is to make locals implementation on the return
                   9735: stack easier.
1.6       pazsan   9736: @item
1.26      crook    9737: The whole definition must be in one line.
                   9738: @end itemize
1.6       pazsan   9739: 
1.44      crook    9740: Locals defined in this way behave like @code{VALUE}s
1.49      anton    9741: (@pxref{Values}). I.e., they are initialized from the stack. Using their
1.26      crook    9742: name produces their value. Their value can be changed using @code{TO}.
1.6       pazsan   9743: 
1.26      crook    9744: Since this syntax is supported by Gforth directly, you need not do
                   9745: anything to use it. If you want to port a program using this syntax to
                   9746: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   9747: syntax on the other system.
1.6       pazsan   9748: 
1.26      crook    9749: Note that a syntax shown in the standard, section A.13 looks
                   9750: similar, but is quite different in having the order of locals
                   9751: reversed. Beware!
1.6       pazsan   9752: 
1.26      crook    9753: The ANS Forth locals wordset itself consists of a word:
1.6       pazsan   9754: 
1.44      crook    9755: 
1.26      crook    9756: doc-(local)
1.6       pazsan   9757: 
1.44      crook    9758: 
1.26      crook    9759: The ANS Forth locals extension wordset defines a syntax using @code{locals|}, but it is so
                   9760: awful that we strongly recommend not to use it. We have implemented this
                   9761: syntax to make porting to Gforth easy, but do not document it here. The
                   9762: problem with this syntax is that the locals are defined in an order
                   9763: reversed with respect to the standard stack comment notation, making
                   9764: programs harder to read, and easier to misread and miswrite. The only
                   9765: merit of this syntax is that it is easy to implement using the ANS Forth
                   9766: locals wordset.
1.7       pazsan   9767: 
                   9768: 
1.26      crook    9769: @c ----------------------------------------------------------
                   9770: @node Structures, Object-oriented Forth, Locals, Words
                   9771: @section  Structures
                   9772: @cindex structures
                   9773: @cindex records
1.7       pazsan   9774: 
1.26      crook    9775: This section presents the structure package that comes with Gforth. A
                   9776: version of the package implemented in ANS Forth is available in
                   9777: @file{compat/struct.fs}. This package was inspired by a posting on
                   9778: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   9779: possibly John Hayes). A version of this section has been published in
                   9780: ???. Marcel Hendrix provided helpful comments.
1.7       pazsan   9781: 
1.26      crook    9782: @menu
                   9783: * Why explicit structure support?::  
                   9784: * Structure Usage::             
                   9785: * Structure Naming Convention::  
                   9786: * Structure Implementation::    
                   9787: * Structure Glossary::          
                   9788: @end menu
1.7       pazsan   9789: 
1.26      crook    9790: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   9791: @subsection Why explicit structure support?
1.7       pazsan   9792: 
1.26      crook    9793: @cindex address arithmetic for structures
                   9794: @cindex structures using address arithmetic
                   9795: If we want to use a structure containing several fields, we could simply
                   9796: reserve memory for it, and access the fields using address arithmetic
1.32      anton    9797: (@pxref{Address arithmetic}). As an example, consider a structure with
1.26      crook    9798: the following fields
1.7       pazsan   9799: 
1.26      crook    9800: @table @code
                   9801: @item a
                   9802: is a float
                   9803: @item b
                   9804: is a cell
                   9805: @item c
                   9806: is a float
                   9807: @end table
1.7       pazsan   9808: 
1.26      crook    9809: Given the (float-aligned) base address of the structure we get the
                   9810: address of the field
1.13      pazsan   9811: 
1.26      crook    9812: @table @code
                   9813: @item a
                   9814: without doing anything further.
                   9815: @item b
                   9816: with @code{float+}
                   9817: @item c
                   9818: with @code{float+ cell+ faligned}
                   9819: @end table
1.13      pazsan   9820: 
1.26      crook    9821: It is easy to see that this can become quite tiring. 
1.13      pazsan   9822: 
1.26      crook    9823: Moreover, it is not very readable, because seeing a
                   9824: @code{cell+} tells us neither which kind of structure is
                   9825: accessed nor what field is accessed; we have to somehow infer the kind
                   9826: of structure, and then look up in the documentation, which field of
                   9827: that structure corresponds to that offset.
1.13      pazsan   9828: 
1.26      crook    9829: Finally, this kind of address arithmetic also causes maintenance
                   9830: troubles: If you add or delete a field somewhere in the middle of the
                   9831: structure, you have to find and change all computations for the fields
                   9832: afterwards.
1.13      pazsan   9833: 
1.26      crook    9834: So, instead of using @code{cell+} and friends directly, how
                   9835: about storing the offsets in constants:
1.13      pazsan   9836: 
                   9837: @example
1.26      crook    9838: 0 constant a-offset
                   9839: 0 float+ constant b-offset
                   9840: 0 float+ cell+ faligned c-offset
1.13      pazsan   9841: @end example
                   9842: 
1.26      crook    9843: Now we can get the address of field @code{x} with @code{x-offset
                   9844: +}. This is much better in all respects. Of course, you still
                   9845: have to change all later offset definitions if you add a field. You can
                   9846: fix this by declaring the offsets in the following way:
1.13      pazsan   9847: 
                   9848: @example
1.26      crook    9849: 0 constant a-offset
                   9850: a-offset float+ constant b-offset
                   9851: b-offset cell+ faligned constant c-offset
1.13      pazsan   9852: @end example
                   9853: 
1.26      crook    9854: Since we always use the offsets with @code{+}, we could use a defining
                   9855: word @code{cfield} that includes the @code{+} in the action of the
                   9856: defined word:
1.8       pazsan   9857: 
                   9858: @example
1.26      crook    9859: : cfield ( n "name" -- )
                   9860:     create ,
                   9861: does> ( name execution: addr1 -- addr2 )
                   9862:     @@ + ;
1.13      pazsan   9863: 
1.26      crook    9864: 0 cfield a
                   9865: 0 a float+ cfield b
                   9866: 0 b cell+ faligned cfield c
1.13      pazsan   9867: @end example
                   9868: 
1.26      crook    9869: Instead of @code{x-offset +}, we now simply write @code{x}.
                   9870: 
                   9871: The structure field words now can be used quite nicely. However,
                   9872: their definition is still a bit cumbersome: We have to repeat the
                   9873: name, the information about size and alignment is distributed before
                   9874: and after the field definitions etc.  The structure package presented
                   9875: here addresses these problems.
                   9876: 
                   9877: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   9878: @subsection Structure Usage
                   9879: @cindex structure usage
1.13      pazsan   9880: 
1.26      crook    9881: @cindex @code{field} usage
                   9882: @cindex @code{struct} usage
                   9883: @cindex @code{end-struct} usage
                   9884: You can define a structure for a (data-less) linked list with:
1.13      pazsan   9885: @example
1.26      crook    9886: struct
                   9887:     cell% field list-next
                   9888: end-struct list%
1.13      pazsan   9889: @end example
                   9890: 
1.26      crook    9891: With the address of the list node on the stack, you can compute the
                   9892: address of the field that contains the address of the next node with
                   9893: @code{list-next}. E.g., you can determine the length of a list
                   9894: with:
1.13      pazsan   9895: 
                   9896: @example
1.26      crook    9897: : list-length ( list -- n )
                   9898: \ "list" is a pointer to the first element of a linked list
                   9899: \ "n" is the length of the list
                   9900:     0 BEGIN ( list1 n1 )
                   9901:         over
                   9902:     WHILE ( list1 n1 )
                   9903:         1+ swap list-next @@ swap
                   9904:     REPEAT
                   9905:     nip ;
1.13      pazsan   9906: @end example
                   9907: 
1.26      crook    9908: You can reserve memory for a list node in the dictionary with
                   9909: @code{list% %allot}, which leaves the address of the list node on the
                   9910: stack. For the equivalent allocation on the heap you can use @code{list%
                   9911: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   9912: use @code{list% %allocate}). You can get the the size of a list
                   9913: node with @code{list% %size} and its alignment with @code{list%
                   9914: %alignment}.
1.13      pazsan   9915: 
1.26      crook    9916: Note that in ANS Forth the body of a @code{create}d word is
                   9917: @code{aligned} but not necessarily @code{faligned};
                   9918: therefore, if you do a:
1.13      pazsan   9919: @example
1.26      crook    9920: create @emph{name} foo% %allot
1.8       pazsan   9921: @end example
                   9922: 
1.26      crook    9923: @noindent
                   9924: then the memory alloted for @code{foo%} is
                   9925: guaranteed to start at the body of @code{@emph{name}} only if
                   9926: @code{foo%} contains only character, cell and double fields.
1.20      pazsan   9927: 
1.45      crook    9928: @cindex structures containing structures
1.26      crook    9929: You can include a structure @code{foo%} as a field of
                   9930: another structure, like this:
1.20      pazsan   9931: @example
1.26      crook    9932: struct
                   9933: ...
                   9934:     foo% field ...
                   9935: ...
                   9936: end-struct ...
1.20      pazsan   9937: @end example
                   9938: 
1.26      crook    9939: @cindex structure extension
                   9940: @cindex extended records
                   9941: Instead of starting with an empty structure, you can extend an
                   9942: existing structure. E.g., a plain linked list without data, as defined
                   9943: above, is hardly useful; You can extend it to a linked list of integers,
                   9944: like this:@footnote{This feature is also known as @emph{extended
                   9945: records}. It is the main innovation in the Oberon language; in other
                   9946: words, adding this feature to Modula-2 led Wirth to create a new
                   9947: language, write a new compiler etc.  Adding this feature to Forth just
                   9948: required a few lines of code.}
1.20      pazsan   9949: 
                   9950: @example
1.26      crook    9951: list%
                   9952:     cell% field intlist-int
                   9953: end-struct intlist%
1.20      pazsan   9954: @end example
                   9955: 
1.26      crook    9956: @code{intlist%} is a structure with two fields:
                   9957: @code{list-next} and @code{intlist-int}.
1.20      pazsan   9958: 
1.26      crook    9959: @cindex structures containing arrays
                   9960: You can specify an array type containing @emph{n} elements of
                   9961: type @code{foo%} like this:
1.20      pazsan   9962: 
                   9963: @example
1.26      crook    9964: foo% @emph{n} *
1.20      pazsan   9965: @end example
                   9966: 
1.26      crook    9967: You can use this array type in any place where you can use a normal
                   9968: type, e.g., when defining a @code{field}, or with
                   9969: @code{%allot}.
1.20      pazsan   9970: 
1.26      crook    9971: @cindex first field optimization
                   9972: The first field is at the base address of a structure and the word
                   9973: for this field (e.g., @code{list-next}) actually does not change
                   9974: the address on the stack. You may be tempted to leave it away in the
                   9975: interest of run-time and space efficiency. This is not necessary,
                   9976: because the structure package optimizes this case and compiling such
                   9977: words does not generate any code. So, in the interest of readability
                   9978: and maintainability you should include the word for the field when
                   9979: accessing the field.
1.20      pazsan   9980: 
1.26      crook    9981: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   9982: @subsection Structure Naming Convention
                   9983: @cindex structure naming convention
1.20      pazsan   9984: 
1.26      crook    9985: The field names that come to (my) mind are often quite generic, and,
                   9986: if used, would cause frequent name clashes. E.g., many structures
                   9987: probably contain a @code{counter} field. The structure names
                   9988: that come to (my) mind are often also the logical choice for the names
                   9989: of words that create such a structure.
1.20      pazsan   9990: 
1.26      crook    9991: Therefore, I have adopted the following naming conventions: 
1.20      pazsan   9992: 
1.26      crook    9993: @itemize @bullet
                   9994: @cindex field naming convention
                   9995: @item
                   9996: The names of fields are of the form
                   9997: @code{@emph{struct}-@emph{field}}, where
                   9998: @code{@emph{struct}} is the basic name of the structure, and
                   9999: @code{@emph{field}} is the basic name of the field. You can
                   10000: think of field words as converting the (address of the)
                   10001: structure into the (address of the) field.
1.20      pazsan   10002: 
1.26      crook    10003: @cindex structure naming convention
                   10004: @item
                   10005: The names of structures are of the form
                   10006: @code{@emph{struct}%}, where
                   10007: @code{@emph{struct}} is the basic name of the structure.
                   10008: @end itemize
1.20      pazsan   10009: 
1.26      crook    10010: This naming convention does not work that well for fields of extended
                   10011: structures; e.g., the integer list structure has a field
                   10012: @code{intlist-int}, but has @code{list-next}, not
                   10013: @code{intlist-next}.
1.20      pazsan   10014: 
1.26      crook    10015: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   10016: @subsection Structure Implementation
                   10017: @cindex structure implementation
                   10018: @cindex implementation of structures
1.20      pazsan   10019: 
1.26      crook    10020: The central idea in the implementation is to pass the data about the
                   10021: structure being built on the stack, not in some global
                   10022: variable. Everything else falls into place naturally once this design
                   10023: decision is made.
1.20      pazsan   10024: 
1.26      crook    10025: The type description on the stack is of the form @emph{align
                   10026: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   10027: very simple.
1.20      pazsan   10028: 
1.26      crook    10029: @code{field} is a defining word that uses @code{Create}
                   10030: and @code{DOES>}. The body of the field contains the offset
                   10031: of the field, and the normal @code{DOES>} action is simply:
1.20      pazsan   10032: 
                   10033: @example
1.48      anton    10034: @@ +
1.20      pazsan   10035: @end example
                   10036: 
1.23      crook    10037: @noindent
1.26      crook    10038: i.e., add the offset to the address, giving the stack effect
1.29      crook    10039: @i{addr1 -- addr2} for a field.
1.20      pazsan   10040: 
1.26      crook    10041: @cindex first field optimization, implementation
                   10042: This simple structure is slightly complicated by the optimization
                   10043: for fields with offset 0, which requires a different
                   10044: @code{DOES>}-part (because we cannot rely on there being
                   10045: something on the stack if such a field is invoked during
                   10046: compilation). Therefore, we put the different @code{DOES>}-parts
                   10047: in separate words, and decide which one to invoke based on the
                   10048: offset. For a zero offset, the field is basically a noop; it is
                   10049: immediate, and therefore no code is generated when it is compiled.
1.20      pazsan   10050: 
1.26      crook    10051: @node Structure Glossary,  , Structure Implementation, Structures
                   10052: @subsection Structure Glossary
                   10053: @cindex structure glossary
1.20      pazsan   10054: 
1.44      crook    10055: 
1.26      crook    10056: doc-%align
                   10057: doc-%alignment
                   10058: doc-%alloc
                   10059: doc-%allocate
                   10060: doc-%allot
                   10061: doc-cell%
                   10062: doc-char%
                   10063: doc-dfloat%
                   10064: doc-double%
                   10065: doc-end-struct
                   10066: doc-field
                   10067: doc-float%
                   10068: doc-naligned
                   10069: doc-sfloat%
                   10070: doc-%size
                   10071: doc-struct
1.23      crook    10072: 
1.44      crook    10073: 
1.26      crook    10074: @c -------------------------------------------------------------
                   10075: @node Object-oriented Forth, Passing Commands to the OS, Structures, Words
                   10076: @section Object-oriented Forth
1.20      pazsan   10077: 
1.26      crook    10078: Gforth comes with three packages for object-oriented programming:
                   10079: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   10080: is preloaded, so you have to @code{include} them before use. The most
                   10081: important differences between these packages (and others) are discussed
                   10082: in @ref{Comparison with other object models}. All packages are written
                   10083: in ANS Forth and can be used with any other ANS Forth.
1.20      pazsan   10084: 
1.26      crook    10085: @menu
1.48      anton    10086: * Why object-oriented programming?::  
                   10087: * Object-Oriented Terminology::  
                   10088: * Objects::                     
                   10089: * OOF::                         
                   10090: * Mini-OOF::                    
1.26      crook    10091: * Comparison with other object models::  
                   10092: @end menu
1.20      pazsan   10093: 
1.48      anton    10094: @c ----------------------------------------------------------------
                   10095: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   10096: @subsection Why object-oriented programming?
1.26      crook    10097: @cindex object-oriented programming motivation
                   10098: @cindex motivation for object-oriented programming
1.23      crook    10099: 
1.26      crook    10100: Often we have to deal with several data structures (@emph{objects}),
                   10101: that have to be treated similarly in some respects, but differently in
                   10102: others. Graphical objects are the textbook example: circles, triangles,
                   10103: dinosaurs, icons, and others, and we may want to add more during program
                   10104: development. We want to apply some operations to any graphical object,
                   10105: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   10106: has to do something different for every kind of object.
                   10107: @comment TODO add some other operations eg perimeter, area
                   10108: @comment and tie in to concrete examples later..
1.23      crook    10109: 
1.26      crook    10110: We could implement @code{draw} as a big @code{CASE}
                   10111: control structure that executes the appropriate code depending on the
                   10112: kind of object to be drawn. This would be not be very elegant, and,
                   10113: moreover, we would have to change @code{draw} every time we add
                   10114: a new kind of graphical object (say, a spaceship).
1.23      crook    10115: 
1.26      crook    10116: What we would rather do is: When defining spaceships, we would tell
                   10117: the system: ``Here's how you @code{draw} a spaceship; you figure
                   10118: out the rest''.
1.23      crook    10119: 
1.26      crook    10120: This is the problem that all systems solve that (rightfully) call
                   10121: themselves object-oriented; the object-oriented packages presented here
                   10122: solve this problem (and not much else).
                   10123: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.23      crook    10124: 
1.48      anton    10125: @c ------------------------------------------------------------------------
1.26      crook    10126: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
1.48      anton    10127: @subsection Object-Oriented Terminology
1.26      crook    10128: @cindex object-oriented terminology
                   10129: @cindex terminology for object-oriented programming
1.23      crook    10130: 
1.26      crook    10131: This section is mainly for reference, so you don't have to understand
                   10132: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   10133: short:
1.23      crook    10134: 
1.26      crook    10135: @table @emph
                   10136: @cindex class
                   10137: @item class
                   10138: a data structure definition with some extras.
1.23      crook    10139: 
1.26      crook    10140: @cindex object
                   10141: @item object
                   10142: an instance of the data structure described by the class definition.
1.23      crook    10143: 
1.26      crook    10144: @cindex instance variables
                   10145: @item instance variables
                   10146: fields of the data structure.
1.23      crook    10147: 
1.26      crook    10148: @cindex selector
                   10149: @cindex method selector
                   10150: @cindex virtual function
                   10151: @item selector
                   10152: (or @emph{method selector}) a word (e.g.,
                   10153: @code{draw}) that performs an operation on a variety of data
                   10154: structures (classes). A selector describes @emph{what} operation to
                   10155: perform. In C++ terminology: a (pure) virtual function.
1.23      crook    10156: 
1.26      crook    10157: @cindex method
                   10158: @item method
                   10159: the concrete definition that performs the operation
                   10160: described by the selector for a specific class. A method specifies
                   10161: @emph{how} the operation is performed for a specific class.
1.23      crook    10162: 
1.26      crook    10163: @cindex selector invocation
                   10164: @cindex message send
                   10165: @cindex invoking a selector
                   10166: @item selector invocation
                   10167: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   10168: is used for determining which method is used. In Smalltalk terminology:
                   10169: a message (consisting of the selector and the other arguments) is sent
                   10170: to the object.
1.1       anton    10171: 
1.26      crook    10172: @cindex receiving object
                   10173: @item receiving object
                   10174: the object used for determining the method executed by a selector
                   10175: invocation. In the @file{objects.fs} model, it is the object that is on
                   10176: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   10177: the Smalltalk @emph{message} terminology.)
1.1       anton    10178: 
1.26      crook    10179: @cindex child class
                   10180: @cindex parent class
                   10181: @cindex inheritance
                   10182: @item child class
                   10183: a class that has (@emph{inherits}) all properties (instance variables,
                   10184: selectors, methods) from a @emph{parent class}. In Smalltalk
                   10185: terminology: The subclass inherits from the superclass. In C++
                   10186: terminology: The derived class inherits from the base class.
1.1       anton    10187: 
1.26      crook    10188: @end table
1.21      crook    10189: 
1.26      crook    10190: @c If you wonder about the message sending terminology, it comes from
                   10191: @c a time when each object had it's own task and objects communicated via
                   10192: @c message passing; eventually the Smalltalk developers realized that
                   10193: @c they can do most things through simple (indirect) calls. They kept the
                   10194: @c terminology.
1.1       anton    10195: 
1.48      anton    10196: @c --------------------------------------------------------------
1.26      crook    10197: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   10198: @subsection The @file{objects.fs} model
                   10199: @cindex objects
                   10200: @cindex object-oriented programming
1.1       anton    10201: 
1.26      crook    10202: @cindex @file{objects.fs}
                   10203: @cindex @file{oof.fs}
1.1       anton    10204: 
1.37      anton    10205: This section describes the @file{objects.fs} package. This material also
1.66    ! anton    10206: has been published in M. Anton Ertl,
        !          10207: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
        !          10208: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
        !          10209: 37--43.
1.26      crook    10210: @c McKewan's and Zsoter's packages
1.1       anton    10211: 
1.26      crook    10212: This section assumes that you have read @ref{Structures}.
1.1       anton    10213: 
1.26      crook    10214: The techniques on which this model is based have been used to implement
                   10215: the parser generator, Gray, and have also been used in Gforth for
                   10216: implementing the various flavours of word lists (hashed or not,
                   10217: case-sensitive or not, special-purpose word lists for locals etc.).
1.1       anton    10218: 
                   10219: 
1.26      crook    10220: @menu
                   10221: * Properties of the Objects model::  
                   10222: * Basic Objects Usage::         
1.37      anton    10223: * The Objects base class::      
1.26      crook    10224: * Creating objects::            
                   10225: * Object-Oriented Programming Style::  
                   10226: * Class Binding::               
                   10227: * Method conveniences::         
                   10228: * Classes and Scoping::         
1.37      anton    10229: * Dividing classes::            
1.26      crook    10230: * Object Interfaces::           
                   10231: * Objects Implementation::      
                   10232: * Objects Glossary::            
                   10233: @end menu
1.1       anton    10234: 
1.26      crook    10235: Marcel Hendrix provided helpful comments on this section. Andras Zsoter
                   10236: and Bernd Paysan helped me with the related works section.
1.1       anton    10237: 
1.26      crook    10238: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   10239: @subsubsection Properties of the @file{objects.fs} model
                   10240: @cindex @file{objects.fs} properties
1.1       anton    10241: 
1.26      crook    10242: @itemize @bullet
                   10243: @item
                   10244: It is straightforward to pass objects on the stack. Passing
                   10245: selectors on the stack is a little less convenient, but possible.
1.1       anton    10246: 
1.26      crook    10247: @item
                   10248: Objects are just data structures in memory, and are referenced by their
                   10249: address. You can create words for objects with normal defining words
                   10250: like @code{constant}. Likewise, there is no difference between instance
                   10251: variables that contain objects and those that contain other data.
1.1       anton    10252: 
1.26      crook    10253: @item
                   10254: Late binding is efficient and easy to use.
1.21      crook    10255: 
1.26      crook    10256: @item
                   10257: It avoids parsing, and thus avoids problems with state-smartness
                   10258: and reduced extensibility; for convenience there are a few parsing
                   10259: words, but they have non-parsing counterparts. There are also a few
                   10260: defining words that parse. This is hard to avoid, because all standard
                   10261: defining words parse (except @code{:noname}); however, such
                   10262: words are not as bad as many other parsing words, because they are not
                   10263: state-smart.
1.21      crook    10264: 
1.26      crook    10265: @item
                   10266: It does not try to incorporate everything. It does a few things and does
                   10267: them well (IMO). In particular, this model was not designed to support
                   10268: information hiding (although it has features that may help); you can use
                   10269: a separate package for achieving this.
1.21      crook    10270: 
1.26      crook    10271: @item
                   10272: It is layered; you don't have to learn and use all features to use this
1.49      anton    10273: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   10274: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
1.26      crook    10275: are optional and independent of each other.
1.21      crook    10276: 
1.26      crook    10277: @item
                   10278: An implementation in ANS Forth is available.
1.21      crook    10279: 
1.26      crook    10280: @end itemize
1.21      crook    10281: 
                   10282: 
1.26      crook    10283: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   10284: @subsubsection Basic @file{objects.fs} Usage
                   10285: @cindex basic objects usage
                   10286: @cindex objects, basic usage
1.21      crook    10287: 
1.26      crook    10288: You can define a class for graphical objects like this:
1.21      crook    10289: 
1.26      crook    10290: @cindex @code{class} usage
                   10291: @cindex @code{end-class} usage
                   10292: @cindex @code{selector} usage
                   10293: @example
                   10294: object class \ "object" is the parent class
                   10295:   selector draw ( x y graphical -- )
                   10296: end-class graphical
                   10297: @end example
1.21      crook    10298: 
1.26      crook    10299: This code defines a class @code{graphical} with an
                   10300: operation @code{draw}.  We can perform the operation
                   10301: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    10302: 
1.26      crook    10303: @example
                   10304: 100 100 t-rex draw
                   10305: @end example
1.21      crook    10306: 
1.26      crook    10307: @noindent
                   10308: where @code{t-rex} is a word (say, a constant) that produces a
                   10309: graphical object.
1.21      crook    10310: 
1.29      crook    10311: @comment TODO add a 2nd operation eg perimeter.. and use for
1.26      crook    10312: @comment a concrete example
1.21      crook    10313: 
1.26      crook    10314: @cindex abstract class
                   10315: How do we create a graphical object? With the present definitions,
                   10316: we cannot create a useful graphical object. The class
                   10317: @code{graphical} describes graphical objects in general, but not
                   10318: any concrete graphical object type (C++ users would call it an
                   10319: @emph{abstract class}); e.g., there is no method for the selector
                   10320: @code{draw} in the class @code{graphical}.
1.21      crook    10321: 
1.26      crook    10322: For concrete graphical objects, we define child classes of the
                   10323: class @code{graphical}, e.g.:
1.21      crook    10324: 
1.26      crook    10325: @cindex @code{overrides} usage
                   10326: @cindex @code{field} usage in class definition
                   10327: @example
                   10328: graphical class \ "graphical" is the parent class
                   10329:   cell% field circle-radius
1.21      crook    10330: 
1.26      crook    10331: :noname ( x y circle -- )
                   10332:   circle-radius @@ draw-circle ;
                   10333: overrides draw
1.21      crook    10334: 
1.26      crook    10335: :noname ( n-radius circle -- )
                   10336:   circle-radius ! ;
                   10337: overrides construct
1.21      crook    10338: 
1.26      crook    10339: end-class circle
1.21      crook    10340: @end example
                   10341: 
1.26      crook    10342: Here we define a class @code{circle} as a child of @code{graphical},
                   10343: with field @code{circle-radius} (which behaves just like a field
                   10344: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   10345: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   10346: defined in @code{object}, the parent class of @code{graphical}).
1.21      crook    10347: 
1.26      crook    10348: Now we can create a circle on the heap (i.e.,
                   10349: @code{allocate}d memory) with:
1.21      crook    10350: 
1.26      crook    10351: @cindex @code{heap-new} usage
1.21      crook    10352: @example
1.26      crook    10353: 50 circle heap-new constant my-circle
                   10354: @end example
1.21      crook    10355: 
1.26      crook    10356: @noindent
                   10357: @code{heap-new} invokes @code{construct}, thus
                   10358: initializing the field @code{circle-radius} with 50. We can draw
                   10359: this new circle at (100,100) with:
1.21      crook    10360: 
1.26      crook    10361: @example
                   10362: 100 100 my-circle draw
1.21      crook    10363: @end example
                   10364: 
1.26      crook    10365: @cindex selector invocation, restrictions
                   10366: @cindex class definition, restrictions
                   10367: Note: You can only invoke a selector if the object on the TOS
                   10368: (the receiving object) belongs to the class where the selector was
                   10369: defined or one of its descendents; e.g., you can invoke
                   10370: @code{draw} only for objects belonging to @code{graphical}
                   10371: or its descendents (e.g., @code{circle}).  Immediately before
                   10372: @code{end-class}, the search order has to be the same as
                   10373: immediately after @code{class}.
1.21      crook    10374: 
1.26      crook    10375: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   10376: @subsubsection The @file{object.fs} base class
                   10377: @cindex @code{object} class
1.21      crook    10378: 
1.26      crook    10379: When you define a class, you have to specify a parent class.  So how do
                   10380: you start defining classes? There is one class available from the start:
                   10381: @code{object}. It is ancestor for all classes and so is the
                   10382: only class that has no parent. It has two selectors: @code{construct}
                   10383: and @code{print}.
1.21      crook    10384: 
1.26      crook    10385: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   10386: @subsubsection Creating objects
                   10387: @cindex creating objects
                   10388: @cindex object creation
                   10389: @cindex object allocation options
1.21      crook    10390: 
1.26      crook    10391: @cindex @code{heap-new} discussion
                   10392: @cindex @code{dict-new} discussion
                   10393: @cindex @code{construct} discussion
                   10394: You can create and initialize an object of a class on the heap with
                   10395: @code{heap-new} ( ... class -- object ) and in the dictionary
                   10396: (allocation with @code{allot}) with @code{dict-new} (
                   10397: ... class -- object ). Both words invoke @code{construct}, which
                   10398: consumes the stack items indicated by "..." above.
1.21      crook    10399: 
1.26      crook    10400: @cindex @code{init-object} discussion
                   10401: @cindex @code{class-inst-size} discussion
                   10402: If you want to allocate memory for an object yourself, you can get its
                   10403: alignment and size with @code{class-inst-size 2@@} ( class --
                   10404: align size ). Once you have memory for an object, you can initialize
                   10405: it with @code{init-object} ( ... class object -- );
                   10406: @code{construct} does only a part of the necessary work.
1.21      crook    10407: 
1.26      crook    10408: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   10409: @subsubsection Object-Oriented Programming Style
                   10410: @cindex object-oriented programming style
1.47      crook    10411: @cindex programming style, object-oriented
1.21      crook    10412: 
1.26      crook    10413: This section is not exhaustive.
1.1       anton    10414: 
1.26      crook    10415: @cindex stack effects of selectors
                   10416: @cindex selectors and stack effects
                   10417: In general, it is a good idea to ensure that all methods for the
                   10418: same selector have the same stack effect: when you invoke a selector,
                   10419: you often have no idea which method will be invoked, so, unless all
                   10420: methods have the same stack effect, you will not know the stack effect
                   10421: of the selector invocation.
1.21      crook    10422: 
1.26      crook    10423: One exception to this rule is methods for the selector
                   10424: @code{construct}. We know which method is invoked, because we
                   10425: specify the class to be constructed at the same place. Actually, I
                   10426: defined @code{construct} as a selector only to give the users a
                   10427: convenient way to specify initialization. The way it is used, a
                   10428: mechanism different from selector invocation would be more natural
                   10429: (but probably would take more code and more space to explain).
1.21      crook    10430: 
1.26      crook    10431: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   10432: @subsubsection Class Binding
                   10433: @cindex class binding
                   10434: @cindex early binding
1.21      crook    10435: 
1.26      crook    10436: @cindex late binding
                   10437: Normal selector invocations determine the method at run-time depending
                   10438: on the class of the receiving object. This run-time selection is called
1.29      crook    10439: @i{late binding}.
1.21      crook    10440: 
1.26      crook    10441: Sometimes it's preferable to invoke a different method. For example,
                   10442: you might want to use the simple method for @code{print}ing
                   10443: @code{object}s instead of the possibly long-winded @code{print} method
                   10444: of the receiver class. You can achieve this by replacing the invocation
                   10445: of @code{print} with:
1.21      crook    10446: 
1.26      crook    10447: @cindex @code{[bind]} usage
                   10448: @example
                   10449: [bind] object print
1.21      crook    10450: @end example
                   10451: 
1.26      crook    10452: @noindent
                   10453: in compiled code or:
1.21      crook    10454: 
1.26      crook    10455: @cindex @code{bind} usage
1.21      crook    10456: @example
1.26      crook    10457: bind object print
1.21      crook    10458: @end example
                   10459: 
1.26      crook    10460: @cindex class binding, alternative to
                   10461: @noindent
                   10462: in interpreted code. Alternatively, you can define the method with a
                   10463: name (e.g., @code{print-object}), and then invoke it through the
                   10464: name. Class binding is just a (often more convenient) way to achieve
                   10465: the same effect; it avoids name clutter and allows you to invoke
                   10466: methods directly without naming them first.
                   10467: 
                   10468: @cindex superclass binding
                   10469: @cindex parent class binding
                   10470: A frequent use of class binding is this: When we define a method
                   10471: for a selector, we often want the method to do what the selector does
                   10472: in the parent class, and a little more. There is a special word for
                   10473: this purpose: @code{[parent]}; @code{[parent]
                   10474: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   10475: selector}}, where @code{@emph{parent}} is the parent
                   10476: class of the current class. E.g., a method definition might look like:
1.21      crook    10477: 
1.26      crook    10478: @cindex @code{[parent]} usage
1.21      crook    10479: @example
1.26      crook    10480: :noname
                   10481:   dup [parent] foo \ do parent's foo on the receiving object
                   10482:   ... \ do some more
                   10483: ; overrides foo
1.21      crook    10484: @end example
                   10485: 
1.26      crook    10486: @cindex class binding as optimization
                   10487: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10488: March 1997), Andrew McKewan presents class binding as an optimization
                   10489: technique. I recommend not using it for this purpose unless you are in
                   10490: an emergency. Late binding is pretty fast with this model anyway, so the
                   10491: benefit of using class binding is small; the cost of using class binding
                   10492: where it is not appropriate is reduced maintainability.
1.21      crook    10493: 
1.26      crook    10494: While we are at programming style questions: You should bind
                   10495: selectors only to ancestor classes of the receiving object. E.g., say,
                   10496: you know that the receiving object is of class @code{foo} or its
                   10497: descendents; then you should bind only to @code{foo} and its
                   10498: ancestors.
1.21      crook    10499: 
1.26      crook    10500: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10501: @subsubsection Method conveniences
                   10502: @cindex method conveniences
1.1       anton    10503: 
1.26      crook    10504: In a method you usually access the receiving object pretty often.  If
                   10505: you define the method as a plain colon definition (e.g., with
                   10506: @code{:noname}), you may have to do a lot of stack
                   10507: gymnastics. To avoid this, you can define the method with @code{m:
                   10508: ... ;m}. E.g., you could define the method for
                   10509: @code{draw}ing a @code{circle} with
1.20      pazsan   10510: 
1.26      crook    10511: @cindex @code{this} usage
                   10512: @cindex @code{m:} usage
                   10513: @cindex @code{;m} usage
                   10514: @example
                   10515: m: ( x y circle -- )
                   10516:   ( x y ) this circle-radius @@ draw-circle ;m
                   10517: @end example
1.20      pazsan   10518: 
1.26      crook    10519: @cindex @code{exit} in @code{m: ... ;m}
                   10520: @cindex @code{exitm} discussion
                   10521: @cindex @code{catch} in @code{m: ... ;m}
                   10522: When this method is executed, the receiver object is removed from the
                   10523: stack; you can access it with @code{this} (admittedly, in this
                   10524: example the use of @code{m: ... ;m} offers no advantage). Note
                   10525: that I specify the stack effect for the whole method (i.e. including
                   10526: the receiver object), not just for the code between @code{m:}
                   10527: and @code{;m}. You cannot use @code{exit} in
                   10528: @code{m:...;m}; instead, use
                   10529: @code{exitm}.@footnote{Moreover, for any word that calls
                   10530: @code{catch} and was defined before loading
                   10531: @code{objects.fs}, you have to redefine it like I redefined
                   10532: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.20      pazsan   10533: 
1.26      crook    10534: @cindex @code{inst-var} usage
                   10535: You will frequently use sequences of the form @code{this
                   10536: @emph{field}} (in the example above: @code{this
                   10537: circle-radius}). If you use the field only in this way, you can
                   10538: define it with @code{inst-var} and eliminate the
                   10539: @code{this} before the field name. E.g., the @code{circle}
                   10540: class above could also be defined with:
1.20      pazsan   10541: 
1.26      crook    10542: @example
                   10543: graphical class
                   10544:   cell% inst-var radius
1.20      pazsan   10545: 
1.26      crook    10546: m: ( x y circle -- )
                   10547:   radius @@ draw-circle ;m
                   10548: overrides draw
1.20      pazsan   10549: 
1.26      crook    10550: m: ( n-radius circle -- )
                   10551:   radius ! ;m
                   10552: overrides construct
1.12      anton    10553: 
1.26      crook    10554: end-class circle
                   10555: @end example
1.12      anton    10556: 
1.26      crook    10557: @code{radius} can only be used in @code{circle} and its
                   10558: descendent classes and inside @code{m:...;m}.
1.12      anton    10559: 
1.26      crook    10560: @cindex @code{inst-value} usage
                   10561: You can also define fields with @code{inst-value}, which is
                   10562: to @code{inst-var} what @code{value} is to
                   10563: @code{variable}.  You can change the value of such a field with
                   10564: @code{[to-inst]}.  E.g., we could also define the class
                   10565: @code{circle} like this:
1.12      anton    10566: 
1.26      crook    10567: @example
                   10568: graphical class
                   10569:   inst-value radius
1.12      anton    10570: 
1.26      crook    10571: m: ( x y circle -- )
                   10572:   radius draw-circle ;m
                   10573: overrides draw
1.12      anton    10574: 
1.26      crook    10575: m: ( n-radius circle -- )
                   10576:   [to-inst] radius ;m
                   10577: overrides construct
1.21      crook    10578: 
1.26      crook    10579: end-class circle
1.12      anton    10580: @end example
                   10581: 
1.38      anton    10582: Finally, you can define named methods with @code{:m}.  One use of this
                   10583: feature is the definition of words that occur only in one class and are
                   10584: not intended to be overridden, but which still need method context
                   10585: (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   10586: would be bound frequently, if defined anonymously.
                   10587: 
1.12      anton    10588: 
1.37      anton    10589: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
1.26      crook    10590: @subsubsection Classes and Scoping
                   10591: @cindex classes and scoping
                   10592: @cindex scoping and classes
1.12      anton    10593: 
1.26      crook    10594: Inheritance is frequent, unlike structure extension. This exacerbates
                   10595: the problem with the field name convention (@pxref{Structure Naming
                   10596: Convention}): One always has to remember in which class the field was
                   10597: originally defined; changing a part of the class structure would require
                   10598: changes for renaming in otherwise unaffected code.
1.12      anton    10599: 
1.26      crook    10600: @cindex @code{inst-var} visibility
                   10601: @cindex @code{inst-value} visibility
                   10602: To solve this problem, I added a scoping mechanism (which was not in my
                   10603: original charter): A field defined with @code{inst-var} (or
                   10604: @code{inst-value}) is visible only in the class where it is defined and in
                   10605: the descendent classes of this class.  Using such fields only makes
                   10606: sense in @code{m:}-defined methods in these classes anyway.
1.12      anton    10607: 
1.26      crook    10608: This scoping mechanism allows us to use the unadorned field name,
                   10609: because name clashes with unrelated words become much less likely.
1.12      anton    10610: 
1.26      crook    10611: @cindex @code{protected} discussion
                   10612: @cindex @code{private} discussion
                   10613: Once we have this mechanism, we can also use it for controlling the
                   10614: visibility of other words: All words defined after
                   10615: @code{protected} are visible only in the current class and its
                   10616: descendents. @code{public} restores the compilation
                   10617: (i.e. @code{current}) word list that was in effect before. If you
                   10618: have several @code{protected}s without an intervening
                   10619: @code{public} or @code{set-current}, @code{public}
                   10620: will restore the compilation word list in effect before the first of
                   10621: these @code{protected}s.
1.12      anton    10622: 
1.37      anton    10623: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   10624: @subsubsection Dividing classes
                   10625: @cindex Dividing classes
                   10626: @cindex @code{methods}...@code{end-methods}
                   10627: 
                   10628: You may want to do the definition of methods separate from the
                   10629: definition of the class, its selectors, fields, and instance variables,
                   10630: i.e., separate the implementation from the definition.  You can do this
                   10631: in the following way:
                   10632: 
                   10633: @example
                   10634: graphical class
                   10635:   inst-value radius
                   10636: end-class circle
                   10637: 
                   10638: ... \ do some other stuff
                   10639: 
                   10640: circle methods \ now we are ready
                   10641: 
                   10642: m: ( x y circle -- )
                   10643:   radius draw-circle ;m
                   10644: overrides draw
                   10645: 
                   10646: m: ( n-radius circle -- )
                   10647:   [to-inst] radius ;m
                   10648: overrides construct
                   10649: 
                   10650: end-methods
                   10651: @end example
                   10652: 
                   10653: You can use several @code{methods}...@code{end-methods} sections.  The
                   10654: only things you can do to the class in these sections are: defining
                   10655: methods, and overriding the class's selectors.  You must not define new
                   10656: selectors or fields.
                   10657: 
                   10658: Note that you often have to override a selector before using it.  In
                   10659: particular, you usually have to override @code{construct} with a new
                   10660: method before you can invoke @code{heap-new} and friends.  E.g., you
                   10661: must not create a circle before the @code{overrides construct} sequence
                   10662: in the example above.
                   10663: 
                   10664: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
1.26      crook    10665: @subsubsection Object Interfaces
                   10666: @cindex object interfaces
                   10667: @cindex interfaces for objects
1.12      anton    10668: 
1.26      crook    10669: In this model you can only call selectors defined in the class of the
                   10670: receiving objects or in one of its ancestors. If you call a selector
                   10671: with a receiving object that is not in one of these classes, the
                   10672: result is undefined; if you are lucky, the program crashes
                   10673: immediately.
1.12      anton    10674: 
1.26      crook    10675: @cindex selectors common to hardly-related classes
                   10676: Now consider the case when you want to have a selector (or several)
                   10677: available in two classes: You would have to add the selector to a
                   10678: common ancestor class, in the worst case to @code{object}. You
                   10679: may not want to do this, e.g., because someone else is responsible for
                   10680: this ancestor class.
1.12      anton    10681: 
1.26      crook    10682: The solution for this problem is interfaces. An interface is a
                   10683: collection of selectors. If a class implements an interface, the
                   10684: selectors become available to the class and its descendents. A class
                   10685: can implement an unlimited number of interfaces. For the problem
                   10686: discussed above, we would define an interface for the selector(s), and
                   10687: both classes would implement the interface.
1.12      anton    10688: 
1.26      crook    10689: As an example, consider an interface @code{storage} for
                   10690: writing objects to disk and getting them back, and a class
                   10691: @code{foo} that implements it. The code would look like this:
1.12      anton    10692: 
1.26      crook    10693: @cindex @code{interface} usage
                   10694: @cindex @code{end-interface} usage
                   10695: @cindex @code{implementation} usage
                   10696: @example
                   10697: interface
                   10698:   selector write ( file object -- )
                   10699:   selector read1 ( file object -- )
                   10700: end-interface storage
1.12      anton    10701: 
1.26      crook    10702: bar class
                   10703:   storage implementation
1.12      anton    10704: 
1.26      crook    10705: ... overrides write
1.37      anton    10706: ... overrides read1
1.26      crook    10707: ...
                   10708: end-class foo
1.12      anton    10709: @end example
                   10710: 
1.26      crook    10711: @noindent
1.29      crook    10712: (I would add a word @code{read} @i{( file -- object )} that uses
1.26      crook    10713: @code{read1} internally, but that's beyond the point illustrated
                   10714: here.)
1.12      anton    10715: 
1.26      crook    10716: Note that you cannot use @code{protected} in an interface; and
                   10717: of course you cannot define fields.
1.12      anton    10718: 
1.26      crook    10719: In the Neon model, all selectors are available for all classes;
                   10720: therefore it does not need interfaces. The price you pay in this model
                   10721: is slower late binding, and therefore, added complexity to avoid late
                   10722: binding.
1.12      anton    10723: 
1.26      crook    10724: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   10725: @subsubsection @file{objects.fs} Implementation
                   10726: @cindex @file{objects.fs} implementation
1.12      anton    10727: 
1.26      crook    10728: @cindex @code{object-map} discussion
                   10729: An object is a piece of memory, like one of the data structures
                   10730: described with @code{struct...end-struct}. It has a field
                   10731: @code{object-map} that points to the method map for the object's
                   10732: class.
1.12      anton    10733: 
1.26      crook    10734: @cindex method map
                   10735: @cindex virtual function table
                   10736: The @emph{method map}@footnote{This is Self terminology; in C++
                   10737: terminology: virtual function table.} is an array that contains the
1.29      crook    10738: execution tokens (@i{xt}s) of the methods for the object's class. Each
1.26      crook    10739: selector contains an offset into a method map.
1.12      anton    10740: 
1.26      crook    10741: @cindex @code{selector} implementation, class
                   10742: @code{selector} is a defining word that uses
                   10743: @code{CREATE} and @code{DOES>}. The body of the
1.44      crook    10744: selector contains the offset; the @code{DOES>} action for a
1.26      crook    10745: class selector is, basically:
1.21      crook    10746: 
1.26      crook    10747: @example
                   10748: ( object addr ) @@ over object-map @@ + @@ execute
                   10749: @end example
1.12      anton    10750: 
1.26      crook    10751: Since @code{object-map} is the first field of the object, it
                   10752: does not generate any code. As you can see, calling a selector has a
                   10753: small, constant cost.
1.12      anton    10754: 
1.26      crook    10755: @cindex @code{current-interface} discussion
                   10756: @cindex class implementation and representation
                   10757: A class is basically a @code{struct} combined with a method
                   10758: map. During the class definition the alignment and size of the class
                   10759: are passed on the stack, just as with @code{struct}s, so
                   10760: @code{field} can also be used for defining class
                   10761: fields. However, passing more items on the stack would be
                   10762: inconvenient, so @code{class} builds a data structure in memory,
                   10763: which is accessed through the variable
                   10764: @code{current-interface}. After its definition is complete, the
                   10765: class is represented on the stack by a pointer (e.g., as parameter for
                   10766: a child class definition).
1.1       anton    10767: 
1.26      crook    10768: A new class starts off with the alignment and size of its parent,
                   10769: and a copy of the parent's method map. Defining new fields extends the
                   10770: size and alignment; likewise, defining new selectors extends the
1.29      crook    10771: method map. @code{overrides} just stores a new @i{xt} in the method
1.26      crook    10772: map at the offset given by the selector.
1.20      pazsan   10773: 
1.26      crook    10774: @cindex class binding, implementation
1.29      crook    10775: Class binding just gets the @i{xt} at the offset given by the selector
1.26      crook    10776: from the class's method map and @code{compile,}s (in the case of
                   10777: @code{[bind]}) it.
1.21      crook    10778: 
1.26      crook    10779: @cindex @code{this} implementation
                   10780: @cindex @code{catch} and @code{this}
                   10781: @cindex @code{this} and @code{catch}
                   10782: I implemented @code{this} as a @code{value}. At the
                   10783: start of an @code{m:...;m} method the old @code{this} is
                   10784: stored to the return stack and restored at the end; and the object on
                   10785: the TOS is stored @code{TO this}. This technique has one
                   10786: disadvantage: If the user does not leave the method via
                   10787: @code{;m}, but via @code{throw} or @code{exit},
                   10788: @code{this} is not restored (and @code{exit} may
                   10789: crash). To deal with the @code{throw} problem, I have redefined
                   10790: @code{catch} to save and restore @code{this}; the same
                   10791: should be done with any word that can catch an exception. As for
                   10792: @code{exit}, I simply forbid it (as a replacement, there is
                   10793: @code{exitm}).
1.21      crook    10794: 
1.26      crook    10795: @cindex @code{inst-var} implementation
                   10796: @code{inst-var} is just the same as @code{field}, with
                   10797: a different @code{DOES>} action:
                   10798: @example
                   10799: @@ this +
                   10800: @end example
                   10801: Similar for @code{inst-value}.
1.21      crook    10802: 
1.26      crook    10803: @cindex class scoping implementation
                   10804: Each class also has a word list that contains the words defined with
                   10805: @code{inst-var} and @code{inst-value}, and its protected
                   10806: words. It also has a pointer to its parent. @code{class} pushes
                   10807: the word lists of the class and all its ancestors onto the search order stack,
                   10808: and @code{end-class} drops them.
1.21      crook    10809: 
1.26      crook    10810: @cindex interface implementation
                   10811: An interface is like a class without fields, parent and protected
                   10812: words; i.e., it just has a method map. If a class implements an
                   10813: interface, its method map contains a pointer to the method map of the
                   10814: interface. The positive offsets in the map are reserved for class
                   10815: methods, therefore interface map pointers have negative
                   10816: offsets. Interfaces have offsets that are unique throughout the
                   10817: system, unlike class selectors, whose offsets are only unique for the
                   10818: classes where the selector is available (invokable).
1.21      crook    10819: 
1.26      crook    10820: This structure means that interface selectors have to perform one
                   10821: indirection more than class selectors to find their method. Their body
                   10822: contains the interface map pointer offset in the class method map, and
                   10823: the method offset in the interface method map. The
                   10824: @code{does>} action for an interface selector is, basically:
1.21      crook    10825: 
                   10826: @example
1.26      crook    10827: ( object selector-body )
                   10828: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   10829: swap object-map @@ + @@ ( object selector-body map )
                   10830: swap selector-offset @@ + @@ execute
1.21      crook    10831: @end example
                   10832: 
1.26      crook    10833: where @code{object-map} and @code{selector-offset} are
                   10834: first fields and generate no code.
                   10835: 
                   10836: As a concrete example, consider the following code:
1.21      crook    10837: 
1.26      crook    10838: @example
                   10839: interface
                   10840:   selector if1sel1
                   10841:   selector if1sel2
                   10842: end-interface if1
1.21      crook    10843: 
1.26      crook    10844: object class
                   10845:   if1 implementation
                   10846:   selector cl1sel1
                   10847:   cell% inst-var cl1iv1
1.21      crook    10848: 
1.26      crook    10849: ' m1 overrides construct
                   10850: ' m2 overrides if1sel1
                   10851: ' m3 overrides if1sel2
                   10852: ' m4 overrides cl1sel2
                   10853: end-class cl1
1.21      crook    10854: 
1.26      crook    10855: create obj1 object dict-new drop
                   10856: create obj2 cl1    dict-new drop
                   10857: @end example
1.21      crook    10858: 
1.26      crook    10859: The data structure created by this code (including the data structure
                   10860: for @code{object}) is shown in the <a
                   10861: href="objects-implementation.eps">figure</a>, assuming a cell size of 4.
1.29      crook    10862: @comment TODO add this diagram..
1.21      crook    10863: 
1.26      crook    10864: @node Objects Glossary,  , Objects Implementation, Objects
                   10865: @subsubsection @file{objects.fs} Glossary
                   10866: @cindex @file{objects.fs} Glossary
1.21      crook    10867: 
1.44      crook    10868: 
1.26      crook    10869: doc---objects-bind
                   10870: doc---objects-<bind>
                   10871: doc---objects-bind'
                   10872: doc---objects-[bind]
                   10873: doc---objects-class
                   10874: doc---objects-class->map
                   10875: doc---objects-class-inst-size
                   10876: doc---objects-class-override!
                   10877: doc---objects-construct
                   10878: doc---objects-current'
                   10879: doc---objects-[current]
                   10880: doc---objects-current-interface
                   10881: doc---objects-dict-new
                   10882: doc---objects-drop-order
                   10883: doc---objects-end-class
                   10884: doc---objects-end-class-noname
                   10885: doc---objects-end-interface
                   10886: doc---objects-end-interface-noname
1.37      anton    10887: doc---objects-end-methods
1.26      crook    10888: doc---objects-exitm
                   10889: doc---objects-heap-new
                   10890: doc---objects-implementation
                   10891: doc---objects-init-object
                   10892: doc---objects-inst-value
                   10893: doc---objects-inst-var
                   10894: doc---objects-interface
1.38      anton    10895: doc---objects-m:
                   10896: doc---objects-:m
1.26      crook    10897: doc---objects-;m
                   10898: doc---objects-method
1.37      anton    10899: doc---objects-methods
1.26      crook    10900: doc---objects-object
                   10901: doc---objects-overrides
                   10902: doc---objects-[parent]
                   10903: doc---objects-print
                   10904: doc---objects-protected
                   10905: doc---objects-public
                   10906: doc---objects-push-order
                   10907: doc---objects-selector
                   10908: doc---objects-this
                   10909: doc---objects-<to-inst>
                   10910: doc---objects-[to-inst]
                   10911: doc---objects-to-this
                   10912: doc---objects-xt-new
1.21      crook    10913: 
1.44      crook    10914: 
1.26      crook    10915: @c -------------------------------------------------------------
                   10916: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   10917: @subsection The @file{oof.fs} model
                   10918: @cindex oof
                   10919: @cindex object-oriented programming
1.21      crook    10920: 
1.26      crook    10921: @cindex @file{objects.fs}
                   10922: @cindex @file{oof.fs}
1.21      crook    10923: 
1.26      crook    10924: This section describes the @file{oof.fs} package.
1.21      crook    10925: 
1.26      crook    10926: The package described in this section has been used in bigFORTH since 1991, and
                   10927: used for two large applications: a chromatographic system used to
                   10928: create new medicaments, and a graphic user interface library (MINOS).
1.21      crook    10929: 
1.26      crook    10930: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   10931: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   10932: 10(2), 1994.
1.21      crook    10933: 
1.26      crook    10934: @menu
                   10935: * Properties of the OOF model::
                   10936: * Basic OOF Usage::
                   10937: * The OOF base class::
                   10938: * Class Declaration::
                   10939: * Class Implementation::
                   10940: @end menu
1.21      crook    10941: 
1.26      crook    10942: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   10943: @subsubsection Properties of the @file{oof.fs} model
                   10944: @cindex @file{oof.fs} properties
1.21      crook    10945: 
1.26      crook    10946: @itemize @bullet
                   10947: @item
                   10948: This model combines object oriented programming with information
                   10949: hiding. It helps you writing large application, where scoping is
                   10950: necessary, because it provides class-oriented scoping.
1.21      crook    10951: 
1.26      crook    10952: @item
                   10953: Named objects, object pointers, and object arrays can be created,
                   10954: selector invocation uses the ``object selector'' syntax. Selector invocation
                   10955: to objects and/or selectors on the stack is a bit less convenient, but
                   10956: possible.
1.21      crook    10957: 
1.26      crook    10958: @item
                   10959: Selector invocation and instance variable usage of the active object is
                   10960: straightforward, since both make use of the active object.
1.21      crook    10961: 
1.26      crook    10962: @item
                   10963: Late binding is efficient and easy to use.
1.21      crook    10964: 
1.26      crook    10965: @item
                   10966: State-smart objects parse selectors. However, extensibility is provided
                   10967: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.21      crook    10968: 
                   10969: @item
1.26      crook    10970: An implementation in ANS Forth is available.
                   10971: 
1.21      crook    10972: @end itemize
                   10973: 
                   10974: 
1.26      crook    10975: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   10976: @subsubsection Basic @file{oof.fs} Usage
                   10977: @cindex @file{oof.fs} usage
                   10978: 
                   10979: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.21      crook    10980: 
1.26      crook    10981: You can define a class for graphical objects like this:
1.21      crook    10982: 
1.26      crook    10983: @cindex @code{class} usage
                   10984: @cindex @code{class;} usage
                   10985: @cindex @code{method} usage
                   10986: @example
                   10987: object class graphical \ "object" is the parent class
                   10988:   method draw ( x y graphical -- )
                   10989: class;
                   10990: @end example
1.21      crook    10991: 
1.26      crook    10992: This code defines a class @code{graphical} with an
                   10993: operation @code{draw}.  We can perform the operation
                   10994: @code{draw} on any @code{graphical} object, e.g.:
1.21      crook    10995: 
1.26      crook    10996: @example
                   10997: 100 100 t-rex draw
                   10998: @end example
1.21      crook    10999: 
1.26      crook    11000: @noindent
                   11001: where @code{t-rex} is an object or object pointer, created with e.g.
                   11002: @code{graphical : t-rex}.
1.21      crook    11003: 
1.26      crook    11004: @cindex abstract class
                   11005: How do we create a graphical object? With the present definitions,
                   11006: we cannot create a useful graphical object. The class
                   11007: @code{graphical} describes graphical objects in general, but not
                   11008: any concrete graphical object type (C++ users would call it an
                   11009: @emph{abstract class}); e.g., there is no method for the selector
                   11010: @code{draw} in the class @code{graphical}.
1.21      crook    11011: 
1.26      crook    11012: For concrete graphical objects, we define child classes of the
                   11013: class @code{graphical}, e.g.:
1.21      crook    11014: 
                   11015: @example
1.26      crook    11016: graphical class circle \ "graphical" is the parent class
                   11017:   cell var circle-radius
                   11018: how:
                   11019:   : draw ( x y -- )
                   11020:     circle-radius @@ draw-circle ;
                   11021: 
                   11022:   : init ( n-radius -- (
                   11023:     circle-radius ! ;
                   11024: class;
                   11025: @end example
                   11026: 
                   11027: Here we define a class @code{circle} as a child of @code{graphical},
                   11028: with a field @code{circle-radius}; it defines new methods for the
                   11029: selectors @code{draw} and @code{init} (@code{init} is defined in
                   11030: @code{object}, the parent class of @code{graphical}).
1.21      crook    11031: 
1.26      crook    11032: Now we can create a circle in the dictionary with:
1.21      crook    11033: 
1.26      crook    11034: @example
                   11035: 50 circle : my-circle
1.21      crook    11036: @end example
                   11037: 
1.26      crook    11038: @noindent
                   11039: @code{:} invokes @code{init}, thus initializing the field
                   11040: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   11041: with:
1.21      crook    11042: 
                   11043: @example
1.26      crook    11044: 100 100 my-circle draw
1.21      crook    11045: @end example
                   11046: 
1.26      crook    11047: @cindex selector invocation, restrictions
                   11048: @cindex class definition, restrictions
                   11049: Note: You can only invoke a selector if the receiving object belongs to
                   11050: the class where the selector was defined or one of its descendents;
                   11051: e.g., you can invoke @code{draw} only for objects belonging to
                   11052: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   11053: mechanism will check if you try to invoke a selector that is not
                   11054: defined in this class hierarchy, so you'll get an error at compilation
                   11055: time.
                   11056: 
                   11057: 
                   11058: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   11059: @subsubsection The @file{oof.fs} base class
                   11060: @cindex @file{oof.fs} base class
                   11061: 
                   11062: When you define a class, you have to specify a parent class.  So how do
                   11063: you start defining classes? There is one class available from the start:
                   11064: @code{object}. You have to use it as ancestor for all classes. It is the
                   11065: only class that has no parent. Classes are also objects, except that
                   11066: they don't have instance variables; class manipulation such as
                   11067: inheritance or changing definitions of a class is handled through
                   11068: selectors of the class @code{object}.
                   11069: 
                   11070: @code{object} provides a number of selectors:
                   11071: 
1.21      crook    11072: @itemize @bullet
                   11073: @item
1.26      crook    11074: @code{class} for subclassing, @code{definitions} to add definitions
                   11075: later on, and @code{class?} to get type informations (is the class a
                   11076: subclass of the class passed on the stack?).
1.44      crook    11077: 
1.26      crook    11078: doc---object-class
                   11079: doc---object-definitions
                   11080: doc---object-class?
                   11081: 
1.44      crook    11082: 
1.21      crook    11083: @item
1.26      crook    11084: @code{init} and @code{dispose} as constructor and destructor of the
                   11085: object. @code{init} is invocated after the object's memory is allocated,
                   11086: while @code{dispose} also handles deallocation. Thus if you redefine
                   11087: @code{dispose}, you have to call the parent's dispose with @code{super
                   11088: dispose}, too.
1.44      crook    11089: 
1.26      crook    11090: doc---object-init
                   11091: doc---object-dispose
                   11092: 
1.44      crook    11093: 
1.21      crook    11094: @item
1.26      crook    11095: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   11096: @code{[]} to create named and unnamed objects and object arrays or
                   11097: object pointers.
1.44      crook    11098: 
1.26      crook    11099: doc---object-new
                   11100: doc---object-new[]
                   11101: doc---object-:
                   11102: doc---object-ptr
                   11103: doc---object-asptr
                   11104: doc---object-[]
1.21      crook    11105: 
1.44      crook    11106: 
1.26      crook    11107: @item
                   11108: @code{::} and @code{super} for explicit scoping. You should use explicit
                   11109: scoping only for super classes or classes with the same set of instance
                   11110: variables. Explicitly-scoped selectors use early binding.
1.44      crook    11111: 
1.26      crook    11112: doc---object-::
                   11113: doc---object-super
1.21      crook    11114: 
1.44      crook    11115: 
1.26      crook    11116: @item
                   11117: @code{self} to get the address of the object
1.44      crook    11118: 
1.26      crook    11119: doc---object-self
1.21      crook    11120: 
1.44      crook    11121: 
1.21      crook    11122: @item
1.26      crook    11123: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   11124: pointers and instance defers.
1.44      crook    11125: 
1.26      crook    11126: doc---object-bind
                   11127: doc---object-bound
                   11128: doc---object-link
                   11129: doc---object-is
                   11130: 
1.44      crook    11131: 
1.21      crook    11132: @item
1.26      crook    11133: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   11134: form the stack, and @code{postpone} to generate selector invocation code.
1.44      crook    11135: 
1.26      crook    11136: doc---object-'
                   11137: doc---object-postpone
                   11138: 
1.44      crook    11139: 
1.21      crook    11140: @item
1.26      crook    11141: @code{with} and @code{endwith} to select the active object from the
                   11142: stack, and enable its scope. Using @code{with} and @code{endwith}
                   11143: also allows you to create code using selector @code{postpone} without being
                   11144: trapped by the state-smart objects.
1.44      crook    11145: 
1.26      crook    11146: doc---object-with
                   11147: doc---object-endwith
                   11148: 
1.44      crook    11149: 
1.21      crook    11150: @end itemize
                   11151: 
1.26      crook    11152: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   11153: @subsubsection Class Declaration
                   11154: @cindex class declaration
                   11155: 
                   11156: @itemize @bullet
                   11157: @item
                   11158: Instance variables
1.44      crook    11159: 
1.26      crook    11160: doc---oof-var
1.21      crook    11161: 
1.44      crook    11162: 
1.26      crook    11163: @item
                   11164: Object pointers
1.44      crook    11165: 
1.26      crook    11166: doc---oof-ptr
                   11167: doc---oof-asptr
1.21      crook    11168: 
1.44      crook    11169: 
1.26      crook    11170: @item
                   11171: Instance defers
1.44      crook    11172: 
1.26      crook    11173: doc---oof-defer
1.21      crook    11174: 
1.44      crook    11175: 
1.26      crook    11176: @item
                   11177: Method selectors
1.44      crook    11178: 
1.26      crook    11179: doc---oof-early
                   11180: doc---oof-method
1.21      crook    11181: 
1.44      crook    11182: 
1.26      crook    11183: @item
                   11184: Class-wide variables
1.44      crook    11185: 
1.26      crook    11186: doc---oof-static
1.21      crook    11187: 
1.44      crook    11188: 
1.26      crook    11189: @item
                   11190: End declaration
1.44      crook    11191: 
1.26      crook    11192: doc---oof-how:
                   11193: doc---oof-class;
1.21      crook    11194: 
1.44      crook    11195: 
1.26      crook    11196: @end itemize
1.21      crook    11197: 
1.26      crook    11198: @c -------------------------------------------------------------
                   11199: @node Class Implementation,  , Class Declaration, OOF
                   11200: @subsubsection Class Implementation
                   11201: @cindex class implementation
1.21      crook    11202: 
1.26      crook    11203: @c -------------------------------------------------------------
                   11204: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   11205: @subsection The @file{mini-oof.fs} model
                   11206: @cindex mini-oof
1.1       anton    11207: 
1.26      crook    11208: Gforth's third object oriented Forth package is a 12-liner. It uses a
                   11209: mixture of the @file{object.fs} and the @file{oof.fs} syntax,
                   11210: and reduces to the bare minimum of features. This is based on a posting
                   11211: of Bernd Paysan in comp.arch.
1.1       anton    11212: 
                   11213: @menu
1.48      anton    11214: * Basic Mini-OOF Usage::        
                   11215: * Mini-OOF Example::            
                   11216: * Mini-OOF Implementation::     
                   11217: * Comparison with other object models::  
1.1       anton    11218: @end menu
                   11219: 
1.26      crook    11220: @c -------------------------------------------------------------
1.48      anton    11221: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
1.26      crook    11222: @subsubsection Basic @file{mini-oof.fs} Usage
                   11223: @cindex mini-oof usage
1.1       anton    11224: 
1.28      crook    11225: There is a base class (@code{class}, which allocates one cell for the
                   11226: object pointer) plus seven other words: to define a method, a variable,
                   11227: a class; to end a class, to resolve binding, to allocate an object and
                   11228: to compile a class method.
1.26      crook    11229: @comment TODO better description of the last one
1.1       anton    11230: 
1.44      crook    11231: 
1.26      crook    11232: doc-object
                   11233: doc-method
                   11234: doc-var
                   11235: doc-class
                   11236: doc-end-class
                   11237: doc-defines
                   11238: doc-new
                   11239: doc-::
1.1       anton    11240: 
1.21      crook    11241: 
1.44      crook    11242: 
1.26      crook    11243: @c -------------------------------------------------------------
                   11244: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   11245: @subsubsection Mini-OOF Example
                   11246: @cindex mini-oof example
1.21      crook    11247: 
1.26      crook    11248: A short example shows how to use this package. This example, in slightly
                   11249: extended form, is supplied as @file{moof-exm.fs}
1.29      crook    11250: @comment TODO could flesh this out with some comments from the Forthwrite article
1.21      crook    11251: 
1.26      crook    11252: @example
                   11253: object class
                   11254:   method init
                   11255:   method draw
                   11256: end-class graphical
                   11257: @end example
1.21      crook    11258: 
1.26      crook    11259: This code defines a class @code{graphical} with an
                   11260: operation @code{draw}.  We can perform the operation
                   11261: @code{draw} on any @code{graphical} object, e.g.:
1.1       anton    11262: 
1.26      crook    11263: @example
                   11264: 100 100 t-rex draw
                   11265: @end example
1.1       anton    11266: 
1.26      crook    11267: where @code{t-rex} is an object or object pointer, created with e.g.
                   11268: @code{graphical new Constant t-rex}.
1.1       anton    11269: 
1.26      crook    11270: For concrete graphical objects, we define child classes of the
                   11271: class @code{graphical}, e.g.:
1.21      crook    11272: 
                   11273: @example
1.26      crook    11274: graphical class
                   11275:   cell var circle-radius
                   11276: end-class circle \ "graphical" is the parent class
1.21      crook    11277: 
1.26      crook    11278: :noname ( x y -- )
                   11279:   circle-radius @@ draw-circle ; circle defines draw
                   11280: :noname ( r -- )
                   11281:   circle-radius ! ; circle defines init
1.21      crook    11282: @end example
                   11283: 
1.26      crook    11284: There is no implicit init method, so we have to define one. The creation
                   11285: code of the object now has to call init explicitely.
1.21      crook    11286: 
1.26      crook    11287: @example
                   11288: circle new Constant my-circle
                   11289: 50 my-circle init
                   11290: @end example
1.21      crook    11291: 
1.26      crook    11292: It is also possible to add a function to create named objects with
                   11293: automatic call of @code{init}, given that all objects have @code{init}
                   11294: on the same place:
1.1       anton    11295: 
                   11296: @example
1.26      crook    11297: : new: ( .. o "name" -- )
                   11298:     new dup Constant init ;
                   11299: 80 circle new: large-circle
1.1       anton    11300: @end example
                   11301: 
1.26      crook    11302: We can draw this new circle at (100,100) with:
1.1       anton    11303: 
                   11304: @example
1.26      crook    11305: 100 100 my-circle draw
1.1       anton    11306: @end example
                   11307: 
1.48      anton    11308: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
1.26      crook    11309: @subsubsection @file{mini-oof.fs} Implementation
1.1       anton    11310: 
1.26      crook    11311: Object-oriented systems with late binding typically use a
                   11312: ``vtable''-approach: the first variable in each object is a pointer to a
                   11313: table, which contains the methods as function pointers. The vtable
                   11314: may also contain other information.
1.1       anton    11315: 
1.26      crook    11316: So first, let's declare methods:
1.1       anton    11317: 
1.26      crook    11318: @example
                   11319: : method ( m v -- m' v ) Create  over , swap cell+ swap
                   11320:   DOES> ( ... o -- ... ) @ over @ + @ execute ;
                   11321: @end example
1.1       anton    11322: 
1.26      crook    11323: During method declaration, the number of methods and instance
                   11324: variables is on the stack (in address units). @code{method} creates
                   11325: one method and increments the method number. To execute a method, it
                   11326: takes the object, fetches the vtable pointer, adds the offset, and
1.29      crook    11327: executes the @i{xt} stored there. Each method takes the object it is
1.26      crook    11328: invoked from as top of stack parameter. The method itself should
                   11329: consume that object.
1.1       anton    11330: 
1.26      crook    11331: Now, we also have to declare instance variables
1.21      crook    11332: 
1.26      crook    11333: @example
                   11334: : var ( m v size -- m v' ) Create  over , +
                   11335:   DOES> ( o -- addr ) @ + ;
                   11336: @end example
1.21      crook    11337: 
1.26      crook    11338: As before, a word is created with the current offset. Instance
                   11339: variables can have different sizes (cells, floats, doubles, chars), so
                   11340: all we do is take the size and add it to the offset. If your machine
                   11341: has alignment restrictions, put the proper @code{aligned} or
                   11342: @code{faligned} before the variable, to adjust the variable
                   11343: offset. That's why it is on the top of stack.
1.2       jwilke   11344: 
1.26      crook    11345: We need a starting point (the base object) and some syntactic sugar:
1.21      crook    11346: 
1.26      crook    11347: @example
                   11348: Create object  1 cells , 2 cells ,
                   11349: : class ( class -- class methods vars ) dup 2@ ;
                   11350: @end example
1.21      crook    11351: 
1.26      crook    11352: For inheritance, the vtable of the parent object has to be
                   11353: copied when a new, derived class is declared. This gives all the
                   11354: methods of the parent class, which can be overridden, though.
1.21      crook    11355: 
1.2       jwilke   11356: @example
1.26      crook    11357: : end-class  ( class methods vars -- )
                   11358:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   11359:   cell+ dup cell+ r> rot @ 2 cells /string move ;
                   11360: @end example
                   11361: 
                   11362: The first line creates the vtable, initialized with
                   11363: @code{noop}s. The second line is the inheritance mechanism, it
                   11364: copies the xts from the parent vtable.
1.2       jwilke   11365: 
1.26      crook    11366: We still have no way to define new methods, let's do that now:
1.2       jwilke   11367: 
1.26      crook    11368: @example
                   11369: : defines ( xt class -- ) ' >body @ + ! ;
1.2       jwilke   11370: @end example
                   11371: 
1.26      crook    11372: To allocate a new object, we need a word, too:
1.2       jwilke   11373: 
1.26      crook    11374: @example
                   11375: : new ( class -- o )  here over @ allot swap over ! ;
                   11376: @end example
1.2       jwilke   11377: 
1.26      crook    11378: Sometimes derived classes want to access the method of the
                   11379: parent object. There are two ways to achieve this with Mini-OOF:
                   11380: first, you could use named words, and second, you could look up the
                   11381: vtable of the parent object.
1.2       jwilke   11382: 
1.26      crook    11383: @example
                   11384: : :: ( class "name" -- ) ' >body @ + @ compile, ;
                   11385: @end example
1.2       jwilke   11386: 
                   11387: 
1.26      crook    11388: Nothing can be more confusing than a good example, so here is
                   11389: one. First let's declare a text object (called
                   11390: @code{button}), that stores text and position:
1.2       jwilke   11391: 
1.26      crook    11392: @example
                   11393: object class
                   11394:   cell var text
                   11395:   cell var len
                   11396:   cell var x
                   11397:   cell var y
                   11398:   method init
                   11399:   method draw
                   11400: end-class button
                   11401: @end example
1.2       jwilke   11402: 
1.26      crook    11403: @noindent
                   11404: Now, implement the two methods, @code{draw} and @code{init}:
1.2       jwilke   11405: 
1.26      crook    11406: @example
                   11407: :noname ( o -- )
                   11408:  >r r@ x @ r@ y @ at-xy  r@ text @ r> len @ type ;
                   11409:  button defines draw
                   11410: :noname ( addr u o -- )
                   11411:  >r 0 r@ x ! 0 r@ y ! r@ len ! r> text ! ;
                   11412:  button defines init
                   11413: @end example
1.2       jwilke   11414: 
1.26      crook    11415: @noindent
                   11416: To demonstrate inheritance, we define a class @code{bold-button}, with no
                   11417: new data and no new methods:
1.2       jwilke   11418: 
1.26      crook    11419: @example
                   11420: button class
                   11421: end-class bold-button
1.1       anton    11422: 
1.26      crook    11423: : bold   27 emit ." [1m" ;
                   11424: : normal 27 emit ." [0m" ;
                   11425: @end example
1.1       anton    11426: 
1.26      crook    11427: @noindent
                   11428: The class @code{bold-button} has a different draw method to
                   11429: @code{button}, but the new method is defined in terms of the draw method
                   11430: for @code{button}:
1.1       anton    11431: 
1.26      crook    11432: @example
                   11433: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   11434: @end example
1.1       anton    11435: 
1.26      crook    11436: @noindent
                   11437: Finally, create two objects and apply methods:
1.1       anton    11438: 
1.26      crook    11439: @example
                   11440: button new Constant foo
                   11441: s" thin foo" foo init
                   11442: page
                   11443: foo draw
                   11444: bold-button new Constant bar
                   11445: s" fat bar" bar init
                   11446: 1 bar y !
                   11447: bar draw
                   11448: @end example
1.1       anton    11449: 
                   11450: 
1.48      anton    11451: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   11452: @subsection Comparison with other object models
1.26      crook    11453: @cindex comparison of object models
                   11454: @cindex object models, comparison
1.1       anton    11455: 
1.26      crook    11456: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   11457: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   11458: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   11459: relation of the object models described here to two well-known and two
                   11460: closely-related (by the use of method maps) models.
1.1       anton    11461: 
1.26      crook    11462: @cindex Neon model
                   11463: The most popular model currently seems to be the Neon model (see
                   11464: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   11465: 1997) by Andrew McKewan) but this model has a number of limitations
                   11466: @footnote{A longer version of this critique can be
                   11467: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   11468: Dimensions, May 1997) by Anton Ertl.}:
1.1       anton    11469: 
1.26      crook    11470: @itemize @bullet
                   11471: @item
1.48      anton    11472: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11473: to pass objects on the stack.
1.1       anton    11474: 
1.26      crook    11475: @item
                   11476: It requires that the selector parses the input stream (at
                   11477: compile time); this leads to reduced extensibility and to bugs that are+
                   11478: hard to find.
1.1       anton    11479: 
1.26      crook    11480: @item
                   11481: It allows using every selector to every object;
                   11482: this eliminates the need for classes, but makes it harder to create
                   11483: efficient implementations. 
                   11484: @end itemize
1.1       anton    11485: 
1.26      crook    11486: @cindex Pountain's object-oriented model
                   11487: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11488: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11489: object-oriented programming, because it hardly deals with late
                   11490: binding. Instead, it focuses on features like information hiding and
                   11491: overloading that are characteristic of modular languages like Ada (83).
1.1       anton    11492: 
1.26      crook    11493: @cindex Zsoter's object-oriented model
1.48      anton    11494: In @cite{Does late binding have to be slow?} (Forth Dimensions 18(1)
                   11495: 1996, pages 31-35) Andras Zsoter describes a model that makes heavy use
                   11496: of an active object (like @code{this} in @file{objects.fs}): The active
                   11497: object is not only used for accessing all fields, but also specifies the
                   11498: receiving object of every selector invocation; you have to change the
                   11499: active object explicitly with @code{@{ ... @}}, whereas in
                   11500: @file{objects.fs} it changes more or less implicitly at @code{m:
                   11501: ... ;m}. Such a change at the method entry point is unnecessary with the
                   11502: Zsoter's model, because the receiving object is the active object
                   11503: already. On the other hand, the explicit change is absolutely necessary
                   11504: in that model, because otherwise no one could ever change the active
                   11505: object. An ANS Forth implementation of this model is available at
                   11506: @uref{http://www.forth.org/fig/oopf.html}.
1.1       anton    11507: 
1.26      crook    11508: @cindex @file{oof.fs}, differences to other models
                   11509: The @file{oof.fs} model combines information hiding and overloading
                   11510: resolution (by keeping names in various word lists) with object-oriented
                   11511: programming. It sets the active object implicitly on method entry, but
                   11512: also allows explicit changing (with @code{>o...o>} or with
                   11513: @code{with...endwith}). It uses parsing and state-smart objects and
                   11514: classes for resolving overloading and for early binding: the object or
                   11515: class parses the selector and determines the method from this. If the
                   11516: selector is not parsed by an object or class, it performs a call to the
                   11517: selector for the active object (late binding), like Zsoter's model.
                   11518: Fields are always accessed through the active object. The big
                   11519: disadvantage of this model is the parsing and the state-smartness, which
                   11520: reduces extensibility and increases the opportunities for subtle bugs;
                   11521: essentially, you are only safe if you never tick or @code{postpone} an
                   11522: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.1       anton    11523: 
1.26      crook    11524: @cindex @file{mini-oof.fs}, differences to other models
1.48      anton    11525: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11526: version of the @file{objects.fs} model, but syntactically it is a
                   11527: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.1       anton    11528: 
1.26      crook    11529: @c -------------------------------------------------------------
1.47      crook    11530: @node Passing Commands to the OS, Keeping track of Time, Object-oriented Forth, Words
1.21      crook    11531: @section Passing Commands to the Operating System
                   11532: @cindex operating system - passing commands
                   11533: @cindex shell commands
                   11534: 
                   11535: Gforth allows you to pass an arbitrary string to the host operating
                   11536: system shell (if such a thing exists) for execution.
                   11537: 
1.44      crook    11538: 
1.21      crook    11539: doc-sh
                   11540: doc-system
                   11541: doc-$?
1.23      crook    11542: doc-getenv
1.21      crook    11543: 
1.44      crook    11544: 
1.26      crook    11545: @c -------------------------------------------------------------
1.47      crook    11546: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
                   11547: @section Keeping track of Time
                   11548: @cindex time-related words
                   11549: 
                   11550: Gforth implements time-related operations by making calls to the C
                   11551: library function, @code{gettimeofday}.
                   11552: 
                   11553: doc-ms
                   11554: doc-time&date
                   11555: 
                   11556: 
                   11557: 
                   11558: @c -------------------------------------------------------------
                   11559: @node Miscellaneous Words,  , Keeping track of Time, Words
1.21      crook    11560: @section Miscellaneous Words
                   11561: @cindex miscellaneous words
                   11562: 
1.29      crook    11563: @comment TODO find homes for these
                   11564: 
1.26      crook    11565: These section lists the ANS Forth words that are not documented
1.21      crook    11566: elsewhere in this manual. Ultimately, they all need proper homes.
                   11567: 
                   11568: doc-[compile]
                   11569: 
1.44      crook    11570: 
1.26      crook    11571: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    11572: (@pxref{ANS conformance}):
1.21      crook    11573: 
                   11574: @code{EDITOR} 
                   11575: @code{EMIT?} 
                   11576: @code{FORGET} 
                   11577: 
1.24      anton    11578: @c ******************************************************************
                   11579: @node Error messages, Tools, Words, Top
                   11580: @chapter Error messages
                   11581: @cindex error messages
                   11582: @cindex backtrace
                   11583: 
                   11584: A typical Gforth error message looks like this:
                   11585: 
                   11586: @example
                   11587: in file included from :-1
                   11588: in file included from ./yyy.fs:1
                   11589: ./xxx.fs:4: Invalid memory address
                   11590: bar
                   11591: ^^^
1.25      anton    11592: $400E664C @@
                   11593: $400E6664 foo
1.24      anton    11594: @end example
                   11595: 
                   11596: The message identifying the error is @code{Invalid memory address}.  The
                   11597: error happened when text-interpreting line 4 of the file
                   11598: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   11599: word on the line where the error happened, is pointed out (with
                   11600: @code{^^^}).
                   11601: 
                   11602: The file containing the error was included in line 1 of @file{./yyy.fs},
                   11603: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   11604: @file{yyy.fs} as command-line parameter to Gforth).
                   11605: 
                   11606: At the end of the error message you find a return stack dump that can be
                   11607: interpreted as a backtrace (possibly empty). On top you find the top of
                   11608: the return stack when the @code{throw} happened, and at the bottom you
                   11609: find the return stack entry just above the return stack of the topmost
                   11610: text interpreter.
                   11611: 
                   11612: To the right of most return stack entries you see a guess for the word
                   11613: that pushed that return stack entry as its return address. This gives a
                   11614: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   11615: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   11616: address} exception).
                   11617: 
                   11618: Note that the backtrace is not perfect: We don't know which return stack
                   11619: entries are return addresses (so we may get false positives); and in
                   11620: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   11621: address the word that pushed the return address, so for some return
                   11622: addresses you see no names in the return stack dump.
1.25      anton    11623: 
                   11624: @cindex @code{catch} and backtraces
                   11625: The return stack dump represents the return stack at the time when a
                   11626: specific @code{throw} was executed.  In programs that make use of
                   11627: @code{catch}, it is not necessarily clear which @code{throw} should be
                   11628: used for the return stack dump (e.g., consider one @code{throw} that
                   11629: indicates an error, which is caught, and during recovery another error
1.42      anton    11630: happens; which @code{throw} should be used for the stack dump?).  Gforth
1.25      anton    11631: presents the return stack dump for the first @code{throw} after the last
                   11632: executed (not returned-to) @code{catch}; this works well in the usual
                   11633: case.
                   11634: 
                   11635: @cindex @code{gforth-fast} and backtraces
                   11636: @cindex @code{gforth-fast}, difference from @code{gforth}
                   11637: @cindex backtraces with @code{gforth-fast}
                   11638: @cindex return stack dump with @code{gforth-fast}
                   11639: @code{gforth} is able to do a return stack dump for throws generated
                   11640: from primitives (e.g., invalid memory address, stack empty etc.);
                   11641: @code{gforth-fast} is only able to do a return stack dump from a
                   11642: directly called @code{throw} (including @code{abort} etc.).  This is the
1.30      anton    11643: only difference (apart from a speed factor of between 1.15 (K6-2) and
                   11644: 1.6 (21164A)) between @code{gforth} and @code{gforth-fast}.  Given an
                   11645: exception caused by a primitive in @code{gforth-fast}, you will
                   11646: typically see no return stack dump at all; however, if the exception is
                   11647: caught by @code{catch} (e.g., for restoring some state), and then
                   11648: @code{throw}n again, the return stack dump will be for the first such
                   11649: @code{throw}.
1.2       jwilke   11650: 
1.5       anton    11651: @c ******************************************************************
1.24      anton    11652: @node Tools, ANS conformance, Error messages, Top
1.1       anton    11653: @chapter Tools
                   11654: 
                   11655: @menu
                   11656: * ANS Report::                  Report the words used, sorted by wordset.
                   11657: @end menu
                   11658: 
                   11659: See also @ref{Emacs and Gforth}.
                   11660: 
                   11661: @node ANS Report,  , Tools, Tools
                   11662: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   11663: @cindex @file{ans-report.fs}
                   11664: @cindex report the words used in your program
                   11665: @cindex words used in your program
                   11666: 
                   11667: If you want to label a Forth program as ANS Forth Program, you must
                   11668: document which wordsets the program uses; for extension wordsets, it is
                   11669: helpful to list the words the program requires from these wordsets
                   11670: (because Forth systems are allowed to provide only some words of them).
                   11671: 
                   11672: The @file{ans-report.fs} tool makes it easy for you to determine which
                   11673: words from which wordset and which non-ANS words your application
                   11674: uses. You simply have to include @file{ans-report.fs} before loading the
                   11675: program you want to check. After loading your program, you can get the
                   11676: report with @code{print-ans-report}. A typical use is to run this as
                   11677: batch job like this:
                   11678: @example
                   11679: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   11680: @end example
                   11681: 
                   11682: The output looks like this (for @file{compat/control.fs}):
                   11683: @example
                   11684: The program uses the following words
                   11685: from CORE :
                   11686: : POSTPONE THEN ; immediate ?dup IF 0= 
                   11687: from BLOCK-EXT :
                   11688: \ 
                   11689: from FILE :
                   11690: ( 
                   11691: @end example
                   11692: 
                   11693: @subsection Caveats
                   11694: 
                   11695: Note that @file{ans-report.fs} just checks which words are used, not whether
                   11696: they are used in an ANS Forth conforming way!
                   11697: 
                   11698: Some words are defined in several wordsets in the
                   11699: standard. @file{ans-report.fs} reports them for only one of the
                   11700: wordsets, and not necessarily the one you expect. It depends on usage
                   11701: which wordset is the right one to specify. E.g., if you only use the
                   11702: compilation semantics of @code{S"}, it is a Core word; if you also use
                   11703: its interpretation semantics, it is a File word.
                   11704: 
                   11705: @c ******************************************************************
1.65      anton    11706: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1       anton    11707: @chapter ANS conformance
                   11708: @cindex ANS conformance of Gforth
                   11709: 
                   11710: To the best of our knowledge, Gforth is an
                   11711: 
                   11712: ANS Forth System
                   11713: @itemize @bullet
                   11714: @item providing the Core Extensions word set
                   11715: @item providing the Block word set
                   11716: @item providing the Block Extensions word set
                   11717: @item providing the Double-Number word set
                   11718: @item providing the Double-Number Extensions word set
                   11719: @item providing the Exception word set
                   11720: @item providing the Exception Extensions word set
                   11721: @item providing the Facility word set
1.40      anton    11722: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1       anton    11723: @item providing the File Access word set
                   11724: @item providing the File Access Extensions word set
                   11725: @item providing the Floating-Point word set
                   11726: @item providing the Floating-Point Extensions word set
                   11727: @item providing the Locals word set
                   11728: @item providing the Locals Extensions word set
                   11729: @item providing the Memory-Allocation word set
                   11730: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   11731: @item providing the Programming-Tools word set
                   11732: @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
                   11733: @item providing the Search-Order word set
                   11734: @item providing the Search-Order Extensions word set
                   11735: @item providing the String word set
                   11736: @item providing the String Extensions word set (another easy one)
                   11737: @end itemize
                   11738: 
                   11739: @cindex system documentation
                   11740: In addition, ANS Forth systems are required to document certain
                   11741: implementation choices. This chapter tries to meet these
                   11742: requirements. In many cases it gives a way to ask the system for the
                   11743: information instead of providing the information directly, in
                   11744: particular, if the information depends on the processor, the operating
                   11745: system or the installation options chosen, or if they are likely to
                   11746: change during the maintenance of Gforth.
                   11747: 
                   11748: @comment The framework for the rest has been taken from pfe.
                   11749: 
                   11750: @menu
                   11751: * The Core Words::              
                   11752: * The optional Block word set::  
                   11753: * The optional Double Number word set::  
                   11754: * The optional Exception word set::  
                   11755: * The optional Facility word set::  
                   11756: * The optional File-Access word set::  
                   11757: * The optional Floating-Point word set::  
                   11758: * The optional Locals word set::  
                   11759: * The optional Memory-Allocation word set::  
                   11760: * The optional Programming-Tools word set::  
                   11761: * The optional Search-Order word set::  
                   11762: @end menu
                   11763: 
                   11764: 
                   11765: @c =====================================================================
                   11766: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   11767: @comment  node-name,  next,  previous,  up
                   11768: @section The Core Words
                   11769: @c =====================================================================
                   11770: @cindex core words, system documentation
                   11771: @cindex system documentation, core words
                   11772: 
                   11773: @menu
                   11774: * core-idef::                   Implementation Defined Options                   
                   11775: * core-ambcond::                Ambiguous Conditions                
                   11776: * core-other::                  Other System Documentation                  
                   11777: @end menu
                   11778: 
                   11779: @c ---------------------------------------------------------------------
                   11780: @node core-idef, core-ambcond, The Core Words, The Core Words
                   11781: @subsection Implementation Defined Options
                   11782: @c ---------------------------------------------------------------------
                   11783: @cindex core words, implementation-defined options
                   11784: @cindex implementation-defined options, core words
                   11785: 
                   11786: 
                   11787: @table @i
                   11788: @item (Cell) aligned addresses:
                   11789: @cindex cell-aligned addresses
                   11790: @cindex aligned addresses
                   11791: processor-dependent. Gforth's alignment words perform natural alignment
                   11792: (e.g., an address aligned for a datum of size 8 is divisible by
                   11793: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   11794: 
                   11795: @item @code{EMIT} and non-graphic characters:
                   11796: @cindex @code{EMIT} and non-graphic characters
                   11797: @cindex non-graphic characters and @code{EMIT}
                   11798: The character is output using the C library function (actually, macro)
                   11799: @code{putc}.
                   11800: 
                   11801: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   11802: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   11803: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   11804: @cindex @code{ACCEPT}, editing
                   11805: @cindex @code{EXPECT}, editing
                   11806: This is modeled on the GNU readline library (@pxref{Readline
                   11807: Interaction, , Command Line Editing, readline, The GNU Readline
                   11808: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   11809: producing a full word completion every time you type it (instead of
1.28      crook    11810: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    11811: 
                   11812: @item character set:
                   11813: @cindex character set
                   11814: The character set of your computer and display device. Gforth is
                   11815: 8-bit-clean (but some other component in your system may make trouble).
                   11816: 
                   11817: @item Character-aligned address requirements:
                   11818: @cindex character-aligned address requirements
                   11819: installation-dependent. Currently a character is represented by a C
                   11820: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   11821: (Comments on that requested).
                   11822: 
                   11823: @item character-set extensions and matching of names:
                   11824: @cindex character-set extensions and matching of names
1.26      crook    11825: @cindex case-sensitivity for name lookup
                   11826: @cindex name lookup, case-sensitivity
                   11827: @cindex locale and case-sensitivity
1.21      crook    11828: Any character except the ASCII NUL character can be used in a
1.1       anton    11829: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47      crook    11830: matching is performed using the C library function @code{strncasecmp}, whose
1.1       anton    11831: function is probably influenced by the locale. E.g., the @code{C} locale
                   11832: does not know about accents and umlauts, so they are matched
                   11833: case-sensitively in that locale. For portability reasons it is best to
                   11834: write programs such that they work in the @code{C} locale. Then one can
                   11835: use libraries written by a Polish programmer (who might use words
                   11836: containing ISO Latin-2 encoded characters) and by a French programmer
                   11837: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   11838: funny results for some of the words (which ones, depends on the font you
                   11839: are using)). Also, the locale you prefer may not be available in other
                   11840: operating systems. Hopefully, Unicode will solve these problems one day.
                   11841: 
                   11842: @item conditions under which control characters match a space delimiter:
                   11843: @cindex space delimiters
                   11844: @cindex control characters as delimiters
                   11845: If @code{WORD} is called with the space character as a delimiter, all
                   11846: white-space characters (as identified by the C macro @code{isspace()})
                   11847: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44      crook    11848: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.1       anton    11849: like @code{PARSE} otherwise. @code{(NAME)}, which is used by the outer
                   11850: interpreter (aka text interpreter) by default, treats all white-space
                   11851: characters as delimiters.
                   11852: 
1.26      crook    11853: @item format of the control-flow stack:
                   11854: @cindex control-flow stack, format
                   11855: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    11856: stack item in cells is given by the constant @code{cs-item-size}. At the
                   11857: time of this writing, an item consists of a (pointer to a) locals list
                   11858: (third), an address in the code (second), and a tag for identifying the
                   11859: item (TOS). The following tags are used: @code{defstart},
                   11860: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   11861: @code{scopestart}.
                   11862: 
                   11863: @item conversion of digits > 35
                   11864: @cindex digits > 35
                   11865: The characters @code{[\]^_'} are the digits with the decimal value
                   11866: 36@minus{}41. There is no way to input many of the larger digits.
                   11867: 
                   11868: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   11869: @cindex @code{EXPECT}, display after end of input
                   11870: @cindex @code{ACCEPT}, display after end of input
                   11871: The cursor is moved to the end of the entered string. If the input is
                   11872: terminated using the @kbd{Return} key, a space is typed.
                   11873: 
                   11874: @item exception abort sequence of @code{ABORT"}:
                   11875: @cindex exception abort sequence of @code{ABORT"}
                   11876: @cindex @code{ABORT"}, exception abort sequence
                   11877: The error string is stored into the variable @code{"error} and a
                   11878: @code{-2 throw} is performed.
                   11879: 
                   11880: @item input line terminator:
                   11881: @cindex input line terminator
                   11882: @cindex line terminator on input
1.26      crook    11883: @cindex newline character on input
1.1       anton    11884: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   11885: lines. One of these characters is typically produced when you type the
                   11886: @kbd{Enter} or @kbd{Return} key.
                   11887: 
                   11888: @item maximum size of a counted string:
                   11889: @cindex maximum size of a counted string
                   11890: @cindex counted string, maximum size
                   11891: @code{s" /counted-string" environment? drop .}. Currently 255 characters
                   11892: on all ports, but this may change.
                   11893: 
                   11894: @item maximum size of a parsed string:
                   11895: @cindex maximum size of a parsed string
                   11896: @cindex parsed string, maximum size
                   11897: Given by the constant @code{/line}. Currently 255 characters.
                   11898: 
                   11899: @item maximum size of a definition name, in characters:
                   11900: @cindex maximum size of a definition name, in characters
                   11901: @cindex name, maximum length
                   11902: 31
                   11903: 
                   11904: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   11905: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   11906: @cindex @code{ENVIRONMENT?} string length, maximum
                   11907: 31
                   11908: 
                   11909: @item method of selecting the user input device:
                   11910: @cindex user input device, method of selecting
                   11911: The user input device is the standard input. There is currently no way to
                   11912: change it from within Gforth. However, the input can typically be
                   11913: redirected in the command line that starts Gforth.
                   11914: 
                   11915: @item method of selecting the user output device:
                   11916: @cindex user output device, method of selecting
                   11917: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    11918: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   11919: output when the user output device is a terminal, otherwise the output
                   11920: is buffered.
1.1       anton    11921: 
                   11922: @item methods of dictionary compilation:
                   11923: What are we expected to document here?
                   11924: 
                   11925: @item number of bits in one address unit:
                   11926: @cindex number of bits in one address unit
                   11927: @cindex address unit, size in bits
                   11928: @code{s" address-units-bits" environment? drop .}. 8 in all current
                   11929: ports.
                   11930: 
                   11931: @item number representation and arithmetic:
                   11932: @cindex number representation and arithmetic
                   11933: Processor-dependent. Binary two's complement on all current ports.
                   11934: 
                   11935: @item ranges for integer types:
                   11936: @cindex ranges for integer types
                   11937: @cindex integer types, ranges
                   11938: Installation-dependent. Make environmental queries for @code{MAX-N},
                   11939: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   11940: unsigned (and positive) types is 0. The lower bound for signed types on
                   11941: two's complement and one's complement machines machines can be computed
                   11942: by adding 1 to the upper bound.
                   11943: 
                   11944: @item read-only data space regions:
                   11945: @cindex read-only data space regions
                   11946: @cindex data-space, read-only regions
                   11947: The whole Forth data space is writable.
                   11948: 
                   11949: @item size of buffer at @code{WORD}:
                   11950: @cindex size of buffer at @code{WORD}
                   11951: @cindex @code{WORD} buffer size
                   11952: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   11953: shared with the pictured numeric output string. If overwriting
                   11954: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   11955: space, although only as much can be sensibly used as fits in a counted
                   11956: string.
                   11957: 
                   11958: @item size of one cell in address units:
                   11959: @cindex cell size
                   11960: @code{1 cells .}.
                   11961: 
                   11962: @item size of one character in address units:
                   11963: @cindex char size
                   11964: @code{1 chars .}. 1 on all current ports.
                   11965: 
                   11966: @item size of the keyboard terminal buffer:
                   11967: @cindex size of the keyboard terminal buffer
                   11968: @cindex terminal buffer, size
                   11969: Varies. You can determine the size at a specific time using @code{lp@@
                   11970: tib - .}. It is shared with the locals stack and TIBs of files that
                   11971: include the current file. You can change the amount of space for TIBs
                   11972: and locals stack at Gforth startup with the command line option
                   11973: @code{-l}.
                   11974: 
                   11975: @item size of the pictured numeric output buffer:
                   11976: @cindex size of the pictured numeric output buffer
                   11977: @cindex pictured numeric output buffer, size
                   11978: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   11979: shared with @code{WORD}.
                   11980: 
                   11981: @item size of the scratch area returned by @code{PAD}:
                   11982: @cindex size of the scratch area returned by @code{PAD}
                   11983: @cindex @code{PAD} size
                   11984: The remainder of dictionary space. @code{unused pad here - - .}.
                   11985: 
                   11986: @item system case-sensitivity characteristics:
                   11987: @cindex case-sensitivity characteristics
1.26      crook    11988: Dictionary searches are case-insensitive (except in
1.1       anton    11989: @code{TABLE}s). However, as explained above under @i{character-set
                   11990: extensions}, the matching for non-ASCII characters is determined by the
                   11991: locale you are using. In the default @code{C} locale all non-ASCII
                   11992: characters are matched case-sensitively.
                   11993: 
                   11994: @item system prompt:
                   11995: @cindex system prompt
                   11996: @cindex prompt
                   11997: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   11998: 
                   11999: @item division rounding:
                   12000: @cindex division rounding
                   12001: installation dependent. @code{s" floored" environment? drop .}. We leave
                   12002: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
                   12003: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
                   12004: 
                   12005: @item values of @code{STATE} when true:
                   12006: @cindex @code{STATE} values
                   12007: -1.
                   12008: 
                   12009: @item values returned after arithmetic overflow:
                   12010: On two's complement machines, arithmetic is performed modulo
                   12011: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   12012: arithmetic (with appropriate mapping for signed types). Division by zero
                   12013: typically results in a @code{-55 throw} (Floating-point unidentified
                   12014: fault), although a @code{-10 throw} (divide by zero) would be more
                   12015: appropriate.
                   12016: 
                   12017: @item whether the current definition can be found after @t{DOES>}:
                   12018: @cindex @t{DOES>}, visibility of current definition
                   12019: No.
                   12020: 
                   12021: @end table
                   12022: 
                   12023: @c ---------------------------------------------------------------------
                   12024: @node core-ambcond, core-other, core-idef, The Core Words
                   12025: @subsection Ambiguous conditions
                   12026: @c ---------------------------------------------------------------------
                   12027: @cindex core words, ambiguous conditions
                   12028: @cindex ambiguous conditions, core words
                   12029: 
                   12030: @table @i
                   12031: 
                   12032: @item a name is neither a word nor a number:
                   12033: @cindex name not found
1.26      crook    12034: @cindex undefined word
1.1       anton    12035: @code{-13 throw} (Undefined word). Actually, @code{-13 bounce}, which
                   12036: preserves the data and FP stack, so you don't lose more work than
                   12037: necessary.
                   12038: 
                   12039: @item a definition name exceeds the maximum length allowed:
1.26      crook    12040: @cindex word name too long
1.1       anton    12041: @code{-19 throw} (Word name too long)
                   12042: 
                   12043: @item addressing a region not inside the various data spaces of the forth system:
                   12044: @cindex Invalid memory address
1.32      anton    12045: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    12046: typically readable. Accessing other addresses gives results dependent on
                   12047: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   12048: address).
                   12049: 
                   12050: @item argument type incompatible with parameter:
1.26      crook    12051: @cindex argument type mismatch
1.1       anton    12052: This is usually not caught. Some words perform checks, e.g., the control
                   12053: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   12054: mismatch).
                   12055: 
                   12056: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   12057: @cindex Interpreting a compile-only word, for @code{'} etc.
                   12058: @cindex execution token of words with undefined execution semantics
                   12059: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   12060: get an execution token for @code{compile-only-error} (which performs a
                   12061: @code{-14 throw} when executed).
                   12062: 
                   12063: @item dividing by zero:
                   12064: @cindex dividing by zero
                   12065: @cindex floating point unidentified fault, integer division
1.24      anton    12066: On better platforms, this produces a @code{-10 throw} (Division by
                   12067: zero); on other systems, this typically results in a @code{-55 throw}
                   12068: (Floating-point unidentified fault).
1.1       anton    12069: 
                   12070: @item insufficient data stack or return stack space:
                   12071: @cindex insufficient data stack or return stack space
                   12072: @cindex stack overflow
1.26      crook    12073: @cindex address alignment exception, stack overflow
1.1       anton    12074: @cindex Invalid memory address, stack overflow
                   12075: Depending on the operating system, the installation, and the invocation
                   12076: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    12077: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   12078: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   12079: throw} (Invalid memory address) (depending on the platform and how you
                   12080: achieved the overflow) as soon as the overflow happens. If it is not
                   12081: checked, overflows typically result in mysterious illegal memory
                   12082: accesses, producing @code{-9 throw} (Invalid memory address) or
                   12083: @code{-23 throw} (Address alignment exception); they might also destroy
                   12084: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   12085: various errors in these words.
1.1       anton    12086: 
                   12087: @item insufficient space for loop control parameters:
                   12088: @cindex insufficient space for loop control parameters
                   12089: like other return stack overflows.
                   12090: 
                   12091: @item insufficient space in the dictionary:
                   12092: @cindex insufficient space in the dictionary
                   12093: @cindex dictionary overflow
1.12      anton    12094: If you try to allot (either directly with @code{allot}, or indirectly
                   12095: with @code{,}, @code{create} etc.) more memory than available in the
                   12096: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   12097: to access memory beyond the end of the dictionary, the results are
                   12098: similar to stack overflows.
1.1       anton    12099: 
                   12100: @item interpreting a word with undefined interpretation semantics:
                   12101: @cindex interpreting a word with undefined interpretation semantics
                   12102: @cindex Interpreting a compile-only word
                   12103: For some words, we have defined interpretation semantics. For the
                   12104: others: @code{-14 throw} (Interpreting a compile-only word).
                   12105: 
                   12106: @item modifying the contents of the input buffer or a string literal:
                   12107: @cindex modifying the contents of the input buffer or a string literal
                   12108: These are located in writable memory and can be modified.
                   12109: 
                   12110: @item overflow of the pictured numeric output string:
                   12111: @cindex overflow of the pictured numeric output string
                   12112: @cindex pictured numeric output string, overflow
1.24      anton    12113: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    12114: 
                   12115: @item parsed string overflow:
                   12116: @cindex parsed string overflow
                   12117: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   12118: 
                   12119: @item producing a result out of range:
                   12120: @cindex result out of range
                   12121: On two's complement machines, arithmetic is performed modulo
                   12122: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   12123: arithmetic (with appropriate mapping for signed types). Division by zero
1.24      anton    12124: typically results in a @code{-10 throw} (divide by zero) or @code{-55
                   12125: throw} (floating point unidentified fault). @code{convert} and
                   12126: @code{>number} currently overflow silently.
1.1       anton    12127: 
                   12128: @item reading from an empty data or return stack:
                   12129: @cindex stack empty
                   12130: @cindex stack underflow
1.24      anton    12131: @cindex return stack underflow
1.1       anton    12132: The data stack is checked by the outer (aka text) interpreter after
                   12133: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   12134: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    12135: depending on operating system, installation, and invocation. If they are
                   12136: caught by a check, they typically result in @code{-4 throw} (Stack
                   12137: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   12138: (Invalid memory address), depending on the platform and which stack
                   12139: underflows and by how much. Note that even if the system uses checking
                   12140: (through the MMU), your program may have to underflow by a significant
                   12141: number of stack items to trigger the reaction (the reason for this is
                   12142: that the MMU, and therefore the checking, works with a page-size
                   12143: granularity).  If there is no checking, the symptoms resulting from an
                   12144: underflow are similar to those from an overflow.  Unbalanced return
                   12145: stack errors result in a variaty of symptoms, including @code{-9 throw}
                   12146: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   12147: throw}).
1.1       anton    12148: 
                   12149: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   12150: @cindex unexpected end of the input buffer
                   12151: @cindex zero-length string as a name
                   12152: @cindex Attempt to use zero-length string as a name
                   12153: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   12154: use zero-length string as a name). Words like @code{'} probably will not
                   12155: find what they search. Note that it is possible to create zero-length
                   12156: names with @code{nextname} (should it not?).
                   12157: 
                   12158: @item @code{>IN} greater than input buffer:
                   12159: @cindex @code{>IN} greater than input buffer
                   12160: The next invocation of a parsing word returns a string with length 0.
                   12161: 
                   12162: @item @code{RECURSE} appears after @code{DOES>}:
                   12163: @cindex @code{RECURSE} appears after @code{DOES>}
                   12164: Compiles a recursive call to the defining word, not to the defined word.
                   12165: 
                   12166: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   12167: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    12168: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    12169: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   12170: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   12171: the end of the file was reached), its source-id may be
                   12172: reused. Therefore, restoring an input source specification referencing a
                   12173: closed file may lead to unpredictable results instead of a @code{-12
                   12174: THROW}.
                   12175: 
                   12176: In the future, Gforth may be able to restore input source specifications
                   12177: from other than the current input source.
                   12178: 
                   12179: @item data space containing definitions gets de-allocated:
                   12180: @cindex data space containing definitions gets de-allocated
                   12181: Deallocation with @code{allot} is not checked. This typically results in
                   12182: memory access faults or execution of illegal instructions.
                   12183: 
                   12184: @item data space read/write with incorrect alignment:
                   12185: @cindex data space read/write with incorrect alignment
                   12186: @cindex alignment faults
1.26      crook    12187: @cindex address alignment exception
1.1       anton    12188: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    12189: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    12190: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   12191: (Invalid memory address). There are reportedly some processors with
1.12      anton    12192: alignment restrictions that do not report violations.
1.1       anton    12193: 
                   12194: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   12195: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   12196: Like other alignment errors.
                   12197: 
                   12198: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   12199: Like other stack underflows.
                   12200: 
                   12201: @item loop control parameters not available:
                   12202: @cindex loop control parameters not available
                   12203: Not checked. The counted loop words simply assume that the top of return
                   12204: stack items are loop control parameters and behave accordingly.
                   12205: 
                   12206: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   12207: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   12208: @cindex last word was headerless
                   12209: @code{abort" last word was headerless"}.
                   12210: 
                   12211: @item name not defined by @code{VALUE} used by @code{TO}:
                   12212: @cindex name not defined by @code{VALUE} used by @code{TO}
                   12213: @cindex @code{TO} on non-@code{VALUE}s
                   12214: @cindex Invalid name argument, @code{TO}
                   12215: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   12216: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   12217: 
                   12218: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   12219: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    12220: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    12221: @code{-13 throw} (Undefined word)
                   12222: 
                   12223: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   12224: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   12225: Gforth behaves as if they were of the same type. I.e., you can predict
                   12226: the behaviour by interpreting all parameters as, e.g., signed.
                   12227: 
                   12228: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   12229: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   12230: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   12231: compilation semantics of @code{TO}.
                   12232: 
                   12233: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    12234: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    12235: @cindex @code{WORD}, string overflow
                   12236: Not checked. The string will be ok, but the count will, of course,
                   12237: contain only the least significant bits of the length.
                   12238: 
                   12239: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   12240: @cindex @code{LSHIFT}, large shift counts
                   12241: @cindex @code{RSHIFT}, large shift counts
                   12242: Processor-dependent. Typical behaviours are returning 0 and using only
                   12243: the low bits of the shift count.
                   12244: 
                   12245: @item word not defined via @code{CREATE}:
                   12246: @cindex @code{>BODY} of non-@code{CREATE}d words
                   12247: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   12248: 
                   12249: @cindex @code{DOES>} of non-@code{CREATE}d words
                   12250: @code{DOES>} changes the execution semantics of the last defined word no
                   12251: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   12252: @code{CREATE , DOES>}.
                   12253: 
                   12254: @item words improperly used outside @code{<#} and @code{#>}:
                   12255: Not checked. As usual, you can expect memory faults.
                   12256: 
                   12257: @end table
                   12258: 
                   12259: 
                   12260: @c ---------------------------------------------------------------------
                   12261: @node core-other,  , core-ambcond, The Core Words
                   12262: @subsection Other system documentation
                   12263: @c ---------------------------------------------------------------------
                   12264: @cindex other system documentation, core words
                   12265: @cindex core words, other system documentation
                   12266: 
                   12267: @table @i
                   12268: @item nonstandard words using @code{PAD}:
                   12269: @cindex @code{PAD} use by nonstandard words
                   12270: None.
                   12271: 
                   12272: @item operator's terminal facilities available:
                   12273: @cindex operator's terminal facilities available
                   12274: After processing the command line, Gforth goes into interactive mode,
                   12275: and you can give commands to Gforth interactively. The actual facilities
                   12276: available depend on how you invoke Gforth.
                   12277: 
                   12278: @item program data space available:
                   12279: @cindex program data space available
                   12280: @cindex data space available
                   12281: @code{UNUSED .} gives the remaining dictionary space. The total
                   12282: dictionary space can be specified with the @code{-m} switch
                   12283: (@pxref{Invoking Gforth}) when Gforth starts up.
                   12284: 
                   12285: @item return stack space available:
                   12286: @cindex return stack space available
                   12287: You can compute the total return stack space in cells with
                   12288: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   12289: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   12290: 
                   12291: @item stack space available:
                   12292: @cindex stack space available
                   12293: You can compute the total data stack space in cells with
                   12294: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   12295: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   12296: 
                   12297: @item system dictionary space required, in address units:
                   12298: @cindex system dictionary space required, in address units
                   12299: Type @code{here forthstart - .} after startup. At the time of this
                   12300: writing, this gives 80080 (bytes) on a 32-bit system.
                   12301: @end table
                   12302: 
                   12303: 
                   12304: @c =====================================================================
                   12305: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   12306: @section The optional Block word set
                   12307: @c =====================================================================
                   12308: @cindex system documentation, block words
                   12309: @cindex block words, system documentation
                   12310: 
                   12311: @menu
                   12312: * block-idef::                  Implementation Defined Options
                   12313: * block-ambcond::               Ambiguous Conditions               
                   12314: * block-other::                 Other System Documentation                 
                   12315: @end menu
                   12316: 
                   12317: 
                   12318: @c ---------------------------------------------------------------------
                   12319: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   12320: @subsection Implementation Defined Options
                   12321: @c ---------------------------------------------------------------------
                   12322: @cindex implementation-defined options, block words
                   12323: @cindex block words, implementation-defined options
                   12324: 
                   12325: @table @i
                   12326: @item the format for display by @code{LIST}:
                   12327: @cindex @code{LIST} display format
                   12328: First the screen number is displayed, then 16 lines of 64 characters,
                   12329: each line preceded by the line number.
                   12330: 
                   12331: @item the length of a line affected by @code{\}:
                   12332: @cindex length of a line affected by @code{\}
                   12333: @cindex @code{\}, line length in blocks
                   12334: 64 characters.
                   12335: @end table
                   12336: 
                   12337: 
                   12338: @c ---------------------------------------------------------------------
                   12339: @node block-ambcond, block-other, block-idef, The optional Block word set
                   12340: @subsection Ambiguous conditions
                   12341: @c ---------------------------------------------------------------------
                   12342: @cindex block words, ambiguous conditions
                   12343: @cindex ambiguous conditions, block words
                   12344: 
                   12345: @table @i
                   12346: @item correct block read was not possible:
                   12347: @cindex block read not possible
                   12348: Typically results in a @code{throw} of some OS-derived value (between
                   12349: -512 and -2048). If the blocks file was just not long enough, blanks are
                   12350: supplied for the missing portion.
                   12351: 
                   12352: @item I/O exception in block transfer:
                   12353: @cindex I/O exception in block transfer
                   12354: @cindex block transfer, I/O exception
                   12355: Typically results in a @code{throw} of some OS-derived value (between
                   12356: -512 and -2048).
                   12357: 
                   12358: @item invalid block number:
                   12359: @cindex invalid block number
                   12360: @cindex block number invalid
                   12361: @code{-35 throw} (Invalid block number)
                   12362: 
                   12363: @item a program directly alters the contents of @code{BLK}:
                   12364: @cindex @code{BLK}, altering @code{BLK}
                   12365: The input stream is switched to that other block, at the same
                   12366: position. If the storing to @code{BLK} happens when interpreting
                   12367: non-block input, the system will get quite confused when the block ends.
                   12368: 
                   12369: @item no current block buffer for @code{UPDATE}:
                   12370: @cindex @code{UPDATE}, no current block buffer
                   12371: @code{UPDATE} has no effect.
                   12372: 
                   12373: @end table
                   12374: 
                   12375: @c ---------------------------------------------------------------------
                   12376: @node block-other,  , block-ambcond, The optional Block word set
                   12377: @subsection Other system documentation
                   12378: @c ---------------------------------------------------------------------
                   12379: @cindex other system documentation, block words
                   12380: @cindex block words, other system documentation
                   12381: 
                   12382: @table @i
                   12383: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   12384: No restrictions (yet).
                   12385: 
                   12386: @item the number of blocks available for source and data:
                   12387: depends on your disk space.
                   12388: 
                   12389: @end table
                   12390: 
                   12391: 
                   12392: @c =====================================================================
                   12393: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   12394: @section The optional Double Number word set
                   12395: @c =====================================================================
                   12396: @cindex system documentation, double words
                   12397: @cindex double words, system documentation
                   12398: 
                   12399: @menu
                   12400: * double-ambcond::              Ambiguous Conditions              
                   12401: @end menu
                   12402: 
                   12403: 
                   12404: @c ---------------------------------------------------------------------
                   12405: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   12406: @subsection Ambiguous conditions
                   12407: @c ---------------------------------------------------------------------
                   12408: @cindex double words, ambiguous conditions
                   12409: @cindex ambiguous conditions, double words
                   12410: 
                   12411: @table @i
1.29      crook    12412: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   12413: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   12414: The least significant cell of @i{d} is produced.
1.1       anton    12415: 
                   12416: @end table
                   12417: 
                   12418: 
                   12419: @c =====================================================================
                   12420: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   12421: @section The optional Exception word set
                   12422: @c =====================================================================
                   12423: @cindex system documentation, exception words
                   12424: @cindex exception words, system documentation
                   12425: 
                   12426: @menu
                   12427: * exception-idef::              Implementation Defined Options              
                   12428: @end menu
                   12429: 
                   12430: 
                   12431: @c ---------------------------------------------------------------------
                   12432: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   12433: @subsection Implementation Defined Options
                   12434: @c ---------------------------------------------------------------------
                   12435: @cindex implementation-defined options, exception words
                   12436: @cindex exception words, implementation-defined options
                   12437: 
                   12438: @table @i
                   12439: @item @code{THROW}-codes used in the system:
                   12440: @cindex @code{THROW}-codes used in the system
                   12441: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    12442: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    12443: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   12444: allocation operations). The mapping from OS error numbers to throw codes
                   12445: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   12446: undefined OS errors produce a message with a strange number; e.g.,
                   12447: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   12448: @end table
                   12449: 
                   12450: @c =====================================================================
                   12451: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   12452: @section The optional Facility word set
                   12453: @c =====================================================================
                   12454: @cindex system documentation, facility words
                   12455: @cindex facility words, system documentation
                   12456: 
                   12457: @menu
                   12458: * facility-idef::               Implementation Defined Options               
                   12459: * facility-ambcond::            Ambiguous Conditions            
                   12460: @end menu
                   12461: 
                   12462: 
                   12463: @c ---------------------------------------------------------------------
                   12464: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   12465: @subsection Implementation Defined Options
                   12466: @c ---------------------------------------------------------------------
                   12467: @cindex implementation-defined options, facility words
                   12468: @cindex facility words, implementation-defined options
                   12469: 
                   12470: @table @i
                   12471: @item encoding of keyboard events (@code{EKEY}):
                   12472: @cindex keyboard events, encoding in @code{EKEY}
                   12473: @cindex @code{EKEY}, encoding of keyboard events
1.40      anton    12474: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41      anton    12475: Other keys are encoded with the constants @code{k-left}, @code{k-right},
                   12476: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
                   12477: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
                   12478: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40      anton    12479: 
1.1       anton    12480: 
                   12481: @item duration of a system clock tick:
                   12482: @cindex duration of a system clock tick
                   12483: @cindex clock tick duration
                   12484: System dependent. With respect to @code{MS}, the time is specified in
                   12485: microseconds. How well the OS and the hardware implement this, is
                   12486: another question.
                   12487: 
                   12488: @item repeatability to be expected from the execution of @code{MS}:
                   12489: @cindex repeatability to be expected from the execution of @code{MS}
                   12490: @cindex @code{MS}, repeatability to be expected
                   12491: System dependent. On Unix, a lot depends on load. If the system is
                   12492: lightly loaded, and the delay is short enough that Gforth does not get
                   12493: swapped out, the performance should be acceptable. Under MS-DOS and
                   12494: other single-tasking systems, it should be good.
                   12495: 
                   12496: @end table
                   12497: 
                   12498: 
                   12499: @c ---------------------------------------------------------------------
                   12500: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   12501: @subsection Ambiguous conditions
                   12502: @c ---------------------------------------------------------------------
                   12503: @cindex facility words, ambiguous conditions
                   12504: @cindex ambiguous conditions, facility words
                   12505: 
                   12506: @table @i
                   12507: @item @code{AT-XY} can't be performed on user output device:
                   12508: @cindex @code{AT-XY} can't be performed on user output device
                   12509: Largely terminal dependent. No range checks are done on the arguments.
                   12510: No errors are reported. You may see some garbage appearing, you may see
                   12511: simply nothing happen.
                   12512: 
                   12513: @end table
                   12514: 
                   12515: 
                   12516: @c =====================================================================
                   12517: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   12518: @section The optional File-Access word set
                   12519: @c =====================================================================
                   12520: @cindex system documentation, file words
                   12521: @cindex file words, system documentation
                   12522: 
                   12523: @menu
                   12524: * file-idef::                   Implementation Defined Options
                   12525: * file-ambcond::                Ambiguous Conditions                
                   12526: @end menu
                   12527: 
                   12528: @c ---------------------------------------------------------------------
                   12529: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   12530: @subsection Implementation Defined Options
                   12531: @c ---------------------------------------------------------------------
                   12532: @cindex implementation-defined options, file words
                   12533: @cindex file words, implementation-defined options
                   12534: 
                   12535: @table @i
                   12536: @item file access methods used:
                   12537: @cindex file access methods used
                   12538: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   12539: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   12540: @code{wb}): The file is cleared, if it exists, and created, if it does
                   12541: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   12542: @code{create-file} creates a file with 666 permissions modified by your
                   12543: umask.
                   12544: 
                   12545: @item file exceptions:
                   12546: @cindex file exceptions
                   12547: The file words do not raise exceptions (except, perhaps, memory access
                   12548: faults when you pass illegal addresses or file-ids).
                   12549: 
                   12550: @item file line terminator:
                   12551: @cindex file line terminator
                   12552: System-dependent. Gforth uses C's newline character as line
                   12553: terminator. What the actual character code(s) of this are is
                   12554: system-dependent.
                   12555: 
                   12556: @item file name format:
                   12557: @cindex file name format
                   12558: System dependent. Gforth just uses the file name format of your OS.
                   12559: 
                   12560: @item information returned by @code{FILE-STATUS}:
                   12561: @cindex @code{FILE-STATUS}, returned information
                   12562: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   12563: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   12564: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   12565: along with the returned mode.
                   12566: 
                   12567: @item input file state after an exception when including source:
                   12568: @cindex exception when including source
                   12569: All files that are left via the exception are closed.
                   12570: 
1.29      crook    12571: @item @i{ior} values and meaning:
                   12572: @cindex @i{ior} values and meaning
                   12573: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    12574: intended as throw codes. They typically are in the range
                   12575: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    12576: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    12577: 
                   12578: @item maximum depth of file input nesting:
                   12579: @cindex maximum depth of file input nesting
                   12580: @cindex file input nesting, maximum depth
                   12581: limited by the amount of return stack, locals/TIB stack, and the number
                   12582: of open files available. This should not give you troubles.
                   12583: 
                   12584: @item maximum size of input line:
                   12585: @cindex maximum size of input line
                   12586: @cindex input line size, maximum
                   12587: @code{/line}. Currently 255.
                   12588: 
                   12589: @item methods of mapping block ranges to files:
                   12590: @cindex mapping block ranges to files
                   12591: @cindex files containing blocks
                   12592: @cindex blocks in files
                   12593: By default, blocks are accessed in the file @file{blocks.fb} in the
                   12594: current working directory. The file can be switched with @code{USE}.
                   12595: 
                   12596: @item number of string buffers provided by @code{S"}:
                   12597: @cindex @code{S"}, number of string buffers
                   12598: 1
                   12599: 
                   12600: @item size of string buffer used by @code{S"}:
                   12601: @cindex @code{S"}, size of string buffer
                   12602: @code{/line}. currently 255.
                   12603: 
                   12604: @end table
                   12605: 
                   12606: @c ---------------------------------------------------------------------
                   12607: @node file-ambcond,  , file-idef, The optional File-Access word set
                   12608: @subsection Ambiguous conditions
                   12609: @c ---------------------------------------------------------------------
                   12610: @cindex file words, ambiguous conditions
                   12611: @cindex ambiguous conditions, file words
                   12612: 
                   12613: @table @i
                   12614: @item attempting to position a file outside its boundaries:
                   12615: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   12616: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   12617: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   12618: 
                   12619: @item attempting to read from file positions not yet written:
                   12620: @cindex reading from file positions not yet written
                   12621: End-of-file, i.e., zero characters are read and no error is reported.
                   12622: 
1.29      crook    12623: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   12624: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    12625: An appropriate exception may be thrown, but a memory fault or other
                   12626: problem is more probable.
                   12627: 
1.29      crook    12628: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   12629: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   12630: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   12631: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    12632: thrown.
                   12633: 
                   12634: @item named file cannot be opened (@code{INCLUDED}):
                   12635: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    12636: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    12637: 
                   12638: @item requesting an unmapped block number:
                   12639: @cindex unmapped block numbers
                   12640: There are no unmapped legal block numbers. On some operating systems,
                   12641: writing a block with a large number may overflow the file system and
                   12642: have an error message as consequence.
                   12643: 
                   12644: @item using @code{source-id} when @code{blk} is non-zero:
                   12645: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   12646: @code{source-id} performs its function. Typically it will give the id of
                   12647: the source which loaded the block. (Better ideas?)
                   12648: 
                   12649: @end table
                   12650: 
                   12651: 
                   12652: @c =====================================================================
                   12653: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   12654: @section The optional Floating-Point word set
                   12655: @c =====================================================================
                   12656: @cindex system documentation, floating-point words
                   12657: @cindex floating-point words, system documentation
                   12658: 
                   12659: @menu
                   12660: * floating-idef::               Implementation Defined Options
                   12661: * floating-ambcond::            Ambiguous Conditions            
                   12662: @end menu
                   12663: 
                   12664: 
                   12665: @c ---------------------------------------------------------------------
                   12666: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   12667: @subsection Implementation Defined Options
                   12668: @c ---------------------------------------------------------------------
                   12669: @cindex implementation-defined options, floating-point words
                   12670: @cindex floating-point words, implementation-defined options
                   12671: 
                   12672: @table @i
                   12673: @item format and range of floating point numbers:
                   12674: @cindex format and range of floating point numbers
                   12675: @cindex floating point numbers, format and range
                   12676: System-dependent; the @code{double} type of C.
                   12677: 
1.29      crook    12678: @item results of @code{REPRESENT} when @i{float} is out of range:
                   12679: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    12680: System dependent; @code{REPRESENT} is implemented using the C library
                   12681: function @code{ecvt()} and inherits its behaviour in this respect.
                   12682: 
                   12683: @item rounding or truncation of floating-point numbers:
                   12684: @cindex rounding of floating-point numbers
                   12685: @cindex truncation of floating-point numbers
                   12686: @cindex floating-point numbers, rounding or truncation
                   12687: System dependent; the rounding behaviour is inherited from the hosting C
                   12688: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   12689: nearest, and break ties by rounding to even (i.e., such that the last
                   12690: bit of the mantissa is 0).
                   12691: 
                   12692: @item size of floating-point stack:
                   12693: @cindex floating-point stack size
                   12694: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   12695: the floating-point stack (in floats). You can specify this on startup
                   12696: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   12697: 
                   12698: @item width of floating-point stack:
                   12699: @cindex floating-point stack width 
                   12700: @code{1 floats}.
                   12701: 
                   12702: @end table
                   12703: 
                   12704: 
                   12705: @c ---------------------------------------------------------------------
                   12706: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   12707: @subsection Ambiguous conditions
                   12708: @c ---------------------------------------------------------------------
                   12709: @cindex floating-point words, ambiguous conditions
                   12710: @cindex ambiguous conditions, floating-point words
                   12711: 
                   12712: @table @i
                   12713: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   12714: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   12715: System-dependent. Typically results in a @code{-23 THROW} like other
                   12716: alignment violations.
                   12717: 
                   12718: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   12719: @cindex @code{f@@} used with an address that is not float aligned
                   12720: @cindex @code{f!} used with an address that is not float aligned
                   12721: System-dependent. Typically results in a @code{-23 THROW} like other
                   12722: alignment violations.
                   12723: 
                   12724: @item floating-point result out of range:
                   12725: @cindex floating-point result out of range
                   12726: System-dependent. Can result in a @code{-55 THROW} (Floating-point
                   12727: unidentified fault), or can produce a special value representing, e.g.,
                   12728: Infinity.
                   12729: 
                   12730: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   12731: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   12732: System-dependent. Typically results in an alignment fault like other
                   12733: alignment violations.
                   12734: 
1.35      anton    12735: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   12736: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    12737: The floating-point number is converted into decimal nonetheless.
                   12738: 
                   12739: @item Both arguments are equal to zero (@code{FATAN2}):
                   12740: @cindex @code{FATAN2}, both arguments are equal to zero
                   12741: System-dependent. @code{FATAN2} is implemented using the C library
                   12742: function @code{atan2()}.
                   12743: 
1.29      crook    12744: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   12745: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   12746: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    12747: because of small errors and the tan will be a very large (or very small)
                   12748: but finite number.
                   12749: 
1.29      crook    12750: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   12751: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    12752: The result is rounded to the nearest float.
                   12753: 
                   12754: @item dividing by zero:
                   12755: @cindex dividing by zero, floating-point
                   12756: @cindex floating-point dividing by zero
                   12757: @cindex floating-point unidentified fault, FP divide-by-zero
                   12758: @code{-55 throw} (Floating-point unidentified fault)
                   12759: 
                   12760: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   12761: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   12762: System dependent. On IEEE-FP based systems the number is converted into
                   12763: an infinity.
                   12764: 
1.29      crook    12765: @item @i{float}<1 (@code{FACOSH}):
                   12766: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    12767: @cindex floating-point unidentified fault, @code{FACOSH}
                   12768: @code{-55 throw} (Floating-point unidentified fault)
                   12769: 
1.29      crook    12770: @item @i{float}=<-1 (@code{FLNP1}):
                   12771: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    12772: @cindex floating-point unidentified fault, @code{FLNP1}
                   12773: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    12774: negative infinity is typically produced for @i{float}=-1.
1.1       anton    12775: 
1.29      crook    12776: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   12777: @cindex @code{FLN}, @i{float}=<0
                   12778: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    12779: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
                   12780: @code{-55 throw} (Floating-point unidentified fault). On IEEE-FP systems
1.29      crook    12781: negative infinity is typically produced for @i{float}=0.
1.1       anton    12782: 
1.29      crook    12783: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   12784: @cindex @code{FASINH}, @i{float}<0
                   12785: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    12786: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
                   12787: @code{-55 throw} (Floating-point unidentified fault). @code{fasinh}
                   12788: produces values for these inputs on my Linux box (Bug in the C library?)
                   12789: 
1.29      crook    12790: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   12791: @cindex @code{FACOS}, |@i{float}|>1
                   12792: @cindex @code{FASIN}, |@i{float}|>1
                   12793: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    12794: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
                   12795: @code{-55 throw} (Floating-point unidentified fault).
                   12796: 
1.29      crook    12797: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   12798: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    12799: @cindex floating-point unidentified fault, @code{F>D}
                   12800: @code{-55 throw} (Floating-point unidentified fault).
                   12801: 
                   12802: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   12803: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
                   12804: This does not happen.
                   12805: @end table
                   12806: 
                   12807: @c =====================================================================
                   12808: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   12809: @section The optional Locals word set
                   12810: @c =====================================================================
                   12811: @cindex system documentation, locals words
                   12812: @cindex locals words, system documentation
                   12813: 
                   12814: @menu
                   12815: * locals-idef::                 Implementation Defined Options                 
                   12816: * locals-ambcond::              Ambiguous Conditions              
                   12817: @end menu
                   12818: 
                   12819: 
                   12820: @c ---------------------------------------------------------------------
                   12821: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   12822: @subsection Implementation Defined Options
                   12823: @c ---------------------------------------------------------------------
                   12824: @cindex implementation-defined options, locals words
                   12825: @cindex locals words, implementation-defined options
                   12826: 
                   12827: @table @i
                   12828: @item maximum number of locals in a definition:
                   12829: @cindex maximum number of locals in a definition
                   12830: @cindex locals, maximum number in a definition
                   12831: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   12832: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   12833: characters. The number of locals in a definition is bounded by the size
                   12834: of locals-buffer, which contains the names of the locals.
                   12835: 
                   12836: @end table
                   12837: 
                   12838: 
                   12839: @c ---------------------------------------------------------------------
                   12840: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   12841: @subsection Ambiguous conditions
                   12842: @c ---------------------------------------------------------------------
                   12843: @cindex locals words, ambiguous conditions
                   12844: @cindex ambiguous conditions, locals words
                   12845: 
                   12846: @table @i
                   12847: @item executing a named local in interpretation state:
                   12848: @cindex local in interpretation state
                   12849: @cindex Interpreting a compile-only word, for a local
                   12850: Locals have no interpretation semantics. If you try to perform the
                   12851: interpretation semantics, you will get a @code{-14 throw} somewhere
                   12852: (Interpreting a compile-only word). If you perform the compilation
                   12853: semantics, the locals access will be compiled (irrespective of state).
                   12854: 
1.29      crook    12855: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    12856: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   12857: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   12858: @cindex Invalid name argument, @code{TO}
                   12859: @code{-32 throw} (Invalid name argument)
                   12860: 
                   12861: @end table
                   12862: 
                   12863: 
                   12864: @c =====================================================================
                   12865: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   12866: @section The optional Memory-Allocation word set
                   12867: @c =====================================================================
                   12868: @cindex system documentation, memory-allocation words
                   12869: @cindex memory-allocation words, system documentation
                   12870: 
                   12871: @menu
                   12872: * memory-idef::                 Implementation Defined Options                 
                   12873: @end menu
                   12874: 
                   12875: 
                   12876: @c ---------------------------------------------------------------------
                   12877: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   12878: @subsection Implementation Defined Options
                   12879: @c ---------------------------------------------------------------------
                   12880: @cindex implementation-defined options, memory-allocation words
                   12881: @cindex memory-allocation words, implementation-defined options
                   12882: 
                   12883: @table @i
1.29      crook    12884: @item values and meaning of @i{ior}:
                   12885: @cindex  @i{ior} values and meaning
                   12886: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    12887: intended as throw codes. They typically are in the range
                   12888: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    12889: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    12890: 
                   12891: @end table
                   12892: 
                   12893: @c =====================================================================
                   12894: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   12895: @section The optional Programming-Tools word set
                   12896: @c =====================================================================
                   12897: @cindex system documentation, programming-tools words
                   12898: @cindex programming-tools words, system documentation
                   12899: 
                   12900: @menu
                   12901: * programming-idef::            Implementation Defined Options            
                   12902: * programming-ambcond::         Ambiguous Conditions         
                   12903: @end menu
                   12904: 
                   12905: 
                   12906: @c ---------------------------------------------------------------------
                   12907: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   12908: @subsection Implementation Defined Options
                   12909: @c ---------------------------------------------------------------------
                   12910: @cindex implementation-defined options, programming-tools words
                   12911: @cindex programming-tools words, implementation-defined options
                   12912: 
                   12913: @table @i
                   12914: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   12915: @cindex @code{;CODE} ending sequence
                   12916: @cindex @code{CODE} ending sequence
                   12917: @code{END-CODE}
                   12918: 
                   12919: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   12920: @cindex @code{;CODE}, processing input
                   12921: @cindex @code{CODE}, processing input
                   12922: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   12923: the input is processed by the text interpreter, (starting) in interpret
                   12924: state.
                   12925: 
                   12926: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   12927: @cindex @code{ASSEMBLER}, search order capability
                   12928: The ANS Forth search order word set.
                   12929: 
                   12930: @item source and format of display by @code{SEE}:
                   12931: @cindex @code{SEE}, source and format of output
                   12932: The source for @code{see} is the intermediate code used by the inner
                   12933: interpreter.  The current @code{see} tries to output Forth source code
                   12934: as well as possible.
                   12935: 
                   12936: @end table
                   12937: 
                   12938: @c ---------------------------------------------------------------------
                   12939: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   12940: @subsection Ambiguous conditions
                   12941: @c ---------------------------------------------------------------------
                   12942: @cindex programming-tools words, ambiguous conditions
                   12943: @cindex ambiguous conditions, programming-tools words
                   12944: 
                   12945: @table @i
                   12946: 
1.21      crook    12947: @item deleting the compilation word list (@code{FORGET}):
                   12948: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    12949: Not implemented (yet).
                   12950: 
1.29      crook    12951: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   12952: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   12953: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    12954: @cindex control-flow stack underflow
                   12955: This typically results in an @code{abort"} with a descriptive error
                   12956: message (may change into a @code{-22 throw} (Control structure mismatch)
                   12957: in the future). You may also get a memory access error. If you are
                   12958: unlucky, this ambiguous condition is not caught.
                   12959: 
1.29      crook    12960: @item @i{name} can't be found (@code{FORGET}):
                   12961: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    12962: Not implemented (yet).
                   12963: 
1.29      crook    12964: @item @i{name} not defined via @code{CREATE}:
                   12965: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    12966: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   12967: the execution semantics of the last defined word no matter how it was
                   12968: defined.
                   12969: 
                   12970: @item @code{POSTPONE} applied to @code{[IF]}:
                   12971: @cindex @code{POSTPONE} applied to @code{[IF]}
                   12972: @cindex @code{[IF]} and @code{POSTPONE}
                   12973: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   12974: equivalent to @code{[IF]}.
                   12975: 
                   12976: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   12977: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   12978: Continue in the same state of conditional compilation in the next outer
                   12979: input source. Currently there is no warning to the user about this.
                   12980: 
                   12981: @item removing a needed definition (@code{FORGET}):
                   12982: @cindex @code{FORGET}, removing a needed definition
                   12983: Not implemented (yet).
                   12984: 
                   12985: @end table
                   12986: 
                   12987: 
                   12988: @c =====================================================================
                   12989: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   12990: @section The optional Search-Order word set
                   12991: @c =====================================================================
                   12992: @cindex system documentation, search-order words
                   12993: @cindex search-order words, system documentation
                   12994: 
                   12995: @menu
                   12996: * search-idef::                 Implementation Defined Options                 
                   12997: * search-ambcond::              Ambiguous Conditions              
                   12998: @end menu
                   12999: 
                   13000: 
                   13001: @c ---------------------------------------------------------------------
                   13002: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   13003: @subsection Implementation Defined Options
                   13004: @c ---------------------------------------------------------------------
                   13005: @cindex implementation-defined options, search-order words
                   13006: @cindex search-order words, implementation-defined options
                   13007: 
                   13008: @table @i
                   13009: @item maximum number of word lists in search order:
                   13010: @cindex maximum number of word lists in search order
                   13011: @cindex search order, maximum depth
                   13012: @code{s" wordlists" environment? drop .}. Currently 16.
                   13013: 
                   13014: @item minimum search order:
                   13015: @cindex minimum search order
                   13016: @cindex search order, minimum
                   13017: @code{root root}.
                   13018: 
                   13019: @end table
                   13020: 
                   13021: @c ---------------------------------------------------------------------
                   13022: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   13023: @subsection Ambiguous conditions
                   13024: @c ---------------------------------------------------------------------
                   13025: @cindex search-order words, ambiguous conditions
                   13026: @cindex ambiguous conditions, search-order words
                   13027: 
                   13028: @table @i
1.21      crook    13029: @item changing the compilation word list (during compilation):
                   13030: @cindex changing the compilation word list (during compilation)
                   13031: @cindex compilation word list, change before definition ends
                   13032: The word is entered into the word list that was the compilation word list
1.1       anton    13033: at the start of the definition. Any changes to the name field (e.g.,
                   13034: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
                   13035: are applied to the latest defined word (as reported by @code{last} or
1.21      crook    13036: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1       anton    13037: 
                   13038: @item search order empty (@code{previous}):
                   13039: @cindex @code{previous}, search order empty
1.26      crook    13040: @cindex vocstack empty, @code{previous}
1.1       anton    13041: @code{abort" Vocstack empty"}.
                   13042: 
                   13043: @item too many word lists in search order (@code{also}):
                   13044: @cindex @code{also}, too many word lists in search order
1.26      crook    13045: @cindex vocstack full, @code{also}
1.1       anton    13046: @code{abort" Vocstack full"}.
                   13047: 
                   13048: @end table
                   13049: 
                   13050: @c ***************************************************************
1.65      anton    13051: @node Standard vs Extensions, Model, ANS conformance, Top
                   13052: @chapter Should I use Gforth extensions?
                   13053: @cindex Gforth extensions
                   13054: 
                   13055: As you read through the rest of this manual, you will see documentation
                   13056: for @i{Standard} words, and documentation for some appealing Gforth
                   13057: @i{extensions}. You might ask yourself the question: @i{``Should I
                   13058: restrict myself to the standard, or should I use the extensions?''}
                   13059: 
                   13060: The answer depends on the goals you have for the program you are working
                   13061: on:
                   13062: 
                   13063: @itemize @bullet
                   13064: 
                   13065: @item Is it just for yourself or do you want to share it with others?
                   13066: 
                   13067: @item
                   13068: If you want to share it, do the others all use Gforth?
                   13069: 
                   13070: @item
                   13071: If it is just for yourself, do you want to restrict yourself to Gforth?
                   13072: 
                   13073: @end itemize
                   13074: 
                   13075: If restricting the program to Gforth is ok, then there is no reason not
                   13076: to use extensions.  It is still a good idea to keep to the standard
                   13077: where it is easy, in case you want to reuse these parts in another
                   13078: program that you want to be portable.
                   13079: 
                   13080: If you want to be able to port the program to other Forth systems, there
                   13081: are the following points to consider:
                   13082: 
                   13083: @itemize @bullet
                   13084: 
                   13085: @item
                   13086: Most Forth systems that are being maintained support the ANS Forth
                   13087: standard.  So if your program complies with the standard, it will be
                   13088: portable among many systems.
                   13089: 
                   13090: @item
                   13091: A number of the Gforth extensions can be implemented in ANS Forth using
                   13092: public-domain files provided in the @file{compat/} directory. These are
                   13093: mentioned in the text in passing.  There is no reason not to use these
                   13094: extensions, your program will still be ANS Forth compliant; just include
                   13095: the appropriate compat files with your program.
                   13096: 
                   13097: @item
                   13098: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                   13099: analyse your program and determine what non-Standard words it relies
                   13100: upon.  However, it does not check whether you use standard words in a
                   13101: non-standard way.
                   13102: 
                   13103: @item
                   13104: Some techniques are not standardized by ANS Forth, and are hard or
                   13105: impossible to implement in a standard way, but can be implemented in
                   13106: most Forth systems easily, and usually in similar ways (e.g., accessing
                   13107: word headers).  Forth has a rich historical precedent for programmers
                   13108: taking advantage of implementation-dependent features of their tools
                   13109: (for example, relying on a knowledge of the dictionary
                   13110: structure). Sometimes these techniques are necessary to extract every
                   13111: last bit of performance from the hardware, sometimes they are just a
                   13112: programming shorthand.
                   13113: 
                   13114: @item
                   13115: Does using a Gforth extension save more work than the porting this part
                   13116: to other Forth systems (if any) will cost?
                   13117: 
                   13118: @item
                   13119: Is the additional functionality worth the reduction in portability and
                   13120: the additional porting problems?
                   13121: 
                   13122: @end itemize
                   13123: 
                   13124: In order to perform these consideratios, you need to know what's
                   13125: standard and what's not.  This manual generally states if something is
                   13126: non-standard, but the authoritative source is the standard document.
                   13127: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
                   13128: into the thought processes of the technical committee.
                   13129: 
                   13130: Note also that portability between Forth systems is not the only
                   13131: portability issue; there is also the issue of portability between
                   13132: different platforms (processor/OS combinations).
                   13133: 
                   13134: @c ***************************************************************
                   13135: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1       anton    13136: @chapter Model
                   13137: 
                   13138: This chapter has yet to be written. It will contain information, on
                   13139: which internal structures you can rely.
                   13140: 
                   13141: @c ***************************************************************
                   13142: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   13143: @chapter Integrating Gforth into C programs
                   13144: 
                   13145: This is not yet implemented.
                   13146: 
                   13147: Several people like to use Forth as scripting language for applications
                   13148: that are otherwise written in C, C++, or some other language.
                   13149: 
                   13150: The Forth system ATLAST provides facilities for embedding it into
                   13151: applications; unfortunately it has several disadvantages: most
                   13152: importantly, it is not based on ANS Forth, and it is apparently dead
                   13153: (i.e., not developed further and not supported). The facilities
1.21      crook    13154: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    13155: making the switch should not be hard.
                   13156: 
                   13157: We also tried to design the interface such that it can easily be
                   13158: implemented by other Forth systems, so that we may one day arrive at a
                   13159: standardized interface. Such a standard interface would allow you to
                   13160: replace the Forth system without having to rewrite C code.
                   13161: 
                   13162: You embed the Gforth interpreter by linking with the library
                   13163: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   13164: global symbols in this library that belong to the interface, have the
                   13165: prefix @code{forth_}. (Global symbols that are used internally have the
                   13166: prefix @code{gforth_}).
                   13167: 
                   13168: You can include the declarations of Forth types and the functions and
                   13169: variables of the interface with @code{#include <forth.h>}.
                   13170: 
                   13171: Types.
                   13172: 
                   13173: Variables.
                   13174: 
                   13175: Data and FP Stack pointer. Area sizes.
                   13176: 
                   13177: functions.
                   13178: 
                   13179: forth_init(imagefile)
                   13180: forth_evaluate(string) exceptions?
                   13181: forth_goto(address) (or forth_execute(xt)?)
                   13182: forth_continue() (a corountining mechanism)
                   13183: 
                   13184: Adding primitives.
                   13185: 
                   13186: No checking.
                   13187: 
                   13188: Signals?
                   13189: 
                   13190: Accessing the Stacks
                   13191: 
1.26      crook    13192: @c ******************************************************************
1.1       anton    13193: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   13194: @chapter Emacs and Gforth
                   13195: @cindex Emacs and Gforth
                   13196: 
                   13197: @cindex @file{gforth.el}
                   13198: @cindex @file{forth.el}
                   13199: @cindex Rydqvist, Goran
                   13200: @cindex comment editing commands
                   13201: @cindex @code{\}, editing with Emacs
                   13202: @cindex debug tracer editing commands
                   13203: @cindex @code{~~}, removal with Emacs
                   13204: @cindex Forth mode in Emacs
                   13205: Gforth comes with @file{gforth.el}, an improved version of
                   13206: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    13207: improvements are:
                   13208: 
                   13209: @itemize @bullet
                   13210: @item
                   13211: A better (but still not perfect) handling of indentation.
                   13212: @item
                   13213: Comment paragraph filling (@kbd{M-q})
                   13214: @item
                   13215: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   13216: @item
                   13217: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41      anton    13218: @item
                   13219: Support of the @code{info-lookup} feature for looking up the
                   13220: documentation of a word.
1.26      crook    13221: @end itemize
                   13222: 
                   13223: I left the stuff I do not use alone, even though some of it only makes
                   13224: sense for TILE. To get a description of these features, enter Forth mode
                   13225: and type @kbd{C-h m}.
1.1       anton    13226: 
                   13227: @cindex source location of error or debugging output in Emacs
                   13228: @cindex error output, finding the source location in Emacs
                   13229: @cindex debugging output, finding the source location in Emacs
                   13230: In addition, Gforth supports Emacs quite well: The source code locations
                   13231: given in error messages, debugging output (from @code{~~}) and failed
                   13232: assertion messages are in the right format for Emacs' compilation mode
                   13233: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   13234: Manual}) so the source location corresponding to an error or other
                   13235: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   13236: @kbd{C-c C-c} for the error under the cursor).
                   13237: 
                   13238: @cindex @file{TAGS} file
                   13239: @cindex @file{etags.fs}
                   13240: @cindex viewing the source of a word in Emacs
1.43      anton    13241: @cindex @code{require}, placement in files
                   13242: @cindex @code{include}, placement in files
                   13243: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
1.26      crook    13244: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    13245: contains the definitions of all words defined afterwards. You can then
                   13246: find the source for a word using @kbd{M-.}. Note that emacs can use
                   13247: several tags files at the same time (e.g., one for the Gforth sources
                   13248: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   13249: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   13250: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43      anton    13251: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
                   13252: with @file{etags.fs}, you should avoid putting definitions both before
                   13253: and after @code{require} etc., otherwise you will see the same file
                   13254: visited several times by commands like @code{tags-search}.
1.1       anton    13255: 
1.41      anton    13256: @cindex viewing the documentation of a word in Emacs
                   13257: @cindex context-sensitive help
                   13258: Moreover, for words documented in this manual, you can look up the
                   13259: glossary entry quickly by using @kbd{C-h TAB}
                   13260: (@code{info-lookup-symbol}, see @pxref{Documentation, ,Documentation
                   13261: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
1.42      anton    13262: later and does not work for words containing @code{:}.
1.41      anton    13263: 
                   13264: 
1.1       anton    13265: @cindex @file{.emacs}
                   13266: To get all these benefits, add the following lines to your @file{.emacs}
                   13267: file:
                   13268: 
                   13269: @example
                   13270: (autoload 'forth-mode "gforth.el")
                   13271: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
                   13272: @end example
                   13273: 
1.26      crook    13274: @c ******************************************************************
1.1       anton    13275: @node Image Files, Engine, Emacs and Gforth, Top
                   13276: @chapter Image Files
1.26      crook    13277: @cindex image file
                   13278: @cindex @file{.fi} files
1.1       anton    13279: @cindex precompiled Forth code
                   13280: @cindex dictionary in persistent form
                   13281: @cindex persistent form of dictionary
                   13282: 
                   13283: An image file is a file containing an image of the Forth dictionary,
                   13284: i.e., compiled Forth code and data residing in the dictionary.  By
                   13285: convention, we use the extension @code{.fi} for image files.
                   13286: 
                   13287: @menu
1.18      anton    13288: * Image Licensing Issues::      Distribution terms for images.
                   13289: * Image File Background::       Why have image files?
1.29      crook    13290: * Non-Relocatable Image Files::   don't always work.
1.18      anton    13291: * Data-Relocatable Image Files::  are better.
1.29      crook    13292: * Fully Relocatable Image Files:: better yet.
1.18      anton    13293: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    13294: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    13295: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    13296: @end menu
                   13297: 
1.18      anton    13298: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   13299: @section Image Licensing Issues
                   13300: @cindex license for images
                   13301: @cindex image license
                   13302: 
                   13303: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   13304: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   13305: original image; i.e., according to copyright law it is a derived work of
                   13306: the original image.
                   13307: 
                   13308: Since Gforth is distributed under the GNU GPL, the newly created image
                   13309: falls under the GNU GPL, too. In particular, this means that if you
                   13310: distribute the image, you have to make all of the sources for the image
                   13311: available, including those you wrote.  For details see @ref{License, ,
                   13312: GNU General Public License (Section 3)}.
                   13313: 
                   13314: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   13315: contains only code compiled from the sources you gave it; if none of
                   13316: these sources is under the GPL, the terms discussed above do not apply
                   13317: to the image. However, if your image needs an engine (a gforth binary)
                   13318: that is under the GPL, you should make sure that you distribute both in
                   13319: a way that is at most a @emph{mere aggregation}, if you don't want the
                   13320: terms of the GPL to apply to the image.
                   13321: 
                   13322: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    13323: @section Image File Background
                   13324: @cindex image file background
                   13325: 
                   13326: Our Forth system consists not only of primitives, but also of
                   13327: definitions written in Forth. Since the Forth compiler itself belongs to
                   13328: those definitions, it is not possible to start the system with the
                   13329: primitives and the Forth source alone. Therefore we provide the Forth
1.26      crook    13330: code as an image file in nearly executable form. When Gforth starts up,
                   13331: a C routine loads the image file into memory, optionally relocates the
                   13332: addresses, then sets up the memory (stacks etc.) according to
                   13333: information in the image file, and (finally) starts executing Forth
                   13334: code.
1.1       anton    13335: 
                   13336: The image file variants represent different compromises between the
                   13337: goals of making it easy to generate image files and making them
                   13338: portable.
                   13339: 
                   13340: @cindex relocation at run-time
1.26      crook    13341: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    13342: run-time. This avoids many of the complications discussed below (image
                   13343: files are data relocatable without further ado), but costs performance
                   13344: (one addition per memory access).
                   13345: 
                   13346: @cindex relocation at load-time
1.26      crook    13347: By contrast, the Gforth loader performs relocation at image load time. The
                   13348: loader also has to replace tokens that represent primitive calls with the
1.1       anton    13349: appropriate code-field addresses (or code addresses in the case of
                   13350: direct threading).
                   13351: 
                   13352: There are three kinds of image files, with different degrees of
                   13353: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   13354: image files.
                   13355: 
                   13356: @cindex image file loader
                   13357: @cindex relocating loader
                   13358: @cindex loader for image files
                   13359: These image file variants have several restrictions in common; they are
                   13360: caused by the design of the image file loader:
                   13361: 
                   13362: @itemize @bullet
                   13363: @item
                   13364: There is only one segment; in particular, this means, that an image file
                   13365: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    13366: them). The contents of the stacks are not represented, either.
1.1       anton    13367: 
                   13368: @item
                   13369: The only kinds of relocation supported are: adding the same offset to
                   13370: all cells that represent data addresses; and replacing special tokens
                   13371: with code addresses or with pieces of machine code.
                   13372: 
                   13373: If any complex computations involving addresses are performed, the
                   13374: results cannot be represented in the image file. Several applications that
                   13375: use such computations come to mind:
                   13376: @itemize @minus
                   13377: @item
                   13378: Hashing addresses (or data structures which contain addresses) for table
                   13379: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   13380: purpose, you will have no problem, because the hash tables are
                   13381: recomputed automatically when the system is started. If you use your own
                   13382: hash tables, you will have to do something similar.
                   13383: 
                   13384: @item
                   13385: There's a cute implementation of doubly-linked lists that uses
                   13386: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   13387: in the image file, and restore the doubly-linked representation on
                   13388: startup.@footnote{In my opinion, though, you should think thrice before
                   13389: using a doubly-linked list (whatever implementation).}
                   13390: 
                   13391: @item
                   13392: The code addresses of run-time routines like @code{docol:} cannot be
                   13393: represented in the image file (because their tokens would be replaced by
                   13394: machine code in direct threaded implementations). As a workaround,
                   13395: compute these addresses at run-time with @code{>code-address} from the
                   13396: executions tokens of appropriate words (see the definitions of
                   13397: @code{docol:} and friends in @file{kernel.fs}).
                   13398: 
                   13399: @item
                   13400: On many architectures addresses are represented in machine code in some
                   13401: shifted or mangled form. You cannot put @code{CODE} words that contain
                   13402: absolute addresses in this form in a relocatable image file. Workarounds
                   13403: are representing the address in some relative form (e.g., relative to
                   13404: the CFA, which is present in some register), or loading the address from
                   13405: a place where it is stored in a non-mangled form.
                   13406: @end itemize
                   13407: @end itemize
                   13408: 
                   13409: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   13410: @section Non-Relocatable Image Files
                   13411: @cindex non-relocatable image files
1.26      crook    13412: @cindex image file, non-relocatable
1.1       anton    13413: 
                   13414: These files are simple memory dumps of the dictionary. They are specific
                   13415: to the executable (i.e., @file{gforth} file) they were created
                   13416: with. What's worse, they are specific to the place on which the
                   13417: dictionary resided when the image was created. Now, there is no
                   13418: guarantee that the dictionary will reside at the same place the next
                   13419: time you start Gforth, so there's no guarantee that a non-relocatable
                   13420: image will work the next time (Gforth will complain instead of crashing,
                   13421: though).
                   13422: 
                   13423: You can create a non-relocatable image file with
                   13424: 
1.44      crook    13425: 
1.1       anton    13426: doc-savesystem
                   13427: 
1.44      crook    13428: 
1.1       anton    13429: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   13430: @section Data-Relocatable Image Files
                   13431: @cindex data-relocatable image files
1.26      crook    13432: @cindex image file, data-relocatable
1.1       anton    13433: 
                   13434: These files contain relocatable data addresses, but fixed code addresses
                   13435: (instead of tokens). They are specific to the executable (i.e.,
                   13436: @file{gforth} file) they were created with. For direct threading on some
                   13437: architectures (e.g., the i386), data-relocatable images do not work. You
                   13438: get a data-relocatable image, if you use @file{gforthmi} with a
                   13439: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   13440: Relocatable Image Files}).
                   13441: 
                   13442: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   13443: @section Fully Relocatable Image Files
                   13444: @cindex fully relocatable image files
1.26      crook    13445: @cindex image file, fully relocatable
1.1       anton    13446: 
                   13447: @cindex @file{kern*.fi}, relocatability
                   13448: @cindex @file{gforth.fi}, relocatability
                   13449: These image files have relocatable data addresses, and tokens for code
                   13450: addresses. They can be used with different binaries (e.g., with and
                   13451: without debugging) on the same machine, and even across machines with
                   13452: the same data formats (byte order, cell size, floating point
                   13453: format). However, they are usually specific to the version of Gforth
                   13454: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   13455: are fully relocatable.
                   13456: 
                   13457: There are two ways to create a fully relocatable image file:
                   13458: 
                   13459: @menu
1.29      crook    13460: * gforthmi::                    The normal way
1.1       anton    13461: * cross.fs::                    The hard way
                   13462: @end menu
                   13463: 
                   13464: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   13465: @subsection @file{gforthmi}
                   13466: @cindex @file{comp-i.fs}
                   13467: @cindex @file{gforthmi}
                   13468: 
                   13469: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    13470: image @i{file} that contains everything you would load by invoking
                   13471: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    13472: @example
1.29      crook    13473: gforthmi @i{file} @i{options}
1.1       anton    13474: @end example
                   13475: 
                   13476: E.g., if you want to create an image @file{asm.fi} that has the file
                   13477: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   13478: like this:
                   13479: 
                   13480: @example
                   13481: gforthmi asm.fi asm.fs
                   13482: @end example
                   13483: 
1.27      crook    13484: @file{gforthmi} is implemented as a sh script and works like this: It
                   13485: produces two non-relocatable images for different addresses and then
                   13486: compares them. Its output reflects this: first you see the output (if
1.62      crook    13487: any) of the two Gforth invocations that produce the non-relocatable image
1.27      crook    13488: files, then you see the output of the comparing program: It displays the
                   13489: offset used for data addresses and the offset used for code addresses;
1.1       anton    13490: moreover, for each cell that cannot be represented correctly in the
1.44      crook    13491: image files, it displays a line like this:
1.1       anton    13492: 
                   13493: @example
                   13494:      78DC         BFFFFA50         BFFFFA40
                   13495: @end example
                   13496: 
                   13497: This means that at offset $78dc from @code{forthstart}, one input image
                   13498: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   13499: cannot be represented correctly in the output image, you should examine
                   13500: these places in the dictionary and verify that these cells are dead
                   13501: (i.e., not read before they are written).
1.39      anton    13502: 
                   13503: @cindex --application, @code{gforthmi} option
                   13504: If you insert the option @code{--application} in front of the image file
                   13505: name, you will get an image that uses the @code{--appl-image} option
                   13506: instead of the @code{--image-file} option (@pxref{Invoking
                   13507: Gforth}). When you execute such an image on Unix (by typing the image
                   13508: name as command), the Gforth engine will pass all options to the image
                   13509: instead of trying to interpret them as engine options.
1.1       anton    13510: 
1.27      crook    13511: If you type @file{gforthmi} with no arguments, it prints some usage
                   13512: instructions.
                   13513: 
1.1       anton    13514: @cindex @code{savesystem} during @file{gforthmi}
                   13515: @cindex @code{bye} during @file{gforthmi}
                   13516: @cindex doubly indirect threaded code
1.44      crook    13517: @cindex environment variables
                   13518: @cindex @code{GFORTHD} -- environment variable
                   13519: @cindex @code{GFORTH} -- environment variable
1.1       anton    13520: @cindex @code{gforth-ditc}
1.29      crook    13521: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    13522: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   13523: indirect threaded version of the @file{gforth} executable is used for
1.62      crook    13524: creating the non-relocatable images; you can pass the exact filename of
1.1       anton    13525: this executable through the environment variable @code{GFORTHD}
                   13526: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   13527: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    13528: data-relocatable image (because there is no code address offset). The
                   13529: normal @file{gforth} executable is used for creating the relocatable
                   13530: image; you can pass the exact filename of this executable through the
                   13531: environment variable @code{GFORTH}.
1.1       anton    13532: 
                   13533: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   13534: @subsection @file{cross.fs}
                   13535: @cindex @file{cross.fs}
                   13536: @cindex cross-compiler
                   13537: @cindex metacompiler
1.47      crook    13538: @cindex target compiler
1.1       anton    13539: 
                   13540: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47      crook    13541: programming language (@pxref{Cross Compiler}).
1.1       anton    13542: 
1.47      crook    13543: @code{cross} allows you to create image files for machines with
1.1       anton    13544: different data sizes and data formats than the one used for generating
                   13545: the image file. You can also use it to create an application image that
                   13546: does not contain a Forth compiler. These features are bought with
                   13547: restrictions and inconveniences in programming. E.g., addresses have to
                   13548: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   13549: order to make the code relocatable.
                   13550: 
                   13551: 
                   13552: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   13553: @section Stack and Dictionary Sizes
                   13554: @cindex image file, stack and dictionary sizes
                   13555: @cindex dictionary size default
                   13556: @cindex stack size default
                   13557: 
                   13558: If you invoke Gforth with a command line flag for the size
                   13559: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   13560: dictionary. If you save the dictionary with @code{savesystem} or create
                   13561: an image with @file{gforthmi}, this size will become the default
                   13562: for the resulting image file. E.g., the following will create a
1.21      crook    13563: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    13564: 
                   13565: @example
                   13566: gforthmi gforth.fi -m 1M
                   13567: @end example
                   13568: 
                   13569: In other words, if you want to set the default size for the dictionary
                   13570: and the stacks of an image, just invoke @file{gforthmi} with the
                   13571: appropriate options when creating the image.
                   13572: 
                   13573: @cindex stack size, cache-friendly
                   13574: Note: For cache-friendly behaviour (i.e., good performance), you should
                   13575: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   13576: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   13577: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   13578: 
                   13579: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   13580: @section Running Image Files
                   13581: @cindex running image files
                   13582: @cindex invoking image files
                   13583: @cindex image file invocation
                   13584: 
                   13585: @cindex -i, invoke image file
                   13586: @cindex --image file, invoke image file
1.29      crook    13587: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    13588: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   13589: @example
1.29      crook    13590: gforth -i @i{image}
1.1       anton    13591: @end example
                   13592: 
                   13593: @cindex executable image file
1.26      crook    13594: @cindex image file, executable
1.1       anton    13595: If your operating system supports starting scripts with a line of the
                   13596: form @code{#! ...}, you just have to type the image file name to start
                   13597: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    13598: just a convention). I.e., to run Gforth with the image file @i{image},
                   13599: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    13600: This works because every @code{.fi} file starts with a line of this
                   13601: format:
                   13602: 
                   13603: @example
                   13604: #! /usr/local/bin/gforth-0.4.0 -i
                   13605: @end example
                   13606: 
                   13607: The file and pathname for the Gforth engine specified on this line is
                   13608: the specific Gforth executable that it was built against; i.e. the value
                   13609: of the environment variable @code{GFORTH} at the time that
                   13610: @file{gforthmi} was executed.
1.1       anton    13611: 
1.27      crook    13612: You can make use of the same shell capability to make a Forth source
                   13613: file into an executable. For example, if you place this text in a file:
1.26      crook    13614: 
                   13615: @example
                   13616: #! /usr/local/bin/gforth
                   13617: 
                   13618: ." Hello, world" CR
                   13619: bye
                   13620: @end example
                   13621: 
                   13622: @noindent
1.27      crook    13623: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    13624: directly from the command line. The sequence @code{#!} is used in two
                   13625: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    13626: system@footnote{The Unix kernel actually recognises two types of files:
                   13627: executable files and files of data, where the data is processed by an
                   13628: interpreter that is specified on the ``interpreter line'' -- the first
                   13629: line of the file, starting with the sequence #!. There may be a small
                   13630: limit (e.g., 32) on the number of characters that may be specified on
                   13631: the interpreter line.} secondly it is treated as a comment character by
                   13632: Gforth. Because of the second usage, a space is required between
                   13633: @code{#!} and the path to the executable.
1.27      crook    13634: 
                   13635: The disadvantage of this latter technique, compared with using
                   13636: @file{gforthmi}, is that it is slower; the Forth source code is compiled
                   13637: on-the-fly, each time the program is invoked.
                   13638: 
1.26      crook    13639: 
1.1       anton    13640: doc-#!
                   13641: 
1.44      crook    13642: 
1.1       anton    13643: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   13644: @section Modifying the Startup Sequence
                   13645: @cindex startup sequence for image file
                   13646: @cindex image file initialization sequence
                   13647: @cindex initialization sequence of image file
                   13648: 
                   13649: You can add your own initialization to the startup sequence through the
1.26      crook    13650: deferred word @code{'cold}. @code{'cold} is invoked just before the
                   13651: image-specific command line processing (by default, loading files and
                   13652: evaluating (@code{-e}) strings) starts.
1.1       anton    13653: 
                   13654: A sequence for adding your initialization usually looks like this:
                   13655: 
                   13656: @example
                   13657: :noname
                   13658:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   13659:     ... \ your stuff
                   13660: ; IS 'cold
                   13661: @end example
                   13662: 
                   13663: @cindex turnkey image files
1.26      crook    13664: @cindex image file, turnkey applications
1.1       anton    13665: You can make a turnkey image by letting @code{'cold} execute a word
                   13666: (your turnkey application) that never returns; instead, it exits Gforth
                   13667: via @code{bye} or @code{throw}.
                   13668: 
                   13669: @cindex command-line arguments, access
                   13670: @cindex arguments on the command line, access
                   13671: You can access the (image-specific) command-line arguments through the
1.26      crook    13672: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1       anton    13673: access to @code{argv}.
                   13674: 
1.26      crook    13675: If @code{'cold} exits normally, Gforth processes the command-line
                   13676: arguments as files to be loaded and strings to be evaluated.  Therefore,
                   13677: @code{'cold} should remove the arguments it has used in this case.
                   13678: 
1.44      crook    13679: 
                   13680: 
1.26      crook    13681: doc-'cold
1.1       anton    13682: doc-argc
                   13683: doc-argv
                   13684: doc-arg
                   13685: 
                   13686: 
1.44      crook    13687: 
1.1       anton    13688: @c ******************************************************************
1.13      pazsan   13689: @node Engine, Binding to System Library, Image Files, Top
1.1       anton    13690: @chapter Engine
                   13691: @cindex engine
                   13692: @cindex virtual machine
                   13693: 
1.26      crook    13694: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    13695: may be helpful for finding your way in the Gforth sources.
                   13696: 
1.66    ! anton    13697: The ideas in this section have also been published in Bernd Paysan,
        !          13698: @cite{ANS fig/GNU/??? Forth} (in German), Forth-Tagung '93 and M. Anton
        !          13699: Ertl, @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
        !          13700: Portable Forth Engine}}, EuroForth '93.
1.1       anton    13701: 
                   13702: @menu
                   13703: * Portability::                 
                   13704: * Threading::                   
                   13705: * Primitives::                  
                   13706: * Performance::                 
                   13707: @end menu
                   13708: 
                   13709: @node Portability, Threading, Engine, Engine
                   13710: @section Portability
                   13711: @cindex engine portability
                   13712: 
1.26      crook    13713: An important goal of the Gforth Project is availability across a wide
                   13714: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   13715: achieved this goal by manually coding the engine in assembly language
                   13716: for several then-popular processors. This approach is very
                   13717: labor-intensive and the results are short-lived due to progress in
                   13718: computer architecture.
1.1       anton    13719: 
                   13720: @cindex C, using C for the engine
                   13721: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   13722: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   13723: particularly popular for UNIX-based Forths due to the large variety of
                   13724: architectures of UNIX machines. Unfortunately an implementation in C
                   13725: does not mix well with the goals of efficiency and with using
                   13726: traditional techniques: Indirect or direct threading cannot be expressed
                   13727: in C, and switch threading, the fastest technique available in C, is
                   13728: significantly slower. Another problem with C is that it is very
                   13729: cumbersome to express double integer arithmetic.
                   13730: 
                   13731: @cindex GNU C for the engine
                   13732: @cindex long long
                   13733: Fortunately, there is a portable language that does not have these
                   13734: limitations: GNU C, the version of C processed by the GNU C compiler
                   13735: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   13736: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   13737: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   13738: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   13739: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
                   13740: double numbers@footnote{Unfortunately, long longs are not implemented
                   13741: properly on all machines (e.g., on alpha-osf1, long longs are only 64
                   13742: bits, the same size as longs (and pointers), but they should be twice as
1.4       anton    13743: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1       anton    13744: C Manual}). So, we had to implement doubles in C after all. Still, on
                   13745: most machines we can use long longs and achieve better performance than
                   13746: with the emulation package.}. GNU C is available for free on all
                   13747: important (and many unimportant) UNIX machines, VMS, 80386s running
                   13748: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   13749: on all these machines.
                   13750: 
                   13751: Writing in a portable language has the reputation of producing code that
                   13752: is slower than assembly. For our Forth engine we repeatedly looked at
                   13753: the code produced by the compiler and eliminated most compiler-induced
                   13754: inefficiencies by appropriate changes in the source code.
                   13755: 
                   13756: @cindex explicit register declarations
                   13757: @cindex --enable-force-reg, configuration flag
                   13758: @cindex -DFORCE_REG
                   13759: However, register allocation cannot be portably influenced by the
                   13760: programmer, leading to some inefficiencies on register-starved
                   13761: machines. We use explicit register declarations (@pxref{Explicit Reg
                   13762: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   13763: improve the speed on some machines. They are turned on by using the
                   13764: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   13765: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   13766: machine, but also on the compiler version: On some machines some
                   13767: compiler versions produce incorrect code when certain explicit register
                   13768: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   13769: 
                   13770: @node Threading, Primitives, Portability, Engine
                   13771: @section Threading
                   13772: @cindex inner interpreter implementation
                   13773: @cindex threaded code implementation
                   13774: 
                   13775: @cindex labels as values
                   13776: GNU C's labels as values extension (available since @code{gcc-2.0},
                   13777: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    13778: makes it possible to take the address of @i{label} by writing
                   13779: @code{&&@i{label}}.  This address can then be used in a statement like
                   13780: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    13781: @code{goto x}.
                   13782: 
1.26      crook    13783: @cindex @code{NEXT}, indirect threaded
1.1       anton    13784: @cindex indirect threaded inner interpreter
                   13785: @cindex inner interpreter, indirect threaded
1.26      crook    13786: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    13787: @example
                   13788: cfa = *ip++;
                   13789: ca = *cfa;
                   13790: goto *ca;
                   13791: @end example
                   13792: @cindex instruction pointer
                   13793: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   13794: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   13795: execution token and points to the code field of the next word to be
                   13796: executed; The @code{ca} (code address) fetched from there points to some
                   13797: executable code, e.g., a primitive or the colon definition handler
                   13798: @code{docol}.
                   13799: 
1.26      crook    13800: @cindex @code{NEXT}, direct threaded
1.1       anton    13801: @cindex direct threaded inner interpreter
                   13802: @cindex inner interpreter, direct threaded
                   13803: Direct threading is even simpler:
                   13804: @example
                   13805: ca = *ip++;
                   13806: goto *ca;
                   13807: @end example
                   13808: 
                   13809: Of course we have packaged the whole thing neatly in macros called
1.26      crook    13810: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    13811: 
                   13812: @menu
                   13813: * Scheduling::                  
                   13814: * Direct or Indirect Threaded?::  
                   13815: * DOES>::                       
                   13816: @end menu
                   13817: 
                   13818: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   13819: @subsection Scheduling
                   13820: @cindex inner interpreter optimization
                   13821: 
                   13822: There is a little complication: Pipelined and superscalar processors,
                   13823: i.e., RISC and some modern CISC machines can process independent
                   13824: instructions while waiting for the results of an instruction. The
                   13825: compiler usually reorders (schedules) the instructions in a way that
                   13826: achieves good usage of these delay slots. However, on our first tries
                   13827: the compiler did not do well on scheduling primitives. E.g., for
                   13828: @code{+} implemented as
                   13829: @example
                   13830: n=sp[0]+sp[1];
                   13831: sp++;
                   13832: sp[0]=n;
                   13833: NEXT;
                   13834: @end example
1.26      crook    13835: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1       anton    13836: scheduling. After a little thought the problem becomes clear: The
1.21      crook    13837: compiler cannot know that @code{sp} and @code{ip} point to different
                   13838: addresses (and the version of @code{gcc} we used would not know it even
                   13839: if it was possible), so it could not move the load of the cfa above the
                   13840: store to the TOS. Indeed the pointers could be the same, if code on or
                   13841: very near the top of stack were executed. In the interest of speed we
                   13842: chose to forbid this probably unused ``feature'' and helped the compiler
1.26      crook    13843: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21      crook    13844: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1       anton    13845: @example
                   13846: n=sp[0]+sp[1];
                   13847: sp++;
                   13848: NEXT_P1;
                   13849: sp[0]=n;
                   13850: NEXT_P2;
                   13851: @end example
                   13852: This can be scheduled optimally by the compiler.
                   13853: 
                   13854: This division can be turned off with the switch @code{-DCISC_NEXT}. This
                   13855: switch is on by default on machines that do not profit from scheduling
                   13856: (e.g., the 80386), in order to preserve registers.
                   13857: 
                   13858: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
                   13859: @subsection Direct or Indirect Threaded?
                   13860: @cindex threading, direct or indirect?
                   13861: 
                   13862: @cindex -DDIRECT_THREADED
                   13863: Both! After packaging the nasty details in macro definitions we
                   13864: realized that we could switch between direct and indirect threading by
                   13865: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
                   13866: defining a few machine-specific macros for the direct-threading case.
                   13867: On the Forth level we also offer access words that hide the
                   13868: differences between the threading methods (@pxref{Threading Words}).
                   13869: 
                   13870: Indirect threading is implemented completely machine-independently.
                   13871: Direct threading needs routines for creating jumps to the executable
1.21      crook    13872: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
                   13873: machine-dependent, but they do not amount to many source lines. Therefore,
                   13874: even porting direct threading to a new machine requires little effort.
1.1       anton    13875: 
                   13876: @cindex --enable-indirect-threaded, configuration flag
                   13877: @cindex --enable-direct-threaded, configuration flag
                   13878: The default threading method is machine-dependent. You can enforce a
                   13879: specific threading method when building Gforth with the configuration
                   13880: flag @code{--enable-direct-threaded} or
                   13881: @code{--enable-indirect-threaded}. Note that direct threading is not
                   13882: supported on all machines.
                   13883: 
                   13884: @node DOES>,  , Direct or Indirect Threaded?, Threading
                   13885: @subsection DOES>
                   13886: @cindex @code{DOES>} implementation
                   13887: 
1.26      crook    13888: @cindex @code{dodoes} routine
                   13889: @cindex @code{DOES>}-code
1.1       anton    13890: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   13891: the chunk of code executed by every word defined by a
                   13892: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
                   13893: the Forth code to be executed, i.e. the code after the
1.26      crook    13894: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1       anton    13895: 
1.21      crook    13896: In fig-Forth the code field points directly to the @code{dodoes} and the
1.45      crook    13897: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
1.29      crook    13898: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1       anton    13899: the Forth-79 and all later standards, because in fig-Forth this address
                   13900: lies in the body (which is illegal in these standards). However, by
                   13901: making the code field larger for all words this solution becomes legal
                   13902: again. We use this approach for the indirect threaded version and for
                   13903: direct threading on some machines. Leaving a cell unused in most words
                   13904: is a bit wasteful, but on the machines we are targeting this is hardly a
                   13905: problem. The other reason for having a code field size of two cells is
                   13906: to avoid having different image files for direct and indirect threaded
                   13907: systems (direct threaded systems require two-cell code fields on many
                   13908: machines).
                   13909: 
1.26      crook    13910: @cindex @code{DOES>}-handler
1.1       anton    13911: The other approach is that the code field points or jumps to the cell
1.26      crook    13912: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
                   13913: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
                   13914: @code{DOES>}-code address by computing the code address, i.e., the address of
1.45      crook    13915: the jump to @code{dodoes}, and add the length of that jump field. A variant of
1.1       anton    13916: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
                   13917: return address (which can be found in the return register on RISCs) is
1.26      crook    13918: the @code{DOES>}-code address. Since the two cells available in the code field
1.1       anton    13919: are used up by the jump to the code address in direct threading on many
                   13920: architectures, we use this approach for direct threading on these
                   13921: architectures. We did not want to add another cell to the code field.
                   13922: 
                   13923: @node Primitives, Performance, Threading, Engine
                   13924: @section Primitives
                   13925: @cindex primitives, implementation
                   13926: @cindex virtual machine instructions, implementation
                   13927: 
                   13928: @menu
                   13929: * Automatic Generation::        
                   13930: * TOS Optimization::            
                   13931: * Produced code::               
                   13932: @end menu
                   13933: 
                   13934: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   13935: @subsection Automatic Generation
                   13936: @cindex primitives, automatic generation
                   13937: 
                   13938: @cindex @file{prims2x.fs}
                   13939: Since the primitives are implemented in a portable language, there is no
                   13940: longer any need to minimize the number of primitives. On the contrary,
                   13941: having many primitives has an advantage: speed. In order to reduce the
                   13942: number of errors in primitives and to make programming them easier, we
                   13943: provide a tool, the primitive generator (@file{prims2x.fs}), that
                   13944: automatically generates most (and sometimes all) of the C code for a
                   13945: primitive from the stack effect notation.  The source for a primitive
                   13946: has the following form:
                   13947: 
                   13948: @cindex primitive source format
                   13949: @format
1.58      anton    13950: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
1.29      crook    13951: [@code{""}@i{glossary entry}@code{""}]
                   13952: @i{C code}
1.1       anton    13953: [@code{:}
1.29      crook    13954: @i{Forth code}]
1.1       anton    13955: @end format
                   13956: 
                   13957: The items in brackets are optional. The category and glossary fields
                   13958: are there for generating the documentation, the Forth code is there
                   13959: for manual implementations on machines without GNU C. E.g., the source
                   13960: for the primitive @code{+} is:
                   13961: @example
1.58      anton    13962: +    ( n1 n2 -- n )   core    plus
1.1       anton    13963: n = n1+n2;
                   13964: @end example
                   13965: 
                   13966: This looks like a specification, but in fact @code{n = n1+n2} is C
                   13967: code. Our primitive generation tool extracts a lot of information from
                   13968: the stack effect notations@footnote{We use a one-stack notation, even
                   13969: though we have separate data and floating-point stacks; The separate
                   13970: notation can be generated easily from the unified notation.}: The number
                   13971: of items popped from and pushed on the stack, their type, and by what
                   13972: name they are referred to in the C code. It then generates a C code
                   13973: prelude and postlude for each primitive. The final C code for @code{+}
                   13974: looks like this:
                   13975: 
                   13976: @example
1.46      pazsan   13977: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
1.1       anton    13978: /*  */                          /* documentation */
                   13979: @{
                   13980: DEF_CA                          /* definition of variable ca (indirect threading) */
                   13981: Cell n1;                        /* definitions of variables */
                   13982: Cell n2;
                   13983: Cell n;
                   13984: n1 = (Cell) sp[1];              /* input */
                   13985: n2 = (Cell) TOS;
                   13986: sp += 1;                        /* stack adjustment */
                   13987: NAME("+")                       /* debugging output (with -DDEBUG) */
                   13988: @{
                   13989: n = n1+n2;                      /* C code taken from the source */
                   13990: @}
                   13991: NEXT_P1;                        /* NEXT part 1 */
                   13992: TOS = (Cell)n;                  /* output */
                   13993: NEXT_P2;                        /* NEXT part 2 */
                   13994: @}
                   13995: @end example
                   13996: 
                   13997: This looks long and inefficient, but the GNU C compiler optimizes quite
                   13998: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   13999: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   14000: using them as intermediate storage also adds no cost.
                   14001: 
1.26      crook    14002: There are also other optimizations that are not illustrated by this
                   14003: example: assignments between simple variables are usually for free (copy
1.1       anton    14004: propagation). If one of the stack items is not used by the primitive
                   14005: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   14006: (dead code elimination). On the other hand, there are some things that
                   14007: the compiler does not do, therefore they are performed by
                   14008: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   14009: a stack item to the place where it just came from (e.g., @code{over}).
                   14010: 
                   14011: While programming a primitive is usually easy, there are a few cases
                   14012: where the programmer has to take the actions of the generator into
                   14013: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    14014: fall through to @code{NEXT}.
1.1       anton    14015: 
                   14016: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   14017: @subsection TOS Optimization
                   14018: @cindex TOS optimization for primitives
                   14019: @cindex primitives, keeping the TOS in a register
                   14020: 
                   14021: An important optimization for stack machine emulators, e.g., Forth
                   14022: engines, is keeping  one or more of the top stack items in
1.29      crook    14023: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   14024: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    14025: @itemize @bullet
                   14026: @item
1.29      crook    14027: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    14028: due to fewer loads from and stores to the stack.
1.29      crook    14029: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   14030: @i{y<n}, due to additional moves between registers.
1.1       anton    14031: @end itemize
                   14032: 
                   14033: @cindex -DUSE_TOS
                   14034: @cindex -DUSE_NO_TOS
                   14035: In particular, keeping one item in a register is never a disadvantage,
                   14036: if there are enough registers. Keeping two items in registers is a
                   14037: disadvantage for frequent words like @code{?branch}, constants,
                   14038: variables, literals and @code{i}. Therefore our generator only produces
                   14039: code that keeps zero or one items in registers. The generated C code
                   14040: covers both cases; the selection between these alternatives is made at
                   14041: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   14042: code for @code{+} is just a simple variable name in the one-item case,
                   14043: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   14044: GNU C compiler tries to keep simple variables like @code{TOS} in
                   14045: registers, and it usually succeeds, if there are enough registers.
                   14046: 
                   14047: @cindex -DUSE_FTOS
                   14048: @cindex -DUSE_NO_FTOS
                   14049: The primitive generator performs the TOS optimization for the
                   14050: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   14051: operations the benefit of this optimization is even larger:
                   14052: floating-point operations take quite long on most processors, but can be
                   14053: performed in parallel with other operations as long as their results are
                   14054: not used. If the FP-TOS is kept in a register, this works. If
                   14055: it is kept on the stack, i.e., in memory, the store into memory has to
                   14056: wait for the result of the floating-point operation, lengthening the
                   14057: execution time of the primitive considerably.
                   14058: 
                   14059: The TOS optimization makes the automatic generation of primitives a
                   14060: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   14061: @code{TOS} is not sufficient. There are some special cases to
                   14062: consider:
                   14063: @itemize @bullet
                   14064: @item In the case of @code{dup ( w -- w w )} the generator must not
                   14065: eliminate the store to the original location of the item on the stack,
                   14066: if the TOS optimization is turned on.
                   14067: @item Primitives with stack effects of the form @code{--}
1.29      crook    14068: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   14069: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    14070: must load the TOS from the stack at the end. But for the null stack
                   14071: effect @code{--} no stores or loads should be generated.
                   14072: @end itemize
                   14073: 
                   14074: @node Produced code,  , TOS Optimization, Primitives
                   14075: @subsection Produced code
                   14076: @cindex primitives, assembly code listing
                   14077: 
                   14078: @cindex @file{engine.s}
                   14079: To see what assembly code is produced for the primitives on your machine
                   14080: with your compiler and your flag settings, type @code{make engine.s} and
                   14081: look at the resulting file @file{engine.s}.
                   14082: 
                   14083: @node  Performance,  , Primitives, Engine
                   14084: @section Performance
                   14085: @cindex performance of some Forth interpreters
                   14086: @cindex engine performance
                   14087: @cindex benchmarking Forth systems
                   14088: @cindex Gforth performance
                   14089: 
                   14090: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
                   14091: impossible to write a significantly faster engine.
                   14092: 
                   14093: On register-starved machines like the 386 architecture processors
                   14094: improvements are possible, because @code{gcc} does not utilize the
                   14095: registers as well as a human, even with explicit register declarations;
                   14096: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   14097: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   14098: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40      anton    14099: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
                   14100: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
                   14101: registers fit in real registers (and we can even afford to use the TOS
                   14102: optimization), resulting in a speedup of 1.14 on the sieve over the
                   14103: earlier results.
1.1       anton    14104: 
                   14105: @cindex Win32Forth performance
                   14106: @cindex NT Forth performance
                   14107: @cindex eforth performance
                   14108: @cindex ThisForth performance
                   14109: @cindex PFE performance
                   14110: @cindex TILE performance
1.40      anton    14111: The potential advantage of assembly language implementations
1.1       anton    14112: is not necessarily realized in complete Forth systems: We compared
1.40      anton    14113: Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and
1.1       anton    14114: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
                   14115: 1994) and Eforth (with and without peephole (aka pinhole) optimization
                   14116: of the threaded code); all these systems were written in assembly
                   14117: language. We also compared Gforth with three systems written in C:
                   14118: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
                   14119: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21      crook    14120: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
                   14121: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1       anton    14122: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
                   14123: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
                   14124: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
                   14125: 486DX2/66 with similar memory performance under Windows NT. Marcel
                   14126: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
                   14127: added the peephole optimizer, ran the benchmarks and reported the
                   14128: results.
1.40      anton    14129: 
1.1       anton    14130: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   14131: matrix multiplication come from the Stanford integer benchmarks and have
                   14132: been translated into Forth by Martin Fraeman; we used the versions
                   14133: included in the TILE Forth package, but with bigger data set sizes; and
                   14134: a recursive Fibonacci number computation for benchmarking calling
                   14135: performance. The following table shows the time taken for the benchmarks
                   14136: scaled by the time taken by Gforth (in other words, it shows the speedup
                   14137: factor that Gforth achieved over the other systems).
                   14138: 
                   14139: @example
1.40      anton    14140: relative      Win32-    NT       eforth       This-      
1.1       anton    14141:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
1.40      anton    14142: sieve     1.00  1.58  1.30   1.58  0.97  1.80  3.63  9.79
                   14143: bubble    1.00  1.55  1.67   1.75  1.04  1.78        4.59
                   14144: matmul    1.00  1.67  1.53   1.66  0.84  1.79        4.63
                   14145: fib       1.00  1.75  1.53   1.40  0.99  1.99  3.43  4.93
1.1       anton    14146: @end example
                   14147: 
1.26      crook    14148: You may be quite surprised by the good performance of Gforth when
                   14149: compared with systems written in assembly language. One important reason
                   14150: for the disappointing performance of these other systems is probably
                   14151: that they are not written optimally for the 486 (e.g., they use the
                   14152: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   14153: but costly method for relocating the Forth image: like @code{cforth}, it
                   14154: computes the actual addresses at run time, resulting in two address
                   14155: computations per @code{NEXT} (@pxref{Image File Background}).
                   14156: 
1.40      anton    14157: Only Eforth with the peephole optimizer performs comparable to
                   14158: Gforth. The speedups achieved with peephole optimization of threaded
                   14159: code are quite remarkable. Adding a peephole optimizer to Gforth should
                   14160: cause similar speedups.
1.1       anton    14161: 
                   14162: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   14163: explained with the self-imposed restriction of the latter systems to
                   14164: standard C, which makes efficient threading impossible (however, the
1.4       anton    14165: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    14166: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   14167: Moreover, current C compilers have a hard time optimizing other aspects
                   14168: of the ThisForth and the TILE source.
                   14169: 
1.26      crook    14170: The performance of Gforth on 386 architecture processors varies widely
                   14171: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   14172: allocate any of the virtual machine registers into real machine
                   14173: registers by itself and would not work correctly with explicit register
1.40      anton    14174: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26      crook    14175: the Sieve) than the one measured above.
1.1       anton    14176: 
1.26      crook    14177: Note that there have been several releases of Win32Forth since the
                   14178: release presented here, so the results presented above may have little
1.40      anton    14179: predictive value for the performance of Win32Forth today (results for
                   14180: the current release on an i486DX2/66 are welcome).
1.1       anton    14181: 
                   14182: @cindex @file{Benchres}
1.66    ! anton    14183: In
        !          14184: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
        !          14185: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1       anton    14186: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66    ! anton    14187: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
        !          14188: several native code systems; that version of Gforth is slower on a 486
        !          14189: than the direct threaded version used here. You can find a newer version
        !          14190: of these measurements at
1.47      crook    14191: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1       anton    14192: find numbers for Gforth on various machines in @file{Benchres}.
                   14193: 
1.26      crook    14194: @c ******************************************************************
1.13      pazsan   14195: @node Binding to System Library, Cross Compiler, Engine, Top
1.14      pazsan   14196: @chapter Binding to System Library
1.13      pazsan   14197: 
                   14198: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14      pazsan   14199: @chapter Cross Compiler
1.47      crook    14200: @cindex @file{cross.fs}
                   14201: @cindex cross-compiler
                   14202: @cindex metacompiler
                   14203: @cindex target compiler
1.13      pazsan   14204: 
1.46      pazsan   14205: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
                   14206: mostly written in Forth, including crucial parts like the outer
                   14207: interpreter and compiler, it needs compiled Forth code to get
                   14208: started. The cross compiler allows to create new images for other
                   14209: architectures, even running under another Forth system.
1.13      pazsan   14210: 
                   14211: @menu
                   14212: * Using the Cross Compiler::
                   14213: * How the Cross Compiler Works::
                   14214: @end menu
                   14215: 
1.21      crook    14216: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   14217: @section Using the Cross Compiler
1.46      pazsan   14218: 
                   14219: The cross compiler uses a language that resembles Forth, but isn't. The
                   14220: main difference is that you can execute Forth code after definition,
                   14221: while you usually can't execute the code compiled by cross, because the
                   14222: code you are compiling is typically for a different computer than the
                   14223: one you are compiling on.
                   14224: 
                   14225: The Makefile is already set up to allow you to create kernels for new
                   14226: architectures with a simple make command. The generic kernels using the
                   14227: GCC compiled virtual machine are created in the normal build process
                   14228: with @code{make}. To create a embedded Gforth executable for e.g. the
                   14229: 8086 processor (running on a DOS machine), type
                   14230: 
                   14231: @example
                   14232: make kernl-8086.fi
                   14233: @end example
                   14234: 
                   14235: This will use the machine description from the @file{arch/8086}
                   14236: directory to create a new kernel. A machine file may look like that:
                   14237: 
                   14238: @example
                   14239: \ Parameter for target systems                         06oct92py
                   14240: 
                   14241:     4 Constant cell             \ cell size in bytes
                   14242:     2 Constant cell<<           \ cell shift to bytes
                   14243:     5 Constant cell>bit         \ cell shift to bits
                   14244:     8 Constant bits/char        \ bits per character
                   14245:     8 Constant bits/byte        \ bits per byte [default: 8]
                   14246:     8 Constant float            \ bytes per float
                   14247:     8 Constant /maxalign        \ maximum alignment in bytes
                   14248: false Constant bigendian        \ byte order
                   14249: ( true=big, false=little )
                   14250: 
                   14251: include machpc.fs               \ feature list
                   14252: @end example
                   14253: 
                   14254: This part is obligatory for the cross compiler itself, the feature list
                   14255: is used by the kernel to conditionally compile some features in and out,
                   14256: depending on whether the target supports these features.
                   14257: 
                   14258: There are some optional features, if you define your own primitives,
                   14259: have an assembler, or need special, nonstandard preparation to make the
                   14260: boot process work. @code{asm-include} include an assembler,
                   14261: @code{prims-include} includes primitives, and @code{>boot} prepares for
                   14262: booting.
                   14263: 
                   14264: @example
                   14265: : asm-include    ." Include assembler" cr
                   14266:   s" arch/8086/asm.fs" included ;
                   14267: 
                   14268: : prims-include  ." Include primitives" cr
                   14269:   s" arch/8086/prim.fs" included ;
                   14270: 
                   14271: : >boot          ." Prepare booting" cr
                   14272:   s" ' boot >body into-forth 1+ !" evaluate ;
                   14273: @end example
                   14274: 
                   14275: These words are used as sort of macro during the cross compilation in
                   14276: the file @file{kernel/main.fs}. Instead of using this macros, it would
                   14277: be possible --- but more complicated --- to write a new kernel project
                   14278: file, too.
                   14279: 
                   14280: @file{kernel/main.fs} expects the machine description file name on the
                   14281: stack; the cross compiler itself (@file{cross.fs}) assumes that either
                   14282: @code{mach-file} leaves a counted string on the stack, or
                   14283: @code{machine-file} leaves an address, count pair of the filename on the
                   14284: stack.
                   14285: 
                   14286: The feature list is typically controlled using @code{SetValue}, generic
                   14287: files that are used by several projects can use @code{DefaultValue}
                   14288: instead. Both functions work like @code{Value}, when the value isn't
                   14289: defined, but @code{SetValue} works like @code{to} if the value is
                   14290: defined, and @code{DefaultValue} doesn't set anything, if the value is
                   14291: defined.
                   14292: 
                   14293: @example
                   14294: \ generic mach file for pc gforth                       03sep97jaw
                   14295: 
                   14296: true DefaultValue NIL  \ relocating
                   14297: 
                   14298: >ENVIRON
                   14299: 
                   14300: true DefaultValue file          \ controls the presence of the
                   14301:                                 \ file access wordset
                   14302: true DefaultValue OS            \ flag to indicate a operating system
                   14303: 
                   14304: true DefaultValue prims         \ true: primitives are c-code
                   14305: 
                   14306: true DefaultValue floating      \ floating point wordset is present
                   14307: 
                   14308: true DefaultValue glocals       \ gforth locals are present
                   14309:                                 \ will be loaded
                   14310: true DefaultValue dcomps        \ double number comparisons
                   14311: 
                   14312: true DefaultValue hash          \ hashing primitives are loaded/present
                   14313: 
                   14314: true DefaultValue xconds        \ used together with glocals,
                   14315:                                 \ special conditionals supporting gforths'
                   14316:                                 \ local variables
                   14317: true DefaultValue header        \ save a header information
                   14318: 
                   14319: true DefaultValue backtrace     \ enables backtrace code
                   14320: 
                   14321: false DefaultValue ec
                   14322: false DefaultValue crlf
                   14323: 
                   14324: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
                   14325: 
                   14326: &16 KB          DefaultValue stack-size
                   14327: &15 KB &512 +   DefaultValue fstack-size
                   14328: &15 KB          DefaultValue rstack-size
                   14329: &14 KB &512 +   DefaultValue lstack-size
                   14330: @end example
1.13      pazsan   14331: 
1.48      anton    14332: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
1.14      pazsan   14333: @section How the Cross Compiler Works
1.13      pazsan   14334: 
                   14335: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    14336: @appendix Bugs
1.1       anton    14337: @cindex bug reporting
                   14338: 
1.21      crook    14339: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    14340: 
                   14341: If you find a bug, please send a bug report to
1.33      anton    14342: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21      crook    14343: information:
                   14344: 
                   14345: @itemize @bullet
                   14346: @item
                   14347: The Gforth version used (it is announced at the start of an
                   14348: interactive Gforth session).
                   14349: @item
                   14350: The machine and operating system (on Unix
                   14351: systems @code{uname -a} will report this information).
                   14352: @item
                   14353: The installation options (send the file @file{config.status}).
                   14354: @item
                   14355: A complete list of changes (if any) you (or your installer) have made to the
                   14356: Gforth sources.
                   14357: @item
                   14358: A program (or a sequence of keyboard commands) that reproduces the bug.
                   14359: @item
                   14360: A description of what you think constitutes the buggy behaviour.
                   14361: @end itemize
1.1       anton    14362: 
                   14363: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   14364: to Report Bugs, gcc.info, GNU C Manual}.
                   14365: 
                   14366: 
1.21      crook    14367: @node Origin, Forth-related information, Bugs, Top
                   14368: @appendix Authors and Ancestors of Gforth
1.1       anton    14369: 
                   14370: @section Authors and Contributors
                   14371: @cindex authors of Gforth
                   14372: @cindex contributors to Gforth
                   14373: 
                   14374: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
                   14375: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
                   14376: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
                   14377: with their continuous feedback. Lennart Benshop contributed
                   14378: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
                   14379: support for calling C libraries. Helpful comments also came from Paul
                   14380: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.58      anton    14381: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
                   14382: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
                   14383: helpful comments from many others; thank you all, sorry for not listing
                   14384: you here (but digging through my mailbox to extract your names is on my
                   14385: to-do list). Since the release of Gforth-0.4.0 Neal Crook worked on the
                   14386: manual.
1.1       anton    14387: 
                   14388: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   14389: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    14390: was developed across the Internet, and its authors did not meet
1.20      pazsan   14391: physically for the first 4 years of development.
1.1       anton    14392: 
                   14393: @section Pedigree
1.26      crook    14394: @cindex pedigree of Gforth
1.1       anton    14395: 
1.20      pazsan   14396: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1       anton    14397: Dirk Zoller) will cross-fertilize each other. Of course, a significant
                   14398: part of the design of Gforth was prescribed by ANS Forth.
                   14399: 
1.20      pazsan   14400: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    14401: 32 bit native code version of VolksForth for the Atari ST, written
                   14402: mostly by Dietrich Weineck.
                   14403: 
                   14404: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
                   14405: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
                   14406: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
                   14407: 
                   14408: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   14409: Forth-83 standard. !! Pedigree? When?
                   14410: 
                   14411: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   14412: 1979. Robert Selzer and Bill Ragsdale developed the original
                   14413: implementation of fig-Forth for the 6502 based on microForth.
                   14414: 
                   14415: The principal architect of microForth was Dean Sanderson. microForth was
                   14416: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   14417: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   14418: Z80.
                   14419: 
                   14420: All earlier Forth systems were custom-made, usually by Charles Moore,
                   14421: who discovered (as he puts it) Forth during the late 60s. The first full
                   14422: Forth existed in 1971.
                   14423: 
                   14424: A part of the information in this section comes from @cite{The Evolution
                   14425: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
                   14426: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
                   14427: Notices 28(3), 1993.  You can find more historical and genealogical
                   14428: information about Forth there.
                   14429: 
1.21      crook    14430: @node Forth-related information, Word Index, Origin, Top
                   14431: @appendix Other Forth-related information
                   14432: @cindex Forth-related information
                   14433: 
                   14434: @menu
                   14435: * Internet resources::
                   14436: * Books::
                   14437: * The Forth Interest Group::
                   14438: * Conferences::
                   14439: @end menu
                   14440: 
                   14441: 
                   14442: @node Internet resources, Books, Forth-related information, Forth-related information
                   14443: @section Internet resources
1.26      crook    14444: @cindex internet resources
1.21      crook    14445: 
                   14446: @cindex comp.lang.forth
                   14447: @cindex frequently asked questions
1.45      crook    14448: There is an active news group (comp.lang.forth) discussing Forth and
1.21      crook    14449: Forth-related issues. A frequently-asked-questions (FAQ) list
1.45      crook    14450: is posted to the news group regularly, and archived at these sites:
1.21      crook    14451: 
                   14452: @itemize @bullet
                   14453: @item
1.47      crook    14454: @uref{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
1.21      crook    14455: @item
1.47      crook    14456: @uref{ftp://ftp.forth.org/pub/Forth/FAQ/}
1.21      crook    14457: @end itemize
                   14458: 
                   14459: The FAQ list should be considered mandatory reading before posting to
1.45      crook    14460: the news group.
1.21      crook    14461: 
                   14462: Here are some other web sites holding Forth-related material:
                   14463: 
                   14464: @itemize @bullet
                   14465: @item
1.47      crook    14466: @uref{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
1.21      crook    14467: @item
1.47      crook    14468: @uref{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
1.21      crook    14469: @item
1.47      crook    14470: @uref{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
1.21      crook    14471: @item
1.47      crook    14472: @uref{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
1.21      crook    14473: Research page, including links to the Journal of Forth Application and
                   14474: Research (JFAR) and a searchable Forth bibliography.
                   14475: @end itemize
                   14476: 
                   14477: 
                   14478: @node Books, The Forth Interest Group, Internet resources, Forth-related information
                   14479: @section Books
1.26      crook    14480: @cindex books on Forth
1.21      crook    14481: 
                   14482: As the Standard is relatively new, there are not many books out yet. It
                   14483: is not recommended to learn Forth by using Gforth and a book that is not
                   14484: written for ANS Forth, as you will not know your mistakes from the
                   14485: deviations of the book. However, books based on the Forth-83 standard
                   14486: should be ok, because ANS Forth is primarily an extension of Forth-83.
1.44      crook    14487: Refer to the Forth FAQ for details of Forth-related books.
1.21      crook    14488: 
                   14489: @cindex standard document for ANS Forth
                   14490: @cindex ANS Forth document
                   14491: The definite reference if you want to write ANS Forth programs is, of
1.26      crook    14492: course, the ANS Forth document. It is available in printed form from the
1.21      crook    14493: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
                   14494: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
                   14495: $200. You can also get it from Global Engineering Documents (Tel.: USA
                   14496: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
                   14497: 
                   14498: @cite{dpANS6}, the last draft of the standard, which was then submitted
                   14499: to ANSI for publication is available electronically and for free in some
                   14500: MS Word format, and it has been converted to HTML
1.47      crook    14501: (@uref{http://www.taygeta.com/forth/dpans.html}; this HTML version also
1.44      crook    14502: includes the answers to Requests for Interpretation (RFIs). Some
                   14503: pointers to these versions can be found through
1.47      crook    14504: @*@uref{http://www.complang.tuwien.ac.at/projects/forth.html}.
1.44      crook    14505: 
1.21      crook    14506: 
                   14507: @node The Forth Interest Group, Conferences, Books, Forth-related information
                   14508: @section The Forth Interest Group
                   14509: @cindex Forth interest group (FIG)
                   14510: 
                   14511: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26      crook    14512: member-supported organisation. It publishes a regular magazine,
                   14513: @var{FORTH Dimensions}, and offers other benefits of membership. You can
                   14514: contact the FIG through their office email address:
                   14515: @email{office@@forth.org} or by visiting their web site at
1.47      crook    14516: @uref{http://www.forth.org/}. This web site also includes links to FIG
1.26      crook    14517: chapters in other countries and American cities
1.47      crook    14518: (@uref{http://www.forth.org/chapters.html}).
1.21      crook    14519: 
1.48      anton    14520: @node Conferences,  , The Forth Interest Group, Forth-related information
1.21      crook    14521: @section Conferences
                   14522: @cindex Conferences
                   14523: 
                   14524: There are several regular conferences related to Forth. They are all
1.26      crook    14525: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
1.45      crook    14526: news group:
1.21      crook    14527: 
                   14528: @itemize @bullet
                   14529: @item
                   14530: FORML -- the Forth modification laboratory convenes every year near
                   14531: Monterey, California.
                   14532: @item
                   14533: The Rochester Forth Conference -- an annual conference traditionally
                   14534: held in Rochester, New York.
                   14535: @item
                   14536: EuroForth -- this European conference takes place annually.
                   14537: @end itemize
                   14538: 
                   14539: 
1.41      anton    14540: @node Word Index, Name Index, Forth-related information, Top
1.1       anton    14541: @unnumbered Word Index
                   14542: 
1.26      crook    14543: This index is a list of Forth words that have ``glossary'' entries
                   14544: within this manual. Each word is listed with its stack effect and
                   14545: wordset.
1.1       anton    14546: 
                   14547: @printindex fn
                   14548: 
1.41      anton    14549: @node Name Index, Concept Index, Word Index, Top
                   14550: @unnumbered Name Index
                   14551: 
                   14552: This index is a list of Forth words that have ``glossary'' entries
                   14553: within this manual.
                   14554: 
                   14555: @printindex ky
                   14556: 
                   14557: @node Concept Index,  , Name Index, Top
1.1       anton    14558: @unnumbered Concept and Word Index
                   14559: 
1.26      crook    14560: Not all entries listed in this index are present verbatim in the
                   14561: text. This index also duplicates, in abbreviated form, all of the words
                   14562: listed in the Word Index (only the names are listed for the words here).
1.1       anton    14563: 
                   14564: @printindex cp
                   14565: 
                   14566: @contents
                   14567: @bye
                   14568: 

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