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

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.78      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: 
1.67      anton     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::  
                    230: * Where to go next::            
                    231: * Exercises::                   
1.24      anton     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::                   
1.78      anton     252: * Locals::                      
                    253: * Structures::                  
                    254: * Object-oriented Forth::       
1.12      anton     255: * Programming Tools::           
                    256: * Assembler and Code Words::    
                    257: * Threading Words::             
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::            
1.67      anton     265: * Double precision::            Double-cell integer arithmetic
1.12      anton     266: * Bitwise operations::          
1.67      anton     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
1.67      anton     293: * Arbitrary control structures::  
                    294: * Calls and returns::           
1.12      anton     295: * Exception Handling::          
                    296: 
                    297: Defining Words
                    298: 
1.67      anton     299: * CREATE::                      
1.44      crook     300: * Variables::                   Variables and user variables
1.67      anton     301: * Constants::                   
1.44      crook     302: * Values::                      Initialised variables
1.67      anton     303: * Colon Definitions::           
1.44      crook     304: * Anonymous Definitions::       Definitions without names
1.71      anton     305: * Supplying names::             Passing definition names as strings
1.67      anton     306: * User-defined Defining Words::  
1.44      crook     307: * Deferred words::              Allow forward references
1.67      anton     308: * Aliases::                     
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.67      anton     318: * Combined words::              
1.12      anton     319: 
1.71      anton     320: Tokens for Words
                    321: 
                    322: * Execution token::             represents execution/interpretation semantics
                    323: * Compilation token::           represents compilation semantics
                    324: * Name token::                  represents named words
                    325: 
1.21      crook     326: The Text Interpreter
                    327: 
1.67      anton     328: * Input Sources::               
                    329: * Number Conversion::           
                    330: * Interpret/Compile states::    
                    331: * Literals::                    
                    332: * Interpreter Directives::      
1.21      crook     333: 
1.26      crook     334: Word Lists
                    335: 
1.75      anton     336: * Vocabularies::                
1.67      anton     337: * Why use word lists?::         
1.75      anton     338: * Word list example::           
1.26      crook     339: 
                    340: Files
                    341: 
1.48      anton     342: * Forth source files::          
                    343: * General files::               
                    344: * Search Paths::                
                    345: 
                    346: Search Paths
                    347: 
1.75      anton     348: * Source Search Paths::         
1.26      crook     349: * General Search Paths::        
                    350: 
                    351: Other I/O
                    352: 
1.32      anton     353: * Simple numeric output::       Predefined formats
                    354: * Formatted numeric output::    Formatted (pictured) output
                    355: * String Formats::              How Forth stores strings in memory
1.67      anton     356: * Displaying characters and strings::  Other stuff
1.32      anton     357: * Input::                       Input
1.26      crook     358: 
                    359: Locals
                    360: 
                    361: * Gforth locals::               
                    362: * ANS Forth locals::            
                    363: 
                    364: Gforth locals
                    365: 
                    366: * Where are locals visible by name?::  
                    367: * How long do locals live?::    
1.78      anton     368: * Locals programming style::    
                    369: * Locals implementation::       
1.26      crook     370: 
1.12      anton     371: Structures
                    372: 
                    373: * Why explicit structure support?::  
                    374: * Structure Usage::             
                    375: * Structure Naming Convention::  
                    376: * Structure Implementation::    
                    377: * Structure Glossary::          
                    378: 
                    379: Object-oriented Forth
                    380: 
1.48      anton     381: * Why object-oriented programming?::  
                    382: * Object-Oriented Terminology::  
                    383: * Objects::                     
                    384: * OOF::                         
                    385: * Mini-OOF::                    
1.23      crook     386: * Comparison with other object models::  
1.12      anton     387: 
1.24      anton     388: The @file{objects.fs} model
1.12      anton     389: 
                    390: * Properties of the Objects model::  
                    391: * Basic Objects Usage::         
1.41      anton     392: * The Objects base class::      
1.12      anton     393: * Creating objects::            
                    394: * Object-Oriented Programming Style::  
                    395: * Class Binding::               
                    396: * Method conveniences::         
                    397: * Classes and Scoping::         
1.41      anton     398: * Dividing classes::            
1.12      anton     399: * Object Interfaces::           
                    400: * Objects Implementation::      
                    401: * Objects Glossary::            
                    402: 
1.24      anton     403: The @file{oof.fs} model
1.12      anton     404: 
1.67      anton     405: * Properties of the OOF model::  
                    406: * Basic OOF Usage::             
                    407: * The OOF base class::          
                    408: * Class Declaration::           
                    409: * Class Implementation::        
1.12      anton     410: 
1.24      anton     411: The @file{mini-oof.fs} model
1.23      crook     412: 
1.48      anton     413: * Basic Mini-OOF Usage::        
                    414: * Mini-OOF Example::            
                    415: * Mini-OOF Implementation::     
1.23      crook     416: 
1.78      anton     417: Programming Tools
                    418: 
                    419: * Examining::                   
                    420: * Forgetting words::            
                    421: * Debugging::                   Simple and quick.
                    422: * Assertions::                  Making your programs self-checking.
                    423: * Singlestep Debugger::         Executing your program word by word.
                    424: 
                    425: Assembler and Code Words
                    426: 
                    427: * Code and ;code::              
                    428: * Common Assembler::            Assembler Syntax
                    429: * Common Disassembler::         
                    430: * 386 Assembler::               Deviations and special cases
                    431: * Alpha Assembler::             Deviations and special cases
                    432: * MIPS assembler::              Deviations and special cases
                    433: * Other assemblers::            How to write them
                    434: 
1.12      anton     435: Tools
                    436: 
                    437: * ANS Report::                  Report the words used, sorted by wordset.
                    438: 
                    439: ANS conformance
                    440: 
                    441: * The Core Words::              
                    442: * The optional Block word set::  
                    443: * The optional Double Number word set::  
                    444: * The optional Exception word set::  
                    445: * The optional Facility word set::  
                    446: * The optional File-Access word set::  
                    447: * The optional Floating-Point word set::  
                    448: * The optional Locals word set::  
                    449: * The optional Memory-Allocation word set::  
                    450: * The optional Programming-Tools word set::  
                    451: * The optional Search-Order word set::  
                    452: 
                    453: The Core Words
                    454: 
                    455: * core-idef::                   Implementation Defined Options                   
                    456: * core-ambcond::                Ambiguous Conditions                
                    457: * core-other::                  Other System Documentation                  
                    458: 
                    459: The optional Block word set
                    460: 
                    461: * block-idef::                  Implementation Defined Options
                    462: * block-ambcond::               Ambiguous Conditions               
                    463: * block-other::                 Other System Documentation                 
                    464: 
                    465: The optional Double Number word set
                    466: 
                    467: * double-ambcond::              Ambiguous Conditions              
                    468: 
                    469: The optional Exception word set
                    470: 
                    471: * exception-idef::              Implementation Defined Options              
                    472: 
                    473: The optional Facility word set
                    474: 
                    475: * facility-idef::               Implementation Defined Options               
                    476: * facility-ambcond::            Ambiguous Conditions            
                    477: 
                    478: The optional File-Access word set
                    479: 
                    480: * file-idef::                   Implementation Defined Options
                    481: * file-ambcond::                Ambiguous Conditions                
                    482: 
                    483: The optional Floating-Point word set
                    484: 
                    485: * floating-idef::               Implementation Defined Options
                    486: * floating-ambcond::            Ambiguous Conditions            
                    487: 
                    488: The optional Locals word set
                    489: 
                    490: * locals-idef::                 Implementation Defined Options                 
                    491: * locals-ambcond::              Ambiguous Conditions              
                    492: 
                    493: The optional Memory-Allocation word set
                    494: 
                    495: * memory-idef::                 Implementation Defined Options                 
                    496: 
                    497: The optional Programming-Tools word set
                    498: 
                    499: * programming-idef::            Implementation Defined Options            
                    500: * programming-ambcond::         Ambiguous Conditions         
                    501: 
                    502: The optional Search-Order word set
                    503: 
                    504: * search-idef::                 Implementation Defined Options                 
                    505: * search-ambcond::              Ambiguous Conditions              
                    506: 
                    507: Image Files
                    508: 
1.24      anton     509: * Image Licensing Issues::      Distribution terms for images.
                    510: * Image File Background::       Why have image files?
1.67      anton     511: * Non-Relocatable Image Files::  don't always work.
1.24      anton     512: * Data-Relocatable Image Files::  are better.
1.67      anton     513: * Fully Relocatable Image Files::  better yet.
1.24      anton     514: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     515: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     516: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     517: 
                    518: Fully Relocatable Image Files
                    519: 
1.27      crook     520: * gforthmi::                    The normal way
1.12      anton     521: * cross.fs::                    The hard way
                    522: 
                    523: Engine
                    524: 
                    525: * Portability::                 
                    526: * Threading::                   
                    527: * Primitives::                  
                    528: * Performance::                 
                    529: 
                    530: Threading
                    531: 
                    532: * Scheduling::                  
                    533: * Direct or Indirect Threaded?::  
                    534: * DOES>::                       
                    535: 
                    536: Primitives
                    537: 
                    538: * Automatic Generation::        
                    539: * TOS Optimization::            
                    540: * Produced code::               
1.13      pazsan    541: 
                    542: Cross Compiler
                    543: 
1.67      anton     544: * Using the Cross Compiler::    
                    545: * How the Cross Compiler Works::  
1.13      pazsan    546: 
1.24      anton     547: Other Forth-related information
1.21      crook     548: 
1.67      anton     549: * Internet resources::          
                    550: * Books::                       
                    551: * The Forth Interest Group::    
                    552: * Conferences::                 
1.21      crook     553: 
1.24      anton     554: @end detailmenu
1.1       anton     555: @end menu
                    556: 
1.26      crook     557: @node License, Goals, Top, Top
1.1       anton     558: @unnumbered GNU GENERAL PUBLIC LICENSE
                    559: @center Version 2, June 1991
                    560: 
                    561: @display
                    562: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
                    563: 675 Mass Ave, Cambridge, MA 02139, USA
                    564: 
                    565: Everyone is permitted to copy and distribute verbatim copies
                    566: of this license document, but changing it is not allowed.
                    567: @end display
                    568: 
                    569: @unnumberedsec Preamble
                    570: 
                    571:   The licenses for most software are designed to take away your
                    572: freedom to share and change it.  By contrast, the GNU General Public
                    573: License is intended to guarantee your freedom to share and change free
                    574: software---to make sure the software is free for all its users.  This
                    575: General Public License applies to most of the Free Software
                    576: Foundation's software and to any other program whose authors commit to
                    577: using it.  (Some other Free Software Foundation software is covered by
                    578: the GNU Library General Public License instead.)  You can apply it to
                    579: your programs, too.
                    580: 
                    581:   When we speak of free software, we are referring to freedom, not
                    582: price.  Our General Public Licenses are designed to make sure that you
                    583: have the freedom to distribute copies of free software (and charge for
                    584: this service if you wish), that you receive source code or can get it
                    585: if you want it, that you can change the software or use pieces of it
                    586: in new free programs; and that you know you can do these things.
                    587: 
                    588:   To protect your rights, we need to make restrictions that forbid
                    589: anyone to deny you these rights or to ask you to surrender the rights.
                    590: These restrictions translate to certain responsibilities for you if you
                    591: distribute copies of the software, or if you modify it.
                    592: 
                    593:   For example, if you distribute copies of such a program, whether
                    594: gratis or for a fee, you must give the recipients all the rights that
                    595: you have.  You must make sure that they, too, receive or can get the
                    596: source code.  And you must show them these terms so they know their
                    597: rights.
                    598: 
                    599:   We protect your rights with two steps: (1) copyright the software, and
                    600: (2) offer you this license which gives you legal permission to copy,
                    601: distribute and/or modify the software.
                    602: 
                    603:   Also, for each author's protection and ours, we want to make certain
                    604: that everyone understands that there is no warranty for this free
                    605: software.  If the software is modified by someone else and passed on, we
                    606: want its recipients to know that what they have is not the original, so
                    607: that any problems introduced by others will not reflect on the original
                    608: authors' reputations.
                    609: 
                    610:   Finally, any free program is threatened constantly by software
                    611: patents.  We wish to avoid the danger that redistributors of a free
                    612: program will individually obtain patent licenses, in effect making the
                    613: program proprietary.  To prevent this, we have made it clear that any
                    614: patent must be licensed for everyone's free use or not licensed at all.
                    615: 
                    616:   The precise terms and conditions for copying, distribution and
                    617: modification follow.
                    618: 
                    619: @iftex
                    620: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    621: @end iftex
1.49      anton     622: @ifnottex
1.1       anton     623: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
1.49      anton     624: @end ifnottex
1.1       anton     625: 
                    626: @enumerate 0
                    627: @item
                    628: This License applies to any program or other work which contains
                    629: a notice placed by the copyright holder saying it may be distributed
                    630: under the terms of this General Public License.  The ``Program'', below,
                    631: refers to any such program or work, and a ``work based on the Program''
                    632: means either the Program or any derivative work under copyright law:
                    633: that is to say, a work containing the Program or a portion of it,
                    634: either verbatim or with modifications and/or translated into another
                    635: language.  (Hereinafter, translation is included without limitation in
                    636: the term ``modification''.)  Each licensee is addressed as ``you''.
                    637: 
                    638: Activities other than copying, distribution and modification are not
                    639: covered by this License; they are outside its scope.  The act of
                    640: running the Program is not restricted, and the output from the Program
                    641: is covered only if its contents constitute a work based on the
                    642: Program (independent of having been made by running the Program).
                    643: Whether that is true depends on what the Program does.
                    644: 
                    645: @item
                    646: You may copy and distribute verbatim copies of the Program's
                    647: source code as you receive it, in any medium, provided that you
                    648: conspicuously and appropriately publish on each copy an appropriate
                    649: copyright notice and disclaimer of warranty; keep intact all the
                    650: notices that refer to this License and to the absence of any warranty;
                    651: and give any other recipients of the Program a copy of this License
                    652: along with the Program.
                    653: 
                    654: You may charge a fee for the physical act of transferring a copy, and
                    655: you may at your option offer warranty protection in exchange for a fee.
                    656: 
                    657: @item
                    658: You may modify your copy or copies of the Program or any portion
                    659: of it, thus forming a work based on the Program, and copy and
                    660: distribute such modifications or work under the terms of Section 1
                    661: above, provided that you also meet all of these conditions:
                    662: 
                    663: @enumerate a
                    664: @item
                    665: You must cause the modified files to carry prominent notices
                    666: stating that you changed the files and the date of any change.
                    667: 
                    668: @item
                    669: You must cause any work that you distribute or publish, that in
                    670: whole or in part contains or is derived from the Program or any
                    671: part thereof, to be licensed as a whole at no charge to all third
                    672: parties under the terms of this License.
                    673: 
                    674: @item
                    675: If the modified program normally reads commands interactively
                    676: when run, you must cause it, when started running for such
                    677: interactive use in the most ordinary way, to print or display an
                    678: announcement including an appropriate copyright notice and a
                    679: notice that there is no warranty (or else, saying that you provide
                    680: a warranty) and that users may redistribute the program under
                    681: these conditions, and telling the user how to view a copy of this
                    682: License.  (Exception: if the Program itself is interactive but
                    683: does not normally print such an announcement, your work based on
                    684: the Program is not required to print an announcement.)
                    685: @end enumerate
                    686: 
                    687: These requirements apply to the modified work as a whole.  If
                    688: identifiable sections of that work are not derived from the Program,
                    689: and can be reasonably considered independent and separate works in
                    690: themselves, then this License, and its terms, do not apply to those
                    691: sections when you distribute them as separate works.  But when you
                    692: distribute the same sections as part of a whole which is a work based
                    693: on the Program, the distribution of the whole must be on the terms of
                    694: this License, whose permissions for other licensees extend to the
                    695: entire whole, and thus to each and every part regardless of who wrote it.
                    696: 
                    697: Thus, it is not the intent of this section to claim rights or contest
                    698: your rights to work written entirely by you; rather, the intent is to
                    699: exercise the right to control the distribution of derivative or
                    700: collective works based on the Program.
                    701: 
                    702: In addition, mere aggregation of another work not based on the Program
                    703: with the Program (or with a work based on the Program) on a volume of
                    704: a storage or distribution medium does not bring the other work under
                    705: the scope of this License.
                    706: 
                    707: @item
                    708: You may copy and distribute the Program (or a work based on it,
                    709: under Section 2) in object code or executable form under the terms of
                    710: Sections 1 and 2 above provided that you also do one of the following:
                    711: 
                    712: @enumerate a
                    713: @item
                    714: Accompany it with the complete corresponding machine-readable
                    715: source code, which must be distributed under the terms of Sections
                    716: 1 and 2 above on a medium customarily used for software interchange; or,
                    717: 
                    718: @item
                    719: Accompany it with a written offer, valid for at least three
                    720: years, to give any third party, for a charge no more than your
                    721: cost of physically performing source distribution, a complete
                    722: machine-readable copy of the corresponding source code, to be
                    723: distributed under the terms of Sections 1 and 2 above on a medium
                    724: customarily used for software interchange; or,
                    725: 
                    726: @item
                    727: Accompany it with the information you received as to the offer
                    728: to distribute corresponding source code.  (This alternative is
                    729: allowed only for noncommercial distribution and only if you
                    730: received the program in object code or executable form with such
                    731: an offer, in accord with Subsection b above.)
                    732: @end enumerate
                    733: 
                    734: The source code for a work means the preferred form of the work for
                    735: making modifications to it.  For an executable work, complete source
                    736: code means all the source code for all modules it contains, plus any
                    737: associated interface definition files, plus the scripts used to
                    738: control compilation and installation of the executable.  However, as a
                    739: special exception, the source code distributed need not include
                    740: anything that is normally distributed (in either source or binary
                    741: form) with the major components (compiler, kernel, and so on) of the
                    742: operating system on which the executable runs, unless that component
                    743: itself accompanies the executable.
                    744: 
                    745: If distribution of executable or object code is made by offering
                    746: access to copy from a designated place, then offering equivalent
                    747: access to copy the source code from the same place counts as
                    748: distribution of the source code, even though third parties are not
                    749: compelled to copy the source along with the object code.
                    750: 
                    751: @item
                    752: You may not copy, modify, sublicense, or distribute the Program
                    753: except as expressly provided under this License.  Any attempt
                    754: otherwise to copy, modify, sublicense or distribute the Program is
                    755: void, and will automatically terminate your rights under this License.
                    756: However, parties who have received copies, or rights, from you under
                    757: this License will not have their licenses terminated so long as such
                    758: parties remain in full compliance.
                    759: 
                    760: @item
                    761: You are not required to accept this License, since you have not
                    762: signed it.  However, nothing else grants you permission to modify or
                    763: distribute the Program or its derivative works.  These actions are
                    764: prohibited by law if you do not accept this License.  Therefore, by
                    765: modifying or distributing the Program (or any work based on the
                    766: Program), you indicate your acceptance of this License to do so, and
                    767: all its terms and conditions for copying, distributing or modifying
                    768: the Program or works based on it.
                    769: 
                    770: @item
                    771: Each time you redistribute the Program (or any work based on the
                    772: Program), the recipient automatically receives a license from the
                    773: original licensor to copy, distribute or modify the Program subject to
                    774: these terms and conditions.  You may not impose any further
                    775: restrictions on the recipients' exercise of the rights granted herein.
                    776: You are not responsible for enforcing compliance by third parties to
                    777: this License.
                    778: 
                    779: @item
                    780: If, as a consequence of a court judgment or allegation of patent
                    781: infringement or for any other reason (not limited to patent issues),
                    782: conditions are imposed on you (whether by court order, agreement or
                    783: otherwise) that contradict the conditions of this License, they do not
                    784: excuse you from the conditions of this License.  If you cannot
                    785: distribute so as to satisfy simultaneously your obligations under this
                    786: License and any other pertinent obligations, then as a consequence you
                    787: may not distribute the Program at all.  For example, if a patent
                    788: license would not permit royalty-free redistribution of the Program by
                    789: all those who receive copies directly or indirectly through you, then
                    790: the only way you could satisfy both it and this License would be to
                    791: refrain entirely from distribution of the Program.
                    792: 
                    793: If any portion of this section is held invalid or unenforceable under
                    794: any particular circumstance, the balance of the section is intended to
                    795: apply and the section as a whole is intended to apply in other
                    796: circumstances.
                    797: 
                    798: It is not the purpose of this section to induce you to infringe any
                    799: patents or other property right claims or to contest validity of any
                    800: such claims; this section has the sole purpose of protecting the
                    801: integrity of the free software distribution system, which is
                    802: implemented by public license practices.  Many people have made
                    803: generous contributions to the wide range of software distributed
                    804: through that system in reliance on consistent application of that
                    805: system; it is up to the author/donor to decide if he or she is willing
                    806: to distribute software through any other system and a licensee cannot
                    807: impose that choice.
                    808: 
                    809: This section is intended to make thoroughly clear what is believed to
                    810: be a consequence of the rest of this License.
                    811: 
                    812: @item
                    813: If the distribution and/or use of the Program is restricted in
                    814: certain countries either by patents or by copyrighted interfaces, the
                    815: original copyright holder who places the Program under this License
                    816: may add an explicit geographical distribution limitation excluding
                    817: those countries, so that distribution is permitted only in or among
                    818: countries not thus excluded.  In such case, this License incorporates
                    819: the limitation as if written in the body of this License.
                    820: 
                    821: @item
                    822: The Free Software Foundation may publish revised and/or new versions
                    823: of the General Public License from time to time.  Such new versions will
                    824: be similar in spirit to the present version, but may differ in detail to
                    825: address new problems or concerns.
                    826: 
                    827: Each version is given a distinguishing version number.  If the Program
                    828: specifies a version number of this License which applies to it and ``any
                    829: later version'', you have the option of following the terms and conditions
                    830: either of that version or of any later version published by the Free
                    831: Software Foundation.  If the Program does not specify a version number of
                    832: this License, you may choose any version ever published by the Free Software
                    833: Foundation.
                    834: 
                    835: @item
                    836: If you wish to incorporate parts of the Program into other free
                    837: programs whose distribution conditions are different, write to the author
                    838: to ask for permission.  For software which is copyrighted by the Free
                    839: Software Foundation, write to the Free Software Foundation; we sometimes
                    840: make exceptions for this.  Our decision will be guided by the two goals
                    841: of preserving the free status of all derivatives of our free software and
                    842: of promoting the sharing and reuse of software generally.
                    843: 
                    844: @iftex
                    845: @heading NO WARRANTY
                    846: @end iftex
1.49      anton     847: @ifnottex
1.1       anton     848: @center NO WARRANTY
1.49      anton     849: @end ifnottex
1.1       anton     850: 
                    851: @item
                    852: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
                    853: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
                    854: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
                    855: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
                    856: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
                    857: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
                    858: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
                    859: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
                    860: REPAIR OR CORRECTION.
                    861: 
                    862: @item
                    863: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                    864: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
                    865: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
                    866: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
                    867: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
                    868: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
                    869: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
                    870: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
                    871: POSSIBILITY OF SUCH DAMAGES.
                    872: @end enumerate
                    873: 
                    874: @iftex
                    875: @heading END OF TERMS AND CONDITIONS
                    876: @end iftex
1.49      anton     877: @ifnottex
1.1       anton     878: @center END OF TERMS AND CONDITIONS
1.49      anton     879: @end ifnottex
1.1       anton     880: 
                    881: @page
                    882: @unnumberedsec How to Apply These Terms to Your New Programs
                    883: 
                    884:   If you develop a new program, and you want it to be of the greatest
                    885: possible use to the public, the best way to achieve this is to make it
                    886: free software which everyone can redistribute and change under these terms.
                    887: 
                    888:   To do so, attach the following notices to the program.  It is safest
                    889: to attach them to the start of each source file to most effectively
                    890: convey the exclusion of warranty; and each file should have at least
                    891: the ``copyright'' line and a pointer to where the full notice is found.
                    892: 
                    893: @smallexample
                    894: @var{one line to give the program's name and a brief idea of what it does.}
                    895: Copyright (C) 19@var{yy}  @var{name of author}
                    896: 
                    897: This program is free software; you can redistribute it and/or modify 
                    898: it under the terms of the GNU General Public License as published by 
                    899: the Free Software Foundation; either version 2 of the License, or 
                    900: (at your option) any later version.
                    901: 
                    902: This program is distributed in the hope that it will be useful,
                    903: but WITHOUT ANY WARRANTY; without even the implied warranty of
                    904: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    905: GNU General Public License for more details.
                    906: 
                    907: You should have received a copy of the GNU General Public License
                    908: along with this program; if not, write to the Free Software
                    909: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
                    910: @end smallexample
                    911: 
                    912: Also add information on how to contact you by electronic and paper mail.
                    913: 
                    914: If the program is interactive, make it output a short notice like this
                    915: when it starts in an interactive mode:
                    916: 
                    917: @smallexample
                    918: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
                    919: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
                    920: type `show w'.  
                    921: This is free software, and you are welcome to redistribute it 
                    922: under certain conditions; type `show c' for details.
                    923: @end smallexample
                    924: 
                    925: The hypothetical commands @samp{show w} and @samp{show c} should show
                    926: the appropriate parts of the General Public License.  Of course, the
                    927: commands you use may be called something other than @samp{show w} and
                    928: @samp{show c}; they could even be mouse-clicks or menu items---whatever
                    929: suits your program.
                    930: 
                    931: You should also get your employer (if you work as a programmer) or your
                    932: school, if any, to sign a ``copyright disclaimer'' for the program, if
                    933: necessary.  Here is a sample; alter the names:
                    934: 
                    935: @smallexample
                    936: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
                    937: `Gnomovision' (which makes passes at compilers) written by James Hacker.
                    938: 
                    939: @var{signature of Ty Coon}, 1 April 1989
                    940: Ty Coon, President of Vice
                    941: @end smallexample
                    942: 
                    943: This General Public License does not permit incorporating your program into
                    944: proprietary programs.  If your program is a subroutine library, you may
                    945: consider it more useful to permit linking proprietary applications with the
                    946: library.  If this is what you want to do, use the GNU Library General
                    947: Public License instead of this License.
                    948: 
                    949: @iftex
                    950: @unnumbered Preface
                    951: @cindex Preface
1.21      crook     952: This manual documents Gforth. Some introductory material is provided for
                    953: readers who are unfamiliar with Forth or who are migrating to Gforth
                    954: from other Forth compilers. However, this manual is primarily a
                    955: reference manual.
1.1       anton     956: @end iftex
                    957: 
1.28      crook     958: @comment TODO much more blurb here.
1.26      crook     959: 
                    960: @c ******************************************************************
1.29      crook     961: @node Goals, Gforth Environment, License, Top
1.26      crook     962: @comment node-name,     next,           previous, up
                    963: @chapter Goals of Gforth
                    964: @cindex goals of the Gforth project
                    965: The goal of the Gforth Project is to develop a standard model for
                    966: ANS Forth. This can be split into several subgoals:
                    967: 
                    968: @itemize @bullet
                    969: @item
                    970: Gforth should conform to the ANS Forth Standard.
                    971: @item
                    972: It should be a model, i.e. it should define all the
                    973: implementation-dependent things.
                    974: @item
                    975: It should become standard, i.e. widely accepted and used. This goal
                    976: is the most difficult one.
                    977: @end itemize
                    978: 
                    979: To achieve these goals Gforth should be
                    980: @itemize @bullet
                    981: @item
                    982: Similar to previous models (fig-Forth, F83)
                    983: @item
                    984: Powerful. It should provide for all the things that are considered
                    985: necessary today and even some that are not yet considered necessary.
                    986: @item
                    987: Efficient. It should not get the reputation of being exceptionally
                    988: slow.
                    989: @item
                    990: Free.
                    991: @item
                    992: Available on many machines/easy to port.
                    993: @end itemize
                    994: 
                    995: Have we achieved these goals? Gforth conforms to the ANS Forth
                    996: standard. It may be considered a model, but we have not yet documented
                    997: which parts of the model are stable and which parts we are likely to
                    998: change. It certainly has not yet become a de facto standard, but it
                    999: appears to be quite popular. It has some similarities to and some
                   1000: differences from previous models. It has some powerful features, but not
                   1001: yet everything that we envisioned. We certainly have achieved our
1.65      anton    1002: execution speed goals (@pxref{Performance})@footnote{However, in 1998
                   1003: the bar was raised when the major commercial Forth vendors switched to
                   1004: native code compilers.}.  It is free and available on many machines.
1.29      crook    1005: 
1.26      crook    1006: @c ******************************************************************
1.48      anton    1007: @node Gforth Environment, Tutorial, Goals, Top
1.29      crook    1008: @chapter Gforth Environment
                   1009: @cindex Gforth environment
1.21      crook    1010: 
1.45      crook    1011: Note: ultimately, the Gforth man page will be auto-generated from the
1.29      crook    1012: material in this chapter.
1.21      crook    1013: 
                   1014: @menu
1.29      crook    1015: * Invoking Gforth::             Getting in
                   1016: * Leaving Gforth::              Getting out
                   1017: * Command-line editing::        
1.48      anton    1018: * Environment variables::       that affect how Gforth starts up
1.29      crook    1019: * Gforth Files::                What gets installed and where
1.48      anton    1020: * Startup speed::               When 35ms is not fast enough ...
1.21      crook    1021: @end menu
                   1022: 
1.49      anton    1023: For related information about the creation of images see @ref{Image Files}.
1.29      crook    1024: 
1.21      crook    1025: @comment ----------------------------------------------
1.48      anton    1026: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29      crook    1027: @section Invoking Gforth
                   1028: @cindex invoking Gforth
                   1029: @cindex running Gforth
                   1030: @cindex command-line options
                   1031: @cindex options on the command line
                   1032: @cindex flags on the command line
1.21      crook    1033: 
1.30      anton    1034: Gforth is made up of two parts; an executable ``engine'' (named
                   1035: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
                   1036: will usually just say @code{gforth} -- this automatically loads the
                   1037: default image file @file{gforth.fi}. In many other cases the default
                   1038: Gforth image will be invoked like this:
1.21      crook    1039: @example
1.30      anton    1040: gforth [file | -e forth-code] ...
1.21      crook    1041: @end example
1.29      crook    1042: @noindent
                   1043: This interprets the contents of the files and the Forth code in the order they
                   1044: are given.
1.21      crook    1045: 
1.30      anton    1046: In addition to the @file{gforth} engine, there is also an engine called
                   1047: @file{gforth-fast}, which is faster, but gives less informative error
                   1048: messages (@pxref{Error messages}).
                   1049: 
1.29      crook    1050: In general, the command line looks like this:
1.21      crook    1051: 
                   1052: @example
1.30      anton    1053: gforth[-fast] [engine options] [image options]
1.21      crook    1054: @end example
                   1055: 
1.30      anton    1056: The engine options must come before the rest of the command
1.29      crook    1057: line. They are:
1.26      crook    1058: 
1.29      crook    1059: @table @code
                   1060: @cindex -i, command-line option
                   1061: @cindex --image-file, command-line option
                   1062: @item --image-file @i{file}
                   1063: @itemx -i @i{file}
                   1064: Loads the Forth image @i{file} instead of the default
                   1065: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook    1066: 
1.39      anton    1067: @cindex --appl-image, command-line option
                   1068: @item --appl-image @i{file}
                   1069: Loads the image @i{file} and leaves all further command-line arguments
1.65      anton    1070: to the image (instead of processing them as engine options).  This is
                   1071: useful for building executable application images on Unix, built with
1.39      anton    1072: @code{gforthmi --application ...}.
                   1073: 
1.29      crook    1074: @cindex --path, command-line option
                   1075: @cindex -p, command-line option
                   1076: @item --path @i{path}
                   1077: @itemx -p @i{path}
                   1078: Uses @i{path} for searching the image file and Forth source code files
                   1079: instead of the default in the environment variable @code{GFORTHPATH} or
                   1080: the path specified at installation time (e.g.,
                   1081: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                   1082: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook    1083: 
1.29      crook    1084: @cindex --dictionary-size, command-line option
                   1085: @cindex -m, command-line option
                   1086: @cindex @i{size} parameters for command-line options
                   1087: @cindex size of the dictionary and the stacks
                   1088: @item --dictionary-size @i{size}
                   1089: @itemx -m @i{size}
                   1090: Allocate @i{size} space for the Forth dictionary space instead of
                   1091: using the default specified in the image (typically 256K). The
                   1092: @i{size} specification for this and subsequent options consists of
                   1093: an integer and a unit (e.g.,
                   1094: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                   1095: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                   1096: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                   1097: @code{e} is used.
1.21      crook    1098: 
1.29      crook    1099: @cindex --data-stack-size, command-line option
                   1100: @cindex -d, command-line option
                   1101: @item --data-stack-size @i{size}
                   1102: @itemx -d @i{size}
                   1103: Allocate @i{size} space for the data stack instead of using the
                   1104: default specified in the image (typically 16K).
1.21      crook    1105: 
1.29      crook    1106: @cindex --return-stack-size, command-line option
                   1107: @cindex -r, command-line option
                   1108: @item --return-stack-size @i{size}
                   1109: @itemx -r @i{size}
                   1110: Allocate @i{size} space for the return stack instead of using the
                   1111: default specified in the image (typically 15K).
1.21      crook    1112: 
1.29      crook    1113: @cindex --fp-stack-size, command-line option
                   1114: @cindex -f, command-line option
                   1115: @item --fp-stack-size @i{size}
                   1116: @itemx -f @i{size}
                   1117: Allocate @i{size} space for the floating point stack instead of
                   1118: using the default specified in the image (typically 15.5K). In this case
                   1119: the unit specifier @code{e} refers to floating point numbers.
1.21      crook    1120: 
1.48      anton    1121: @cindex --locals-stack-size, command-line option
                   1122: @cindex -l, command-line option
                   1123: @item --locals-stack-size @i{size}
                   1124: @itemx -l @i{size}
                   1125: Allocate @i{size} space for the locals stack instead of using the
                   1126: default specified in the image (typically 14.5K).
                   1127: 
                   1128: @cindex -h, command-line option
                   1129: @cindex --help, command-line option
                   1130: @item --help
                   1131: @itemx -h
                   1132: Print a message about the command-line options
                   1133: 
                   1134: @cindex -v, command-line option
                   1135: @cindex --version, command-line option
                   1136: @item --version
                   1137: @itemx -v
                   1138: Print version and exit
                   1139: 
                   1140: @cindex --debug, command-line option
                   1141: @item --debug
                   1142: Print some information useful for debugging on startup.
                   1143: 
                   1144: @cindex --offset-image, command-line option
                   1145: @item --offset-image
                   1146: Start the dictionary at a slightly different position than would be used
                   1147: otherwise (useful for creating data-relocatable images,
                   1148: @pxref{Data-Relocatable Image Files}).
                   1149: 
                   1150: @cindex --no-offset-im, command-line option
                   1151: @item --no-offset-im
                   1152: Start the dictionary at the normal position.
                   1153: 
                   1154: @cindex --clear-dictionary, command-line option
                   1155: @item --clear-dictionary
                   1156: Initialize all bytes in the dictionary to 0 before loading the image
                   1157: (@pxref{Data-Relocatable Image Files}).
                   1158: 
                   1159: @cindex --die-on-signal, command-line-option
                   1160: @item --die-on-signal
                   1161: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                   1162: or the segmentation violation SIGSEGV) by translating it into a Forth
                   1163: @code{THROW}. With this option, Gforth exits if it receives such a
                   1164: signal. This option is useful when the engine and/or the image might be
                   1165: severely broken (such that it causes another signal before recovering
                   1166: from the first); this option avoids endless loops in such cases.
                   1167: @end table
                   1168: 
                   1169: @cindex loading files at startup
                   1170: @cindex executing code on startup
                   1171: @cindex batch processing with Gforth
                   1172: As explained above, the image-specific command-line arguments for the
                   1173: default image @file{gforth.fi} consist of a sequence of filenames and
                   1174: @code{-e @var{forth-code}} options that are interpreted in the sequence
                   1175: in which they are given. The @code{-e @var{forth-code}} or
                   1176: @code{--evaluate @var{forth-code}} option evaluates the Forth
                   1177: code. This option takes only one argument; if you want to evaluate more
                   1178: Forth words, you have to quote them or use @code{-e} several times. To exit
                   1179: after processing the command line (instead of entering interactive mode)
                   1180: append @code{-e bye} to the command line.
                   1181: 
                   1182: @cindex versions, invoking other versions of Gforth
                   1183: If you have several versions of Gforth installed, @code{gforth} will
                   1184: invoke the version that was installed last. @code{gforth-@i{version}}
                   1185: invokes a specific version. If your environment contains the variable
                   1186: @code{GFORTHPATH}, you may want to override it by using the
                   1187: @code{--path} option.
                   1188: 
                   1189: Not yet implemented:
                   1190: On startup the system first executes the system initialization file
                   1191: (unless the option @code{--no-init-file} is given; note that the system
                   1192: resulting from using this option may not be ANS Forth conformant). Then
                   1193: the user initialization file @file{.gforth.fs} is executed, unless the
1.62      crook    1194: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48      anton    1195: then in @file{~}, then in the normal path (see above).
                   1196: 
                   1197: 
                   1198: 
                   1199: @comment ----------------------------------------------
                   1200: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                   1201: @section Leaving Gforth
                   1202: @cindex Gforth - leaving
                   1203: @cindex leaving Gforth
                   1204: 
                   1205: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                   1206: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                   1207: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49      anton    1208: data are discarded.  For ways of saving the state of the system before
                   1209: leaving Gforth see @ref{Image Files}.
1.48      anton    1210: 
                   1211: doc-bye
                   1212: 
                   1213: 
                   1214: @comment ----------------------------------------------
1.65      anton    1215: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48      anton    1216: @section Command-line editing
                   1217: @cindex command-line editing
                   1218: 
                   1219: Gforth maintains a history file that records every line that you type to
                   1220: the text interpreter. This file is preserved between sessions, and is
                   1221: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
                   1222: repeatedly you can recall successively older commands from this (or
                   1223: previous) session(s). The full list of command-line editing facilities is:
                   1224: 
                   1225: @itemize @bullet
                   1226: @item
                   1227: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
                   1228: commands from the history buffer.
                   1229: @item
                   1230: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
                   1231: from the history buffer.
                   1232: @item
                   1233: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
                   1234: @item
                   1235: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
                   1236: @item
                   1237: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
                   1238: closing up the line.
                   1239: @item
                   1240: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
                   1241: @item
                   1242: @kbd{Ctrl-a} to move the cursor to the start of the line.
                   1243: @item
                   1244: @kbd{Ctrl-e} to move the cursor to the end of the line.
                   1245: @item
                   1246: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
                   1247: line.
                   1248: @item
                   1249: @key{TAB} to step through all possible full-word completions of the word
                   1250: currently being typed.
                   1251: @item
1.65      anton    1252: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
                   1253: using @code{bye}). 
                   1254: @item
                   1255: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
                   1256: character under the cursor.
1.48      anton    1257: @end itemize
                   1258: 
                   1259: When editing, displayable characters are inserted to the left of the
                   1260: cursor position; the line is always in ``insert'' (as opposed to
                   1261: ``overstrike'') mode.
                   1262: 
                   1263: @cindex history file
                   1264: @cindex @file{.gforth-history}
                   1265: On Unix systems, the history file is @file{~/.gforth-history} by
                   1266: default@footnote{i.e. it is stored in the user's home directory.}. You
                   1267: can find out the name and location of your history file using:
                   1268: 
                   1269: @example 
                   1270: history-file type \ Unix-class systems
                   1271: 
                   1272: history-file type \ Other systems
                   1273: history-dir  type
                   1274: @end example
                   1275: 
                   1276: If you enter long definitions by hand, you can use a text editor to
                   1277: paste them out of the history file into a Forth source file for reuse at
                   1278: a later time.
                   1279: 
                   1280: Gforth never trims the size of the history file, so you should do this
                   1281: periodically, if necessary.
                   1282: 
                   1283: @comment this is all defined in history.fs
                   1284: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
                   1285: @comment chosen?
                   1286: 
                   1287: 
                   1288: @comment ----------------------------------------------
1.65      anton    1289: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48      anton    1290: @section Environment variables
                   1291: @cindex environment variables
                   1292: 
                   1293: Gforth uses these environment variables:
                   1294: 
                   1295: @itemize @bullet
                   1296: @item
                   1297: @cindex @code{GFORTHHIST} -- environment variable
                   1298: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
                   1299: open/create the history file, @file{.gforth-history}. Default:
                   1300: @code{$HOME}.
                   1301: 
                   1302: @item
                   1303: @cindex @code{GFORTHPATH} -- environment variable
                   1304: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
                   1305: for Forth source-code files.
                   1306: 
                   1307: @item
                   1308: @cindex @code{GFORTH} -- environment variable
1.49      anton    1309: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1310: 
                   1311: @item
                   1312: @cindex @code{GFORTHD} -- environment variable
1.62      crook    1313: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1314: 
                   1315: @item
                   1316: @cindex @code{TMP}, @code{TEMP} - environment variable
                   1317: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
                   1318: location for the history file.
                   1319: @end itemize
                   1320: 
                   1321: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1322: @comment mentioning these.
                   1323: 
                   1324: All the Gforth environment variables default to sensible values if they
                   1325: are not set.
                   1326: 
                   1327: 
                   1328: @comment ----------------------------------------------
                   1329: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
                   1330: @section Gforth files
                   1331: @cindex Gforth files
                   1332: 
                   1333: When you install Gforth on a Unix system, it installs files in these
                   1334: locations by default:
                   1335: 
                   1336: @itemize @bullet
                   1337: @item
                   1338: @file{/usr/local/bin/gforth}
                   1339: @item
                   1340: @file{/usr/local/bin/gforthmi}
                   1341: @item
                   1342: @file{/usr/local/man/man1/gforth.1} - man page.
                   1343: @item
                   1344: @file{/usr/local/info} - the Info version of this manual.
                   1345: @item
                   1346: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
                   1347: @item
                   1348: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
                   1349: @item
                   1350: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
                   1351: @item
                   1352: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
                   1353: @end itemize
                   1354: 
                   1355: You can select different places for installation by using
                   1356: @code{configure} options (listed with @code{configure --help}).
                   1357: 
                   1358: @comment ----------------------------------------------
                   1359: @node Startup speed,  , Gforth Files, Gforth Environment
                   1360: @section Startup speed
                   1361: @cindex Startup speed
                   1362: @cindex speed, startup
                   1363: 
                   1364: If Gforth is used for CGI scripts or in shell scripts, its startup
                   1365: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
                   1366: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
                   1367: system time.
                   1368: 
                   1369: If startup speed is a problem, you may consider the following ways to
                   1370: improve it; or you may consider ways to reduce the number of startups
1.62      crook    1371: (for example, by using Fast-CGI).
1.48      anton    1372: 
                   1373: The first step to improve startup speed is to statically link Gforth, by
                   1374: building it with @code{XLDFLAGS=-static}.  This requires more memory for
                   1375: the code and will therefore slow down the first invocation, but
                   1376: subsequent invocations avoid the dynamic linking overhead.  Another
                   1377: disadvantage is that Gforth won't profit from library upgrades.  As a
                   1378: result, @code{gforth-static -e bye} takes about 17.1ms user and
                   1379: 8.2ms system time.
                   1380: 
                   1381: The next step to improve startup speed is to use a non-relocatable image
1.65      anton    1382: (@pxref{Non-Relocatable Image Files}).  You can create this image with
1.48      anton    1383: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
                   1384: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
                   1385: and a part of the copy-on-write overhead.  The disadvantage is that the
1.62      crook    1386: non-relocatable image does not work if the OS gives Gforth a different
1.48      anton    1387: address for the dictionary, for whatever reason; so you better provide a
                   1388: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
                   1389: bye} takes about 15.3ms user and 7.5ms system time.
                   1390: 
                   1391: The final step is to disable dictionary hashing in Gforth.  Gforth
                   1392: builds the hash table on startup, which takes much of the startup
                   1393: overhead. You can do this by commenting out the @code{include hash.fs}
                   1394: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
                   1395: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
                   1396: The disadvantages are that functionality like @code{table} and
                   1397: @code{ekey} is missing and that text interpretation (e.g., compiling)
                   1398: now takes much longer. So, you should only use this method if there is
                   1399: no significant text interpretation to perform (the script should be
1.62      crook    1400: compiled into the image, amongst other things).  @code{gforth-static -i
1.48      anton    1401: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
                   1402: 
                   1403: @c ******************************************************************
                   1404: @node Tutorial, Introduction, Gforth Environment, Top
                   1405: @chapter Forth Tutorial
                   1406: @cindex Tutorial
                   1407: @cindex Forth Tutorial
                   1408: 
1.67      anton    1409: @c Topics from nac's Introduction that could be mentioned:
                   1410: @c press <ret> after each line
                   1411: @c Prompt
                   1412: @c numbers vs. words in dictionary on text interpretation
                   1413: @c what happens on redefinition
                   1414: @c parsing words (in particular, defining words)
                   1415: 
1.62      crook    1416: This tutorial can be used with any ANS-compliant Forth; any
                   1417: Gforth-specific features are marked as such and you can skip them if you
                   1418: work with another Forth.  This tutorial does not explain all features of
                   1419: Forth, just enough to get you started and give you some ideas about the
                   1420: facilities available in Forth.  Read the rest of the manual and the
                   1421: standard when you are through this.
1.48      anton    1422: 
                   1423: The intended way to use this tutorial is that you work through it while
                   1424: sitting in front of the console, take a look at the examples and predict
                   1425: what they will do, then try them out; if the outcome is not as expected,
                   1426: find out why (e.g., by trying out variations of the example), so you
                   1427: understand what's going on.  There are also some assignments that you
                   1428: should solve.
                   1429: 
                   1430: This tutorial assumes that you have programmed before and know what,
                   1431: e.g., a loop is.
                   1432: 
                   1433: @c !! explain compat library
                   1434: 
                   1435: @menu
                   1436: * Starting Gforth Tutorial::    
                   1437: * Syntax Tutorial::             
                   1438: * Crash Course Tutorial::       
                   1439: * Stack Tutorial::              
                   1440: * Arithmetics Tutorial::        
                   1441: * Stack Manipulation Tutorial::  
                   1442: * Using files for Forth code Tutorial::  
                   1443: * Comments Tutorial::           
                   1444: * Colon Definitions Tutorial::  
                   1445: * Decompilation Tutorial::      
                   1446: * Stack-Effect Comments Tutorial::  
                   1447: * Types Tutorial::              
                   1448: * Factoring Tutorial::          
                   1449: * Designing the stack effect Tutorial::  
                   1450: * Local Variables Tutorial::    
                   1451: * Conditional execution Tutorial::  
                   1452: * Flags and Comparisons Tutorial::  
                   1453: * General Loops Tutorial::      
                   1454: * Counted loops Tutorial::      
                   1455: * Recursion Tutorial::          
                   1456: * Leaving definitions or loops Tutorial::  
                   1457: * Return Stack Tutorial::       
                   1458: * Memory Tutorial::             
                   1459: * Characters and Strings Tutorial::  
                   1460: * Alignment Tutorial::          
                   1461: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1462: * Execution Tokens Tutorial::   
                   1463: * Exceptions Tutorial::         
                   1464: * Defining Words Tutorial::     
                   1465: * Arrays and Records Tutorial::  
                   1466: * POSTPONE Tutorial::           
                   1467: * Literal Tutorial::            
                   1468: * Advanced macros Tutorial::    
                   1469: * Compilation Tokens Tutorial::  
                   1470: * Wordlists and Search Order Tutorial::  
                   1471: @end menu
                   1472: 
                   1473: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1474: @section Starting Gforth
1.66      anton    1475: @cindex starting Gforth tutorial
1.48      anton    1476: You can start Gforth by typing its name:
                   1477: 
                   1478: @example
                   1479: gforth
                   1480: @end example
                   1481: 
                   1482: That puts you into interactive mode; you can leave Gforth by typing
                   1483: @code{bye}.  While in Gforth, you can edit the command line and access
                   1484: the command line history with cursor keys, similar to bash.
                   1485: 
                   1486: 
                   1487: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1488: @section Syntax
1.66      anton    1489: @cindex syntax tutorial
1.48      anton    1490: 
                   1491: A @dfn{word} is a sequence of arbitrary characters (expcept white
                   1492: space).  Words are separated by white space.  E.g., each of the
                   1493: following lines contains exactly one word:
                   1494: 
                   1495: @example
                   1496: word
                   1497: !@@#$%^&*()
                   1498: 1234567890
                   1499: 5!a
                   1500: @end example
                   1501: 
                   1502: A frequent beginner's error is to leave away necessary white space,
                   1503: resulting in an error like @samp{Undefined word}; so if you see such an
                   1504: error, check if you have put spaces wherever necessary.
                   1505: 
                   1506: @example
                   1507: ." hello, world" \ correct
                   1508: ."hello, world"  \ gives an "Undefined word" error
                   1509: @end example
                   1510: 
1.65      anton    1511: Gforth and most other Forth systems ignore differences in case (they are
1.48      anton    1512: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1513: your system is case-sensitive, you may have to type all the examples
                   1514: given here in upper case.
                   1515: 
                   1516: 
                   1517: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1518: @section Crash Course
                   1519: 
                   1520: Type
                   1521: 
                   1522: @example
                   1523: 0 0 !
                   1524: here execute
                   1525: ' catch >body 20 erase abort
                   1526: ' (quit) >body 20 erase
                   1527: @end example
                   1528: 
                   1529: The last two examples are guaranteed to destroy parts of Gforth (and
                   1530: most other systems), so you better leave Gforth afterwards (if it has
                   1531: not finished by itself).  On some systems you may have to kill gforth
                   1532: from outside (e.g., in Unix with @code{kill}).
                   1533: 
                   1534: Now that you know how to produce crashes (and that there's not much to
                   1535: them), let's learn how to produce meaningful programs.
                   1536: 
                   1537: 
                   1538: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1539: @section Stack
1.66      anton    1540: @cindex stack tutorial
1.48      anton    1541: 
                   1542: The most obvious feature of Forth is the stack.  When you type in a
                   1543: number, it is pushed on the stack.  You can display the content of the
                   1544: stack with @code{.s}.
                   1545: 
                   1546: @example
                   1547: 1 2 .s
                   1548: 3 .s
                   1549: @end example
                   1550: 
                   1551: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1552: appear in @code{.s} output as they appeared in the input.
                   1553: 
                   1554: You can print the top of stack element with @code{.}.
                   1555: 
                   1556: @example
                   1557: 1 2 3 . . .
                   1558: @end example
                   1559: 
                   1560: In general, words consume their stack arguments (@code{.s} is an
                   1561: exception).
                   1562: 
                   1563: @assignment
                   1564: What does the stack contain after @code{5 6 7 .}?
                   1565: @endassignment
                   1566: 
                   1567: 
                   1568: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1569: @section Arithmetics
1.66      anton    1570: @cindex arithmetics tutorial
1.48      anton    1571: 
                   1572: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1573: operate on the top two stack items:
                   1574: 
                   1575: @example
1.67      anton    1576: 2 2 .s
                   1577: + .s
                   1578: .
1.48      anton    1579: 2 1 - .
                   1580: 7 3 mod .
                   1581: @end example
                   1582: 
                   1583: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1584: as in the corresponding infix expression (this is generally the case in
                   1585: Forth).
                   1586: 
                   1587: Parentheses are superfluous (and not available), because the order of
                   1588: the words unambiguously determines the order of evaluation and the
                   1589: operands:
                   1590: 
                   1591: @example
                   1592: 3 4 + 5 * .
                   1593: 3 4 5 * + .
                   1594: @end example
                   1595: 
                   1596: @assignment
                   1597: What are the infix expressions corresponding to the Forth code above?
                   1598: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1599: known as Postfix or RPN (Reverse Polish Notation).}.
                   1600: @endassignment
                   1601: 
                   1602: To change the sign, use @code{negate}:
                   1603: 
                   1604: @example
                   1605: 2 negate .
                   1606: @end example
                   1607: 
                   1608: @assignment
                   1609: Convert -(-3)*4-5 to Forth.
                   1610: @endassignment
                   1611: 
                   1612: @code{/mod} performs both @code{/} and @code{mod}.
                   1613: 
                   1614: @example
                   1615: 7 3 /mod . .
                   1616: @end example
                   1617: 
1.66      anton    1618: Reference: @ref{Arithmetic}.
                   1619: 
                   1620: 
1.48      anton    1621: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1622: @section Stack Manipulation
1.66      anton    1623: @cindex stack manipulation tutorial
1.48      anton    1624: 
                   1625: Stack manipulation words rearrange the data on the stack.
                   1626: 
                   1627: @example
                   1628: 1 .s drop .s
                   1629: 1 .s dup .s drop drop .s
                   1630: 1 2 .s over .s drop drop drop
                   1631: 1 2 .s swap .s drop drop
                   1632: 1 2 3 .s rot .s drop drop drop
                   1633: @end example
                   1634: 
                   1635: These are the most important stack manipulation words.  There are also
                   1636: variants that manipulate twice as many stack items:
                   1637: 
                   1638: @example
                   1639: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1640: @end example
                   1641: 
                   1642: Two more stack manipulation words are:
                   1643: 
                   1644: @example
                   1645: 1 2 .s nip .s drop
                   1646: 1 2 .s tuck .s 2drop drop
                   1647: @end example
                   1648: 
                   1649: @assignment
                   1650: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1651: manipulation words.
                   1652: 
                   1653: @example
                   1654: Given:          How do you get:
                   1655: 1 2 3           3 2 1           
                   1656: 1 2 3           1 2 3 2                 
                   1657: 1 2 3           1 2 3 3                 
                   1658: 1 2 3           1 3 3           
                   1659: 1 2 3           2 1 3           
                   1660: 1 2 3 4         4 3 2 1         
                   1661: 1 2 3           1 2 3 1 2 3             
                   1662: 1 2 3 4         1 2 3 4 1 2             
                   1663: 1 2 3
                   1664: 1 2 3           1 2 3 4                 
                   1665: 1 2 3           1 3             
                   1666: @end example
                   1667: @endassignment
                   1668: 
                   1669: @example
                   1670: 5 dup * .
                   1671: @end example
                   1672: 
                   1673: @assignment
                   1674: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1675: Write a piece of Forth code that expects two numbers on the stack
                   1676: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1677: @code{(a-b)(a+1)}.
                   1678: @endassignment
                   1679: 
1.66      anton    1680: Reference: @ref{Stack Manipulation}.
                   1681: 
                   1682: 
1.48      anton    1683: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1684: @section Using files for Forth code
1.66      anton    1685: @cindex loading Forth code, tutorial
                   1686: @cindex files containing Forth code, tutorial
1.48      anton    1687: 
                   1688: While working at the Forth command line is convenient for one-line
                   1689: examples and short one-off code, you probably want to store your source
                   1690: code in files for convenient editing and persistence.  You can use your
                   1691: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
                   1692: Gforth}) to create @var{file} and use
                   1693: 
                   1694: @example
                   1695: s" @var{file}" included
                   1696: @end example
                   1697: 
                   1698: to load it into your Forth system.  The file name extension I use for
                   1699: Forth files is @samp{.fs}.
                   1700: 
                   1701: You can easily start Gforth with some files loaded like this:
                   1702: 
                   1703: @example
                   1704: gforth @var{file1} @var{file2}
                   1705: @end example
                   1706: 
                   1707: If an error occurs during loading these files, Gforth terminates,
                   1708: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1709: a Gforth command line.  Starting the Forth system every time gives you a
                   1710: clean start every time, without interference from the results of earlier
                   1711: tries.
                   1712: 
                   1713: I often put all the tests in a file, then load the code and run the
                   1714: tests with
                   1715: 
                   1716: @example
                   1717: gforth @var{code} @var{tests} -e bye
                   1718: @end example
                   1719: 
                   1720: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1721: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1722: restart this command without ado.
                   1723: 
                   1724: The advantage of this approach is that the tests can be repeated easily
                   1725: every time the program ist changed, making it easy to catch bugs
                   1726: introduced by the change.
                   1727: 
1.66      anton    1728: Reference: @ref{Forth source files}.
                   1729: 
1.48      anton    1730: 
                   1731: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1732: @section Comments
1.66      anton    1733: @cindex comments tutorial
1.48      anton    1734: 
                   1735: @example
                   1736: \ That's a comment; it ends at the end of the line
                   1737: ( Another comment; it ends here: )  .s
                   1738: @end example
                   1739: 
                   1740: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1741: separated with white space from the following text.
                   1742: 
                   1743: @example
                   1744: \This gives an "Undefined word" error
                   1745: @end example
                   1746: 
                   1747: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1748: nest @code{(}-comments; and you cannot comment out text containing a
                   1749: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1750: avoid @code{)} in word names.}.
                   1751: 
                   1752: I use @code{\}-comments for descriptive text and for commenting out code
                   1753: of one or more line; I use @code{(}-comments for describing the stack
                   1754: effect, the stack contents, or for commenting out sub-line pieces of
                   1755: code.
                   1756: 
                   1757: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1758: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1759: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1760: with @kbd{M-q}.
                   1761: 
1.66      anton    1762: Reference: @ref{Comments}.
                   1763: 
1.48      anton    1764: 
                   1765: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1766: @section Colon Definitions
1.66      anton    1767: @cindex colon definitions, tutorial
                   1768: @cindex definitions, tutorial
                   1769: @cindex procedures, tutorial
                   1770: @cindex functions, tutorial
1.48      anton    1771: 
                   1772: are similar to procedures and functions in other programming languages.
                   1773: 
                   1774: @example
                   1775: : squared ( n -- n^2 )
                   1776:    dup * ;
                   1777: 5 squared .
                   1778: 7 squared .
                   1779: @end example
                   1780: 
                   1781: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1782: following comment describes its stack effect.  The words @code{dup *}
                   1783: are not executed, but compiled into the definition.  @code{;} ends the
                   1784: colon definition.
                   1785: 
                   1786: The newly-defined word can be used like any other word, including using
                   1787: it in other definitions:
                   1788: 
                   1789: @example
                   1790: : cubed ( n -- n^3 )
                   1791:    dup squared * ;
                   1792: -5 cubed .
                   1793: : fourth-power ( n -- n^4 )
                   1794:    squared squared ;
                   1795: 3 fourth-power .
                   1796: @end example
                   1797: 
                   1798: @assignment
                   1799: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1800: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1801: test your tests on the originals first).  Don't let the
                   1802: @samp{redefined}-Messages spook you, they are just warnings.
                   1803: @endassignment
                   1804: 
1.66      anton    1805: Reference: @ref{Colon Definitions}.
                   1806: 
1.48      anton    1807: 
                   1808: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1809: @section Decompilation
1.66      anton    1810: @cindex decompilation tutorial
                   1811: @cindex see tutorial
1.48      anton    1812: 
                   1813: You can decompile colon definitions with @code{see}:
                   1814: 
                   1815: @example
                   1816: see squared
                   1817: see cubed
                   1818: @end example
                   1819: 
                   1820: In Gforth @code{see} shows you a reconstruction of the source code from
                   1821: the executable code.  Informations that were present in the source, but
                   1822: not in the executable code, are lost (e.g., comments).
                   1823: 
1.65      anton    1824: You can also decompile the predefined words:
                   1825: 
                   1826: @example
                   1827: see .
                   1828: see +
                   1829: @end example
                   1830: 
                   1831: 
1.48      anton    1832: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1833: @section Stack-Effect Comments
1.66      anton    1834: @cindex stack-effect comments, tutorial
                   1835: @cindex --, tutorial
1.48      anton    1836: By convention the comment after the name of a definition describes the
                   1837: stack effect: The part in from of the @samp{--} describes the state of
                   1838: the stack before the execution of the definition, i.e., the parameters
                   1839: that are passed into the colon definition; the part behind the @samp{--}
                   1840: is the state of the stack after the execution of the definition, i.e.,
                   1841: the results of the definition.  The stack comment only shows the top
                   1842: stack items that the definition accesses and/or changes.
                   1843: 
                   1844: You should put a correct stack effect on every definition, even if it is
                   1845: just @code{( -- )}.  You should also add some descriptive comment to
                   1846: more complicated words (I usually do this in the lines following
                   1847: @code{:}).  If you don't do this, your code becomes unreadable (because
                   1848: you have to work through every definition before you can undertsand
                   1849: any).
                   1850: 
                   1851: @assignment
                   1852: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1853: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1854: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
1.65      anton    1855: are done, you can compare your stack effects to those in this manual
1.48      anton    1856: (@pxref{Word Index}).
                   1857: @endassignment
                   1858: 
                   1859: Sometimes programmers put comments at various places in colon
                   1860: definitions that describe the contents of the stack at that place (stack
                   1861: comments); i.e., they are like the first part of a stack-effect
                   1862: comment. E.g.,
                   1863: 
                   1864: @example
                   1865: : cubed ( n -- n^3 )
                   1866:    dup squared  ( n n^2 ) * ;
                   1867: @end example
                   1868: 
                   1869: In this case the stack comment is pretty superfluous, because the word
                   1870: is simple enough.  If you think it would be a good idea to add such a
                   1871: comment to increase readability, you should also consider factoring the
                   1872: word into several simpler words (@pxref{Factoring Tutorial,,
1.60      anton    1873: Factoring}), which typically eliminates the need for the stack comment;
1.48      anton    1874: however, if you decide not to refactor it, then having such a comment is
                   1875: better than not having it.
                   1876: 
                   1877: The names of the stack items in stack-effect and stack comments in the
                   1878: standard, in this manual, and in many programs specify the type through
                   1879: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1880: frequent prefixes are:
                   1881: 
                   1882: @table @code
                   1883: @item n
                   1884: signed integer
                   1885: @item u
                   1886: unsigned integer
                   1887: @item c
                   1888: character
                   1889: @item f
                   1890: Boolean flags, i.e. @code{false} or @code{true}.
                   1891: @item a-addr,a-
                   1892: Cell-aligned address
                   1893: @item c-addr,c-
                   1894: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1895: @item xt
                   1896: Execution token, same size as Cell
                   1897: @item w,x
                   1898: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1899: 16 bits (depending on your platform and Forth system). A cell is more
                   1900: commonly known as machine word, but the term @emph{word} already means
                   1901: something different in Forth.
                   1902: @item d
                   1903: signed double-cell integer
                   1904: @item ud
                   1905: unsigned double-cell integer
                   1906: @item r
                   1907: Float (on the FP stack)
                   1908: @end table
                   1909: 
                   1910: You can find a more complete list in @ref{Notation}.
                   1911: 
                   1912: @assignment
                   1913: Write stack-effect comments for all definitions you have written up to
                   1914: now.
                   1915: @endassignment
                   1916: 
                   1917: 
                   1918: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1919: @section Types
1.66      anton    1920: @cindex types tutorial
1.48      anton    1921: 
                   1922: In Forth the names of the operations are not overloaded; so similar
                   1923: operations on different types need different names; e.g., @code{+} adds
                   1924: integers, and you have to use @code{f+} to add floating-point numbers.
                   1925: The following prefixes are often used for related operations on
                   1926: different types:
                   1927: 
                   1928: @table @code
                   1929: @item (none)
                   1930: signed integer
                   1931: @item u
                   1932: unsigned integer
                   1933: @item c
                   1934: character
                   1935: @item d
                   1936: signed double-cell integer
                   1937: @item ud, du
                   1938: unsigned double-cell integer
                   1939: @item 2
                   1940: two cells (not-necessarily double-cell numbers)
                   1941: @item m, um
                   1942: mixed single-cell and double-cell operations
                   1943: @item f
                   1944: floating-point (note that in stack comments @samp{f} represents flags,
1.66      anton    1945: and @samp{r} represents FP numbers).
1.48      anton    1946: @end table
                   1947: 
                   1948: If there are no differences between the signed and the unsigned variant
                   1949: (e.g., for @code{+}), there is only the prefix-less variant.
                   1950: 
                   1951: Forth does not perform type checking, neither at compile time, nor at
                   1952: run time.  If you use the wrong oeration, the data are interpreted
                   1953: incorrectly:
                   1954: 
                   1955: @example
                   1956: -1 u.
                   1957: @end example
                   1958: 
                   1959: If you have only experience with type-checked languages until now, and
                   1960: have heard how important type-checking is, don't panic!  In my
                   1961: experience (and that of other Forthers), type errors in Forth code are
                   1962: usually easy to find (once you get used to it), the increased vigilance
                   1963: of the programmer tends to catch some harder errors in addition to most
                   1964: type errors, and you never have to work around the type system, so in
                   1965: most situations the lack of type-checking seems to be a win (projects to
                   1966: add type checking to Forth have not caught on).
                   1967: 
                   1968: 
                   1969: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   1970: @section Factoring
1.66      anton    1971: @cindex factoring tutorial
1.48      anton    1972: 
                   1973: If you try to write longer definitions, you will soon find it hard to
                   1974: keep track of the stack contents.  Therefore, good Forth programmers
                   1975: tend to write only short definitions (e.g., three lines).  The art of
                   1976: finding meaningful short definitions is known as factoring (as in
                   1977: factoring polynomials).
                   1978: 
                   1979: Well-factored programs offer additional advantages: smaller, more
                   1980: general words, are easier to test and debug and can be reused more and
                   1981: better than larger, specialized words.
                   1982: 
                   1983: So, if you run into difficulties with stack management, when writing
                   1984: code, try to define meaningful factors for the word, and define the word
                   1985: in terms of those.  Even if a factor contains only two words, it is
                   1986: often helpful.
                   1987: 
1.65      anton    1988: Good factoring is not easy, and it takes some practice to get the knack
                   1989: for it; but even experienced Forth programmers often don't find the
                   1990: right solution right away, but only when rewriting the program.  So, if
                   1991: you don't come up with a good solution immediately, keep trying, don't
                   1992: despair.
1.48      anton    1993: 
                   1994: @c example !!
                   1995: 
                   1996: 
                   1997: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   1998: @section Designing the stack effect
1.66      anton    1999: @cindex Stack effect design, tutorial
                   2000: @cindex design of stack effects, tutorial
1.48      anton    2001: 
                   2002: In other languages you can use an arbitrary order of parameters for a
1.65      anton    2003: function; and since there is only one result, you don't have to deal with
1.48      anton    2004: the order of results, either.
                   2005: 
                   2006: In Forth (and other stack-based languages, e.g., Postscript) the
                   2007: parameter and result order of a definition is important and should be
                   2008: designed well.  The general guideline is to design the stack effect such
                   2009: that the word is simple to use in most cases, even if that complicates
                   2010: the implementation of the word.  Some concrete rules are:
                   2011: 
                   2012: @itemize @bullet
                   2013: 
                   2014: @item
                   2015: Words consume all of their parameters (e.g., @code{.}).
                   2016: 
                   2017: @item
                   2018: If there is a convention on the order of parameters (e.g., from
                   2019: mathematics or another programming language), stick with it (e.g.,
                   2020: @code{-}).
                   2021: 
                   2022: @item
                   2023: If one parameter usually requires only a short computation (e.g., it is
                   2024: a constant), pass it on the top of the stack.  Conversely, parameters
                   2025: that usually require a long sequence of code to compute should be passed
                   2026: as the bottom (i.e., first) parameter.  This makes the code easier to
                   2027: read, because reader does not need to keep track of the bottom item
                   2028: through a long sequence of code (or, alternatively, through stack
1.49      anton    2029: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    2030: address on top of the stack because it is usually simpler to compute
                   2031: than the stored value (often the address is just a variable).
                   2032: 
                   2033: @item
                   2034: Similarly, results that are usually consumed quickly should be returned
                   2035: on the top of stack, whereas a result that is often used in long
                   2036: computations should be passed as bottom result.  E.g., the file words
                   2037: like @code{open-file} return the error code on the top of stack, because
                   2038: it is usually consumed quickly by @code{throw}; moreover, the error code
                   2039: has to be checked before doing anything with the other results.
                   2040: 
                   2041: @end itemize
                   2042: 
                   2043: These rules are just general guidelines, don't lose sight of the overall
                   2044: goal to make the words easy to use.  E.g., if the convention rule
                   2045: conflicts with the computation-length rule, you might decide in favour
                   2046: of the convention if the word will be used rarely, and in favour of the
                   2047: computation-length rule if the word will be used frequently (because
                   2048: with frequent use the cost of breaking the computation-length rule would
                   2049: be quite high, and frequent use makes it easier to remember an
                   2050: unconventional order).
                   2051: 
                   2052: @c example !! structure package
                   2053: 
1.65      anton    2054: 
1.48      anton    2055: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   2056: @section Local Variables
1.66      anton    2057: @cindex local variables, tutorial
1.48      anton    2058: 
                   2059: You can define local variables (@emph{locals}) in a colon definition:
                   2060: 
                   2061: @example
                   2062: : swap @{ a b -- b a @}
                   2063:   b a ;
                   2064: 1 2 swap .s 2drop
                   2065: @end example
                   2066: 
                   2067: (If your Forth system does not support this syntax, include
                   2068: @file{compat/anslocals.fs} first).
                   2069: 
                   2070: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   2071: takes two cells from the stack, puts the top of stack in @code{b} and
                   2072: the next stack element in @code{a}.  @code{--} starts a comment ending
                   2073: with @code{@}}.  After the locals definition, using the name of the
                   2074: local will push its value on the stack.  You can leave the comment
                   2075: part (@code{-- b a}) away:
                   2076: 
                   2077: @example
                   2078: : swap ( x1 x2 -- x2 x1 )
                   2079:   @{ a b @} b a ;
                   2080: @end example
                   2081: 
                   2082: In Gforth you can have several locals definitions, anywhere in a colon
                   2083: definition; in contrast, in a standard program you can have only one
                   2084: locals definition per colon definition, and that locals definition must
                   2085: be outside any controll structure.
                   2086: 
                   2087: With locals you can write slightly longer definitions without running
                   2088: into stack trouble.  However, I recommend trying to write colon
                   2089: definitions without locals for exercise purposes to help you gain the
                   2090: essential factoring skills.
                   2091: 
                   2092: @assignment
                   2093: Rewrite your definitions until now with locals
                   2094: @endassignment
                   2095: 
1.66      anton    2096: Reference: @ref{Locals}.
                   2097: 
1.48      anton    2098: 
                   2099: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   2100: @section Conditional execution
1.66      anton    2101: @cindex conditionals, tutorial
                   2102: @cindex if, tutorial
1.48      anton    2103: 
                   2104: In Forth you can use control structures only inside colon definitions.
                   2105: An @code{if}-structure looks like this:
                   2106: 
                   2107: @example
                   2108: : abs ( n1 -- +n2 )
                   2109:     dup 0 < if
                   2110:         negate
                   2111:     endif ;
                   2112: 5 abs .
                   2113: -5 abs .
                   2114: @end example
                   2115: 
                   2116: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   2117: the following code is performed, otherwise execution continues after the
1.51      pazsan   2118: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.48      anton    2119: elements and prioduces a flag:
                   2120: 
                   2121: @example
                   2122: 1 2 < .
                   2123: 2 1 < .
                   2124: 1 1 < .
                   2125: @end example
                   2126: 
                   2127: Actually the standard name for @code{endif} is @code{then}.  This
                   2128: tutorial presents the examples using @code{endif}, because this is often
                   2129: less confusing for people familiar with other programming languages
                   2130: where @code{then} has a different meaning.  If your system does not have
                   2131: @code{endif}, define it with
                   2132: 
                   2133: @example
                   2134: : endif postpone then ; immediate
                   2135: @end example
                   2136: 
                   2137: You can optionally use an @code{else}-part:
                   2138: 
                   2139: @example
                   2140: : min ( n1 n2 -- n )
                   2141:   2dup < if
                   2142:     drop
                   2143:   else
                   2144:     nip
                   2145:   endif ;
                   2146: 2 3 min .
                   2147: 3 2 min .
                   2148: @end example
                   2149: 
                   2150: @assignment
                   2151: Write @code{min} without @code{else}-part (hint: what's the definition
                   2152: of @code{nip}?).
                   2153: @endassignment
                   2154: 
1.66      anton    2155: Reference: @ref{Selection}.
                   2156: 
1.48      anton    2157: 
                   2158: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   2159: @section Flags and Comparisons
1.66      anton    2160: @cindex flags tutorial
                   2161: @cindex comparison tutorial
1.48      anton    2162: 
                   2163: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   2164: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   2165: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   2166: treated as true flag.
                   2167: 
                   2168: @example
                   2169: false .
                   2170: true .
                   2171: true hex u. decimal
                   2172: @end example
                   2173: 
                   2174: Comparison words produce canonical flags:
                   2175: 
                   2176: @example
                   2177: 1 1 = .
                   2178: 1 0= .
                   2179: 0 1 < .
                   2180: 0 0 < .
                   2181: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   2182: -1 1 < .
                   2183: @end example
                   2184: 
1.66      anton    2185: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
                   2186: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
                   2187: these combinations are standard (for details see the standard,
                   2188: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48      anton    2189: 
                   2190: You can use @code{and or xor invert} can be used as operations on
                   2191: canonical flags.  Actually they are bitwise operations:
                   2192: 
                   2193: @example
                   2194: 1 2 and .
                   2195: 1 2 or .
                   2196: 1 3 xor .
                   2197: 1 invert .
                   2198: @end example
                   2199: 
                   2200: You can convert a zero/non-zero flag into a canonical flag with
                   2201: @code{0<>} (and complement it on the way with @code{0=}).
                   2202: 
                   2203: @example
                   2204: 1 0= .
                   2205: 1 0<> .
                   2206: @end example
                   2207: 
1.65      anton    2208: You can use the all-bits-set feature of canonical flags and the bitwise
1.48      anton    2209: operation of the Boolean operations to avoid @code{if}s:
                   2210: 
                   2211: @example
                   2212: : foo ( n1 -- n2 )
                   2213:   0= if
                   2214:     14
                   2215:   else
                   2216:     0
                   2217:   endif ;
                   2218: 0 foo .
                   2219: 1 foo .
                   2220: 
                   2221: : foo ( n1 -- n2 )
                   2222:   0= 14 and ;
                   2223: 0 foo .
                   2224: 1 foo .
                   2225: @end example
                   2226: 
                   2227: @assignment
                   2228: Write @code{min} without @code{if}.
                   2229: @endassignment
                   2230: 
1.66      anton    2231: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
                   2232: @ref{Bitwise operations}.
                   2233: 
1.48      anton    2234: 
                   2235: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   2236: @section General Loops
1.66      anton    2237: @cindex loops, indefinite, tutorial
1.48      anton    2238: 
                   2239: The endless loop is the most simple one:
                   2240: 
                   2241: @example
                   2242: : endless ( -- )
                   2243:   0 begin
                   2244:     dup . 1+
                   2245:   again ;
                   2246: endless
                   2247: @end example
                   2248: 
                   2249: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   2250: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   2251: 
                   2252: A loop with one exit at any place looks like this:
                   2253: 
                   2254: @example
                   2255: : log2 ( +n1 -- n2 )
                   2256: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2257:   assert( dup 0> )
                   2258:   2/ 0 begin
                   2259:     over 0> while
                   2260:       1+ swap 2/ swap
                   2261:   repeat
                   2262:   nip ;
                   2263: 7 log2 .
                   2264: 8 log2 .
                   2265: @end example
                   2266: 
                   2267: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   2268: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    2269: continues behind the @code{while}.  @code{Repeat} jumps back to
                   2270: @code{begin}, just like @code{again}.
                   2271: 
                   2272: In Forth there are many combinations/abbreviations, like @code{1+}.
                   2273: However, @code{2/} is not one of them; it shifts it's argument right by
                   2274: one bit (arithmetic shift right):
                   2275: 
                   2276: @example
                   2277: -5 2 / .
                   2278: -5 2/ .
                   2279: @end example
                   2280: 
                   2281: @code{assert(} is no standard word, but you can get it on systems other
                   2282: then Gforth by including @file{compat/assert.fs}.  You can see what it
                   2283: does by trying
                   2284: 
                   2285: @example
                   2286: 0 log2 .
                   2287: @end example
                   2288: 
                   2289: Here's a loop with an exit at the end:
                   2290: 
                   2291: @example
                   2292: : log2 ( +n1 -- n2 )
                   2293: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2294:   assert( dup 0 > )
                   2295:   -1 begin
                   2296:     1+ swap 2/ swap
                   2297:     over 0 <=
                   2298:   until
                   2299:   nip ;
                   2300: @end example
                   2301: 
                   2302: @code{Until} consumes a flag; if it is non-zero, execution continues at
                   2303: the @code{begin}, otherwise after the @code{until}.
                   2304: 
                   2305: @assignment
                   2306: Write a definition for computing the greatest common divisor.
                   2307: @endassignment
                   2308: 
1.66      anton    2309: Reference: @ref{Simple Loops}.
                   2310: 
1.48      anton    2311: 
                   2312: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   2313: @section Counted loops
1.66      anton    2314: @cindex loops, counted, tutorial
1.48      anton    2315: 
                   2316: @example
                   2317: : ^ ( n1 u -- n )
                   2318: \ n = the uth power of u1
                   2319:   1 swap 0 u+do
                   2320:     over *
                   2321:   loop
                   2322:   nip ;
                   2323: 3 2 ^ .
                   2324: 4 3 ^ .
                   2325: @end example
                   2326: 
                   2327: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   2328: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   2329: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2330: times (or not at all, if @code{u3-u4<0}).
                   2331: 
                   2332: You can see the stack effect design rules at work in the stack effect of
                   2333: the loop start words: Since the start value of the loop is more
                   2334: frequently constant than the end value, the start value is passed on
                   2335: the top-of-stack.
                   2336: 
                   2337: You can access the counter of a counted loop with @code{i}:
                   2338: 
                   2339: @example
                   2340: : fac ( u -- u! )
                   2341:   1 swap 1+ 1 u+do
                   2342:     i *
                   2343:   loop ;
                   2344: 5 fac .
                   2345: 7 fac .
                   2346: @end example
                   2347: 
                   2348: There is also @code{+do}, which expects signed numbers (important for
                   2349: deciding whether to enter the loop).
                   2350: 
                   2351: @assignment
                   2352: Write a definition for computing the nth Fibonacci number.
                   2353: @endassignment
                   2354: 
1.65      anton    2355: You can also use increments other than 1:
                   2356: 
                   2357: @example
                   2358: : up2 ( n1 n2 -- )
                   2359:   +do
                   2360:     i .
                   2361:   2 +loop ;
                   2362: 10 0 up2
                   2363: 
                   2364: : down2 ( n1 n2 -- )
                   2365:   -do
                   2366:     i .
                   2367:   2 -loop ;
                   2368: 0 10 down2
                   2369: @end example
1.48      anton    2370: 
1.66      anton    2371: Reference: @ref{Counted Loops}.
                   2372: 
1.48      anton    2373: 
                   2374: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2375: @section Recursion
1.66      anton    2376: @cindex recursion tutorial
1.48      anton    2377: 
                   2378: Usually the name of a definition is not visible in the definition; but
                   2379: earlier definitions are usually visible:
                   2380: 
                   2381: @example
                   2382: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
                   2383: : / ( n1 n2 -- n )
                   2384:   dup 0= if
                   2385:     -10 throw \ report division by zero
                   2386:   endif
                   2387:   /           \ old version
                   2388: ;
                   2389: 1 0 /
                   2390: @end example
                   2391: 
                   2392: For recursive definitions you can use @code{recursive} (non-standard) or
                   2393: @code{recurse}:
                   2394: 
                   2395: @example
                   2396: : fac1 ( n -- n! ) recursive
                   2397:  dup 0> if
                   2398:    dup 1- fac1 *
                   2399:  else
                   2400:    drop 1
                   2401:  endif ;
                   2402: 7 fac1 .
                   2403: 
                   2404: : fac2 ( n -- n! )
                   2405:  dup 0> if
                   2406:    dup 1- recurse *
                   2407:  else
                   2408:    drop 1
                   2409:  endif ;
                   2410: 8 fac2 .
                   2411: @end example
                   2412: 
                   2413: @assignment
                   2414: Write a recursive definition for computing the nth Fibonacci number.
                   2415: @endassignment
                   2416: 
1.66      anton    2417: Reference (including indirect recursion): @xref{Calls and returns}.
                   2418: 
1.48      anton    2419: 
                   2420: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2421: @section Leaving definitions or loops
1.66      anton    2422: @cindex leaving definitions, tutorial
                   2423: @cindex leaving loops, tutorial
1.48      anton    2424: 
                   2425: @code{EXIT} exits the current definition right away.  For every counted
                   2426: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2427: before the @code{EXIT}:
                   2428: 
                   2429: @c !! real examples
                   2430: @example
                   2431: : ...
                   2432:  ... u+do
                   2433:    ... if
                   2434:      ... unloop exit
                   2435:    endif
                   2436:    ...
                   2437:  loop
                   2438:  ... ;
                   2439: @end example
                   2440: 
                   2441: @code{LEAVE} leaves the innermost counted loop right away:
                   2442: 
                   2443: @example
                   2444: : ...
                   2445:  ... u+do
                   2446:    ... if
                   2447:      ... leave
                   2448:    endif
                   2449:    ...
                   2450:  loop
                   2451:  ... ;
                   2452: @end example
                   2453: 
1.65      anton    2454: @c !! example
1.48      anton    2455: 
1.66      anton    2456: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
                   2457: 
                   2458: 
1.48      anton    2459: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2460: @section Return Stack
1.66      anton    2461: @cindex return stack tutorial
1.48      anton    2462: 
                   2463: In addition to the data stack Forth also has a second stack, the return
                   2464: stack; most Forth systems store the return addresses of procedure calls
                   2465: there (thus its name).  Programmers can also use this stack:
                   2466: 
                   2467: @example
                   2468: : foo ( n1 n2 -- )
                   2469:  .s
                   2470:  >r .s
1.50      anton    2471:  r@@ .
1.48      anton    2472:  >r .s
1.50      anton    2473:  r@@ .
1.48      anton    2474:  r> .
1.50      anton    2475:  r@@ .
1.48      anton    2476:  r> . ;
                   2477: 1 2 foo
                   2478: @end example
                   2479: 
                   2480: @code{>r} takes an element from the data stack and pushes it onto the
                   2481: return stack; conversely, @code{r>} moves an elementm from the return to
                   2482: the data stack; @code{r@@} pushes a copy of the top of the return stack
                   2483: on the return stack.
                   2484: 
                   2485: Forth programmers usually use the return stack for storing data
                   2486: temporarily, if using the data stack alone would be too complex, and
                   2487: factoring and locals are not an option:
                   2488: 
                   2489: @example
                   2490: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2491:  rot >r rot r> ;
                   2492: @end example
                   2493: 
                   2494: The return address of the definition and the loop control parameters of
                   2495: counted loops usually reside on the return stack, so you have to take
                   2496: all items, that you have pushed on the return stack in a colon
                   2497: definition or counted loop, from the return stack before the definition
                   2498: or loop ends.  You cannot access items that you pushed on the return
                   2499: stack outside some definition or loop within the definition of loop.
                   2500: 
                   2501: If you miscount the return stack items, this usually ends in a crash:
                   2502: 
                   2503: @example
                   2504: : crash ( n -- )
                   2505:   >r ;
                   2506: 5 crash
                   2507: @end example
                   2508: 
                   2509: You cannot mix using locals and using the return stack (according to the
                   2510: standard; Gforth has no problem).  However, they solve the same
                   2511: problems, so this shouldn't be an issue.
                   2512: 
                   2513: @assignment
                   2514: Can you rewrite any of the definitions you wrote until now in a better
                   2515: way using the return stack?
                   2516: @endassignment
                   2517: 
1.66      anton    2518: Reference: @ref{Return stack}.
                   2519: 
1.48      anton    2520: 
                   2521: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2522: @section Memory
1.66      anton    2523: @cindex memory access/allocation tutorial
1.48      anton    2524: 
                   2525: You can create a global variable @code{v} with
                   2526: 
                   2527: @example
                   2528: variable v ( -- addr )
                   2529: @end example
                   2530: 
                   2531: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2532: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2533: values into this cell and @code{@@} (fetch) to load the value from the
                   2534: stack into memory:
                   2535: 
                   2536: @example
                   2537: v .
                   2538: 5 v ! .s
1.50      anton    2539: v @@ .
1.48      anton    2540: @end example
                   2541: 
1.65      anton    2542: You can see a raw dump of memory with @code{dump}:
                   2543: 
                   2544: @example
                   2545: v 1 cells .s dump
                   2546: @end example
                   2547: 
                   2548: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
                   2549: generally, address units (aus)) that @code{n1 cells} occupy.  You can
                   2550: also reserve more memory:
1.48      anton    2551: 
                   2552: @example
                   2553: create v2 20 cells allot
1.65      anton    2554: v2 20 cells dump
1.48      anton    2555: @end example
                   2556: 
1.65      anton    2557: creates a word @code{v2} and reserves 20 uninitialized cells; the
                   2558: address pushed by @code{v2} points to the start of these 20 cells.  You
                   2559: can use address arithmetic to access these cells:
1.48      anton    2560: 
                   2561: @example
                   2562: 3 v2 5 cells + !
1.65      anton    2563: v2 20 cells dump
1.48      anton    2564: @end example
                   2565: 
                   2566: You can reserve and initialize memory with @code{,}:
                   2567: 
                   2568: @example
                   2569: create v3
                   2570:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2571: v3 @@ .
                   2572: v3 cell+ @@ .
                   2573: v3 2 cells + @@ .
1.65      anton    2574: v3 5 cells dump
1.48      anton    2575: @end example
                   2576: 
                   2577: @assignment
                   2578: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2579: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2580: one at @code{addr cell+} etc.
                   2581: @endassignment
                   2582: 
                   2583: You can also reserve memory without creating a new word:
                   2584: 
                   2585: @example
1.60      anton    2586: here 10 cells allot .
                   2587: here .
1.48      anton    2588: @end example
                   2589: 
                   2590: @code{Here} pushes the start address of the memory area.  You should
                   2591: store it somewhere, or you will have a hard time finding the memory area
                   2592: again.
                   2593: 
                   2594: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2595: the system's data structures for words etc. on Gforth and most other
                   2596: Forth systems.  It is managed like a stack: You can free the memory that
                   2597: you have just @code{allot}ed with
                   2598: 
                   2599: @example
                   2600: -10 cells allot
1.60      anton    2601: here .
1.48      anton    2602: @end example
                   2603: 
                   2604: Note that you cannot do this if you have created a new word in the
                   2605: meantime (because then your @code{allot}ed memory is no longer on the
                   2606: top of the dictionary ``stack'').
                   2607: 
                   2608: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2609: freeing memory in any order:
                   2610: 
                   2611: @example
                   2612: 10 cells allocate throw .s
                   2613: 20 cells allocate throw .s
                   2614: swap
                   2615: free throw
                   2616: free throw
                   2617: @end example
                   2618: 
                   2619: The @code{throw}s deal with errors (e.g., out of memory).
                   2620: 
1.65      anton    2621: And there is also a
                   2622: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   2623: garbage collector}, which eliminates the need to @code{free} memory
                   2624: explicitly.
1.48      anton    2625: 
1.66      anton    2626: Reference: @ref{Memory}.
                   2627: 
1.48      anton    2628: 
                   2629: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2630: @section Characters and Strings
1.66      anton    2631: @cindex strings tutorial
                   2632: @cindex characters tutorial
1.48      anton    2633: 
                   2634: On the stack characters take up a cell, like numbers.  In memory they
                   2635: have their own size (one 8-bit byte on most systems), and therefore
                   2636: require their own words for memory access:
                   2637: 
                   2638: @example
                   2639: create v4 
                   2640:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2641: v4 4 chars + c@@ .
1.65      anton    2642: v4 5 chars dump
1.48      anton    2643: @end example
                   2644: 
                   2645: The preferred representation of strings on the stack is @code{addr
                   2646: u-count}, where @code{addr} is the address of the first character and
                   2647: @code{u-count} is the number of characters in the string.
                   2648: 
                   2649: @example
                   2650: v4 5 type
                   2651: @end example
                   2652: 
                   2653: You get a string constant with
                   2654: 
                   2655: @example
                   2656: s" hello, world" .s
                   2657: type
                   2658: @end example
                   2659: 
                   2660: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2661: is a normal Forth word and must be delimited with white space (try what
                   2662: happens when you remove the space).
                   2663: 
                   2664: However, this interpretive use of @code{s"} is quite restricted: the
                   2665: string exists only until the next call of @code{s"} (some Forth systems
                   2666: keep more than one of these strings, but usually they still have a
1.62      crook    2667: limited lifetime).
1.48      anton    2668: 
                   2669: @example
                   2670: s" hello," s" world" .s
                   2671: type
                   2672: type
                   2673: @end example
                   2674: 
1.62      crook    2675: You can also use @code{s"} in a definition, and the resulting
                   2676: strings then live forever (well, for as long as the definition):
1.48      anton    2677: 
                   2678: @example
                   2679: : foo s" hello," s" world" ;
                   2680: foo .s
                   2681: type
                   2682: type
                   2683: @end example
                   2684: 
                   2685: @assignment
                   2686: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2687: Implement @code{type ( addr u -- )}.
                   2688: @endassignment
                   2689: 
1.66      anton    2690: Reference: @ref{Memory Blocks}.
                   2691: 
                   2692: 
1.48      anton    2693: @node Alignment Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Characters and Strings Tutorial, Tutorial
                   2694: @section Alignment
1.66      anton    2695: @cindex alignment tutorial
                   2696: @cindex memory alignment tutorial
1.48      anton    2697: 
                   2698: On many processors cells have to be aligned in memory, if you want to
                   2699: access them with @code{@@} and @code{!} (and even if the processor does
1.62      crook    2700: not require alignment, access to aligned cells is faster).
1.48      anton    2701: 
                   2702: @code{Create} aligns @code{here} (i.e., the place where the next
                   2703: allocation will occur, and that the @code{create}d word points to).
                   2704: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2705: address.  Adding a number of @code{cells} to an aligned address produces
                   2706: another aligned address.
                   2707: 
                   2708: However, address arithmetic involving @code{char+} and @code{chars} can
                   2709: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2710: a-addr )} produces the next aligned address:
                   2711: 
                   2712: @example
1.50      anton    2713: v3 char+ aligned .s @@ .
                   2714: v3 char+ .s @@ .
1.48      anton    2715: @end example
                   2716: 
                   2717: Similarly, @code{align} advances @code{here} to the next aligned
                   2718: address:
                   2719: 
                   2720: @example
                   2721: create v5 97 c,
                   2722: here .
                   2723: align here .
                   2724: 1000 ,
                   2725: @end example
                   2726: 
                   2727: Note that you should use aligned addresses even if your processor does
                   2728: not require them, if you want your program to be portable.
                   2729: 
1.66      anton    2730: Reference: @ref{Address arithmetic}.
                   2731: 
1.48      anton    2732: 
                   2733: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Alignment Tutorial, Tutorial
                   2734: @section Interpretation and Compilation Semantics and Immediacy
1.66      anton    2735: @cindex semantics tutorial
                   2736: @cindex interpretation semantics tutorial
                   2737: @cindex compilation semantics tutorial
                   2738: @cindex immediate, tutorial
1.48      anton    2739: 
                   2740: When a word is compiled, it behaves differently from being interpreted.
                   2741: E.g., consider @code{+}:
                   2742: 
                   2743: @example
                   2744: 1 2 + .
                   2745: : foo + ;
                   2746: @end example
                   2747: 
                   2748: These two behaviours are known as compilation and interpretation
                   2749: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2750: is to append the interpretation semantics to the currently defined word
                   2751: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2752: later, the interpretation semantics of @code{+} (i.e., adding two
                   2753: numbers) will be performed.
                   2754: 
                   2755: However, there are words with non-default compilation semantics, e.g.,
                   2756: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2757: change the compilation semantics of the last defined word to be equal to
                   2758: the interpretation semantics:
                   2759: 
                   2760: @example
                   2761: : [FOO] ( -- )
                   2762:  5 . ; immediate
                   2763: 
                   2764: [FOO]
                   2765: : bar ( -- )
                   2766:   [FOO] ;
                   2767: bar
                   2768: see bar
                   2769: @end example
                   2770: 
                   2771: Two conventions to mark words with non-default compilation semnatics are
                   2772: names with brackets (more frequently used) and to write them all in
                   2773: upper case (less frequently used).
                   2774: 
                   2775: In Gforth (and many other systems) you can also remove the
                   2776: interpretation semantics with @code{compile-only} (the compilation
                   2777: semantics is derived from the original interpretation semantics):
                   2778: 
                   2779: @example
                   2780: : flip ( -- )
                   2781:  6 . ; compile-only \ but not immediate
                   2782: flip
                   2783: 
                   2784: : flop ( -- )
                   2785:  flip ;
                   2786: flop
                   2787: @end example
                   2788: 
                   2789: In this example the interpretation semantics of @code{flop} is equal to
                   2790: the original interpretation semantics of @code{flip}.
                   2791: 
                   2792: The text interpreter has two states: in interpret state, it performs the
                   2793: interpretation semantics of words it encounters; in compile state, it
                   2794: performs the compilation semantics of these words.
                   2795: 
                   2796: Among other things, @code{:} switches into compile state, and @code{;}
                   2797: switches back to interpret state.  They contain the factors @code{]}
                   2798: (switch to compile state) and @code{[} (switch to interpret state), that
                   2799: do nothing but switch the state.
                   2800: 
                   2801: @example
                   2802: : xxx ( -- )
                   2803:   [ 5 . ]
                   2804: ;
                   2805: 
                   2806: xxx
                   2807: see xxx
                   2808: @end example
                   2809: 
                   2810: These brackets are also the source of the naming convention mentioned
                   2811: above.
                   2812: 
1.66      anton    2813: Reference: @ref{Interpretation and Compilation Semantics}.
                   2814: 
1.48      anton    2815: 
                   2816: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2817: @section Execution Tokens
1.66      anton    2818: @cindex execution tokens tutorial
                   2819: @cindex XT tutorial
1.48      anton    2820: 
                   2821: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2822: cell representing the interpretation semantics of a word.  You can
                   2823: execute this semantics with @code{execute}:
                   2824: 
                   2825: @example
                   2826: ' + .s
                   2827: 1 2 rot execute .
                   2828: @end example
                   2829: 
                   2830: The XT is similar to a function pointer in C.  However, parameter
                   2831: passing through the stack makes it a little more flexible:
                   2832: 
                   2833: @example
                   2834: : map-array ( ... addr u xt -- ... )
1.50      anton    2835: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2836: \ at addr and containing u elements
1.48      anton    2837:   @{ xt @}
                   2838:   cells over + swap ?do
1.50      anton    2839:     i @@ xt execute
1.48      anton    2840:   1 cells +loop ;
                   2841: 
                   2842: create a 3 , 4 , 2 , -1 , 4 ,
                   2843: a 5 ' . map-array .s
                   2844: 0 a 5 ' + map-array .
                   2845: s" max-n" environment? drop .s
                   2846: a 5 ' min map-array .
                   2847: @end example
                   2848: 
                   2849: You can use map-array with the XTs of words that consume one element
                   2850: more than they produce.  In theory you can also use it with other XTs,
                   2851: but the stack effect then depends on the size of the array, which is
                   2852: hard to understand.
                   2853: 
1.51      pazsan   2854: Since XTs are cell-sized, you can store them in memory and manipulate
                   2855: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2856: word with @code{compile,}:
                   2857: 
                   2858: @example
                   2859: : foo1 ( n1 n2 -- n )
                   2860:    [ ' + compile, ] ;
                   2861: see foo
                   2862: @end example
                   2863: 
                   2864: This is non-standard, because @code{compile,} has no compilation
                   2865: semantics in the standard, but it works in good Forth systems.  For the
                   2866: broken ones, use
                   2867: 
                   2868: @example
                   2869: : [compile,] compile, ; immediate
                   2870: 
                   2871: : foo1 ( n1 n2 -- n )
                   2872:    [ ' + ] [compile,] ;
                   2873: see foo
                   2874: @end example
                   2875: 
                   2876: @code{'} is a word with default compilation semantics; it parses the
                   2877: next word when its interpretation semantics are executed, not during
                   2878: compilation:
                   2879: 
                   2880: @example
                   2881: : foo ( -- xt )
                   2882:   ' ;
                   2883: see foo
                   2884: : bar ( ... "word" -- ... )
                   2885:   ' execute ;
                   2886: see bar
1.60      anton    2887: 1 2 bar + .
1.48      anton    2888: @end example
                   2889: 
                   2890: You often want to parse a word during compilation and compile its XT so
                   2891: it will be pushed on the stack at run-time.  @code{[']} does this:
                   2892: 
                   2893: @example
                   2894: : xt-+ ( -- xt )
                   2895:   ['] + ;
                   2896: see xt-+
                   2897: 1 2 xt-+ execute .
                   2898: @end example
                   2899: 
                   2900: Many programmers tend to see @code{'} and the word it parses as one
                   2901: unit, and expect it to behave like @code{[']} when compiled, and are
                   2902: confused by the actual behaviour.  If you are, just remember that the
                   2903: Forth system just takes @code{'} as one unit and has no idea that it is
                   2904: a parsing word (attempts to convenience programmers in this issue have
                   2905: usually resulted in even worse pitfalls, see
1.66      anton    2906: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
                   2907: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48      anton    2908: 
                   2909: Note that the state of the interpreter does not come into play when
1.51      pazsan   2910: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    2911: compile state, it still gives you the interpretation semantics.  And
                   2912: whatever that state is, @code{execute} performs the semantics
1.66      anton    2913: represented by the XT (i.e., for XTs produced with @code{'} the
                   2914: interpretation semantics).
                   2915: 
                   2916: Reference: @ref{Tokens for Words}.
1.48      anton    2917: 
                   2918: 
                   2919: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   2920: @section Exceptions
1.66      anton    2921: @cindex exceptions tutorial
1.48      anton    2922: 
                   2923: @code{throw ( n -- )} causes an exception unless n is zero.
                   2924: 
                   2925: @example
                   2926: 100 throw .s
                   2927: 0 throw .s
                   2928: @end example
                   2929: 
                   2930: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   2931: it catches exceptions and pushes the number of the exception on the
                   2932: stack (or 0, if the xt executed without exception).  If there was an
                   2933: exception, the stacks have the same depth as when entering @code{catch}:
                   2934: 
                   2935: @example
                   2936: .s
                   2937: 3 0 ' / catch .s
                   2938: 3 2 ' / catch .s
                   2939: @end example
                   2940: 
                   2941: @assignment
                   2942: Try the same with @code{execute} instead of @code{catch}.
                   2943: @endassignment
                   2944: 
                   2945: @code{Throw} always jumps to the dynamically next enclosing
                   2946: @code{catch}, even if it has to leave several call levels to achieve
                   2947: this:
                   2948: 
                   2949: @example
                   2950: : foo 100 throw ;
                   2951: : foo1 foo ." after foo" ;
1.51      pazsan   2952: : bar ['] foo1 catch ;
1.60      anton    2953: bar .
1.48      anton    2954: @end example
                   2955: 
                   2956: It is often important to restore a value upon leaving a definition, even
                   2957: if the definition is left through an exception.  You can ensure this
                   2958: like this:
                   2959: 
                   2960: @example
                   2961: : ...
                   2962:    save-x
1.51      pazsan   2963:    ['] word-changing-x catch ( ... n )
1.48      anton    2964:    restore-x
                   2965:    ( ... n ) throw ;
                   2966: @end example
                   2967: 
1.55      anton    2968: Gforth provides an alternative syntax in addition to @code{catch}:
1.48      anton    2969: @code{try ... recover ... endtry}.  If the code between @code{try} and
                   2970: @code{recover} has an exception, the stack depths are restored, the
                   2971: exception number is pushed on the stack, and the code between
                   2972: @code{recover} and @code{endtry} is performed.  E.g., the definition for
                   2973: @code{catch} is
                   2974: 
                   2975: @example
                   2976: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
                   2977:   try
                   2978:     execute 0
                   2979:   recover
                   2980:     nip
                   2981:   endtry ;
                   2982: @end example
                   2983: 
                   2984: The equivalent to the restoration code above is
                   2985: 
                   2986: @example
                   2987: : ...
                   2988:   save-x
                   2989:   try
                   2990:     word-changing-x
                   2991:   end-try
                   2992:   restore-x
                   2993:   throw ;
                   2994: @end example
                   2995: 
                   2996: As you can see, the @code{recover} part is optional.
                   2997: 
1.66      anton    2998: Reference: @ref{Exception Handling}.
                   2999: 
1.48      anton    3000: 
                   3001: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   3002: @section Defining Words
1.66      anton    3003: @cindex defining words tutorial
                   3004: @cindex does> tutorial
                   3005: @cindex create...does> tutorial
                   3006: 
                   3007: @c before semantics?
1.48      anton    3008: 
                   3009: @code{:}, @code{create}, and @code{variable} are definition words: They
                   3010: define other words.  @code{Constant} is another definition word:
                   3011: 
                   3012: @example
                   3013: 5 constant foo
                   3014: foo .
                   3015: @end example
                   3016: 
                   3017: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   3018: (floating point) with @code{variable} and @code{constant}.
                   3019: 
                   3020: You can also define your own defining words.  E.g.:
                   3021: 
                   3022: @example
                   3023: : variable ( "name" -- )
                   3024:   create 0 , ;
                   3025: @end example
                   3026: 
                   3027: You can also define defining words that create words that do something
                   3028: other than just producing their address:
                   3029: 
                   3030: @example
                   3031: : constant ( n "name" -- )
                   3032:   create ,
                   3033: does> ( -- n )
1.50      anton    3034:   ( addr ) @@ ;
1.48      anton    3035: 
                   3036: 5 constant foo
                   3037: foo .
                   3038: @end example
                   3039: 
                   3040: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   3041: @code{does>} replaces @code{;}, but it also does something else: It
                   3042: changes the last defined word such that it pushes the address of the
                   3043: body of the word and then performs the code after the @code{does>}
                   3044: whenever it is called.
                   3045: 
                   3046: In the example above, @code{constant} uses @code{,} to store 5 into the
                   3047: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   3048: the body onto the stack, then (in the code after the @code{does>})
                   3049: fetches the 5 from there.
                   3050: 
                   3051: The stack comment near the @code{does>} reflects the stack effect of the
                   3052: defined word, not the stack effect of the code after the @code{does>}
                   3053: (the difference is that the code expects the address of the body that
                   3054: the stack comment does not show).
                   3055: 
                   3056: You can use these definition words to do factoring in cases that involve
                   3057: (other) definition words.  E.g., a field offset is always added to an
                   3058: address.  Instead of defining
                   3059: 
                   3060: @example
                   3061: 2 cells constant offset-field1
                   3062: @end example
                   3063: 
                   3064: and using this like
                   3065: 
                   3066: @example
                   3067: ( addr ) offset-field1 +
                   3068: @end example
                   3069: 
                   3070: you can define a definition word
                   3071: 
                   3072: @example
                   3073: : simple-field ( n "name" -- )
                   3074:   create ,
                   3075: does> ( n1 -- n1+n )
1.50      anton    3076:   ( addr ) @@ + ;
1.48      anton    3077: @end example
1.21      crook    3078: 
1.48      anton    3079: Definition and use of field offsets now look like this:
1.21      crook    3080: 
1.48      anton    3081: @example
                   3082: 2 cells simple-field field1
1.60      anton    3083: create mystruct 4 cells allot
                   3084: mystruct .s field1 .s drop
1.48      anton    3085: @end example
1.21      crook    3086: 
1.48      anton    3087: If you want to do something with the word without performing the code
                   3088: after the @code{does>}, you can access the body of a @code{create}d word
                   3089: with @code{>body ( xt -- addr )}:
1.21      crook    3090: 
1.48      anton    3091: @example
                   3092: : value ( n "name" -- )
                   3093:   create ,
                   3094: does> ( -- n1 )
1.50      anton    3095:   @@ ;
1.48      anton    3096: : to ( n "name" -- )
                   3097:   ' >body ! ;
1.21      crook    3098: 
1.48      anton    3099: 5 value foo
                   3100: foo .
                   3101: 7 to foo
                   3102: foo .
                   3103: @end example
1.21      crook    3104: 
1.48      anton    3105: @assignment
                   3106: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   3107: XT (at the start the XT of @code{abort}), and upon execution
                   3108: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   3109: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   3110: recursion is one application of @code{defer}.
                   3111: @endassignment
1.29      crook    3112: 
1.66      anton    3113: Reference: @ref{User-defined Defining Words}.
                   3114: 
                   3115: 
1.48      anton    3116: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   3117: @section Arrays and Records
1.66      anton    3118: @cindex arrays tutorial
                   3119: @cindex records tutorial
                   3120: @cindex structs tutorial
1.29      crook    3121: 
1.48      anton    3122: Forth has no standard words for defining data structures such as arrays
                   3123: and records (structs in C terminology), but you can build them yourself
                   3124: based on address arithmetic.  You can also define words for defining
                   3125: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    3126: 
1.48      anton    3127: One of the first projects a Forth newcomer sets out upon when learning
                   3128: about defining words is an array defining word (possibly for
                   3129: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   3130: learn something from it.  However, don't be disappointed when you later
                   3131: learn that you have little use for these words (inappropriate use would
                   3132: be even worse).  I have not yet found a set of useful array words yet;
                   3133: the needs are just too diverse, and named, global arrays (the result of
                   3134: naive use of defining words) are often not flexible enough (e.g.,
1.66      anton    3135: consider how to pass them as parameters).  Another such project is a set
                   3136: of words to help dealing with strings.
1.29      crook    3137: 
1.48      anton    3138: On the other hand, there is a useful set of record words, and it has
                   3139: been defined in @file{compat/struct.fs}; these words are predefined in
                   3140: Gforth.  They are explained in depth elsewhere in this manual (see
                   3141: @pxref{Structures}).  The @code{simple-field} example above is
                   3142: simplified variant of fields in this package.
1.21      crook    3143: 
                   3144: 
1.48      anton    3145: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   3146: @section @code{POSTPONE}
1.66      anton    3147: @cindex postpone tutorial
1.21      crook    3148: 
1.48      anton    3149: You can compile the compilation semantics (instead of compiling the
                   3150: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    3151: 
1.48      anton    3152: @example
                   3153: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   3154:  POSTPONE + ; immediate
1.48      anton    3155: : foo ( n1 n2 -- n )
                   3156:  MY-+ ;
                   3157: 1 2 foo .
                   3158: see foo
                   3159: @end example
1.21      crook    3160: 
1.48      anton    3161: During the definition of @code{foo} the text interpreter performs the
                   3162: compilation semantics of @code{MY-+}, which performs the compilation
                   3163: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   3164: 
                   3165: This example also displays separate stack comments for the compilation
                   3166: semantics and for the stack effect of the compiled code.  For words with
                   3167: default compilation semantics these stack effects are usually not
                   3168: displayed; the stack effect of the compilation semantics is always
                   3169: @code{( -- )} for these words, the stack effect for the compiled code is
                   3170: the stack effect of the interpretation semantics.
                   3171: 
                   3172: Note that the state of the interpreter does not come into play when
                   3173: performing the compilation semantics in this way.  You can also perform
                   3174: it interpretively, e.g.:
                   3175: 
                   3176: @example
                   3177: : foo2 ( n1 n2 -- n )
                   3178:  [ MY-+ ] ;
                   3179: 1 2 foo .
                   3180: see foo
                   3181: @end example
1.21      crook    3182: 
1.48      anton    3183: However, there are some broken Forth systems where this does not always
1.62      crook    3184: work, and therefore this practice was been declared non-standard in
1.48      anton    3185: 1999.
                   3186: @c !! repair.fs
                   3187: 
                   3188: Here is another example for using @code{POSTPONE}:
1.44      crook    3189: 
1.48      anton    3190: @example
                   3191: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   3192:  POSTPONE negate POSTPONE + ; immediate compile-only
                   3193: : bar ( n1 n2 -- n )
                   3194:   MY-- ;
                   3195: 2 1 bar .
                   3196: see bar
                   3197: @end example
1.21      crook    3198: 
1.48      anton    3199: You can define @code{ENDIF} in this way:
1.21      crook    3200: 
1.48      anton    3201: @example
                   3202: : ENDIF ( Compilation: orig -- )
                   3203:   POSTPONE then ; immediate
                   3204: @end example
1.21      crook    3205: 
1.48      anton    3206: @assignment
                   3207: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   3208: @code{2dup}, but compiles @code{over over}.
                   3209: @endassignment
1.29      crook    3210: 
1.66      anton    3211: @c !! @xref{Macros} for reference
                   3212: 
                   3213: 
1.48      anton    3214: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3215: @section @code{Literal}
1.66      anton    3216: @cindex literal tutorial
1.29      crook    3217: 
1.48      anton    3218: You cannot @code{POSTPONE} numbers:
1.21      crook    3219: 
1.48      anton    3220: @example
                   3221: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3222: @end example
                   3223: 
1.48      anton    3224: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3225: 
1.48      anton    3226: @example
                   3227: : [FOO] ( compilation: --; run-time: -- n )
                   3228:   500 POSTPONE literal ; immediate
1.29      crook    3229: 
1.60      anton    3230: : flip [FOO] ;
1.48      anton    3231: flip .
                   3232: see flip
                   3233: @end example
1.29      crook    3234: 
1.48      anton    3235: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3236: semantics are executed) and pushes it at run-time (when the code it
                   3237: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3238: number computed at compile time into the current word:
1.29      crook    3239: 
1.48      anton    3240: @example
                   3241: : bar ( -- n )
                   3242:   [ 2 2 + ] literal ;
                   3243: see bar
                   3244: @end example
1.29      crook    3245: 
1.48      anton    3246: @assignment
                   3247: Write @code{]L} which allows writing the example above as @code{: bar (
                   3248: -- n ) [ 2 2 + ]L ;}
                   3249: @endassignment
                   3250: 
1.66      anton    3251: @c !! @xref{Macros} for reference
                   3252: 
1.48      anton    3253: 
                   3254: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3255: @section Advanced macros
1.66      anton    3256: @cindex macros, advanced tutorial
                   3257: @cindex run-time code generation, tutorial
1.48      anton    3258: 
1.66      anton    3259: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
                   3260: Execution Tokens}.  It frequently performs @code{execute}, a relatively
                   3261: expensive operation in some Forth implementations.  You can use
1.48      anton    3262: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3263: and produce a word that contains the word to be performed directly:
                   3264: 
                   3265: @c use ]] ... [[
                   3266: @example
                   3267: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3268: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3269: \ array beginning at addr and containing u elements
                   3270:   @{ xt @}
                   3271:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3272:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3273:   1 cells POSTPONE literal POSTPONE +loop ;
                   3274: 
                   3275: : sum-array ( addr u -- n )
                   3276:  0 rot rot [ ' + compile-map-array ] ;
                   3277: see sum-array
                   3278: a 5 sum-array .
                   3279: @end example
                   3280: 
                   3281: You can use the full power of Forth for generating the code; here's an
                   3282: example where the code is generated in a loop:
                   3283: 
                   3284: @example
                   3285: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3286: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3287:   POSTPONE tuck POSTPONE @@
1.48      anton    3288:   POSTPONE literal POSTPONE * POSTPONE +
                   3289:   POSTPONE swap POSTPONE cell+ ;
                   3290: 
                   3291: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3292: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3293:   0 postpone literal postpone swap
                   3294:   [ ' compile-vmul-step compile-map-array ]
                   3295:   postpone drop ;
                   3296: see compile-vmul
                   3297: 
                   3298: : a-vmul ( addr -- n )
1.51      pazsan   3299: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3300:  [ a 5 compile-vmul ] ;
                   3301: see a-vmul
                   3302: a a-vmul .
                   3303: @end example
                   3304: 
                   3305: This example uses @code{compile-map-array} to show off, but you could
1.66      anton    3306: also use @code{map-array} instead (try it now!).
1.48      anton    3307: 
                   3308: You can use this technique for efficient multiplication of large
                   3309: matrices.  In matrix multiplication, you multiply every line of one
                   3310: matrix with every column of the other matrix.  You can generate the code
                   3311: for one line once, and use it for every column.  The only downside of
                   3312: this technique is that it is cumbersome to recover the memory consumed
                   3313: by the generated code when you are done (and in more complicated cases
                   3314: it is not possible portably).
                   3315: 
1.66      anton    3316: @c !! @xref{Macros} for reference
                   3317: 
                   3318: 
1.48      anton    3319: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3320: @section Compilation Tokens
1.66      anton    3321: @cindex compilation tokens, tutorial
                   3322: @cindex CT, tutorial
1.48      anton    3323: 
                   3324: This section is Gforth-specific.  You can skip it.
                   3325: 
                   3326: @code{' word compile,} compiles the interpretation semantics.  For words
                   3327: with default compilation semantics this is the same as performing the
                   3328: compilation semantics.  To represent the compilation semantics of other
                   3329: words (e.g., words like @code{if} that have no interpretation
                   3330: semantics), Gforth has the concept of a compilation token (CT,
                   3331: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3332: You can perform the compilation semantics represented by a CT with
                   3333: @code{execute}:
1.29      crook    3334: 
1.48      anton    3335: @example
                   3336: : foo2 ( n1 n2 -- n )
                   3337:    [ comp' + execute ] ;
                   3338: see foo
                   3339: @end example
1.29      crook    3340: 
1.48      anton    3341: You can compile the compilation semantics represented by a CT with
                   3342: @code{postpone,}:
1.30      anton    3343: 
1.48      anton    3344: @example
                   3345: : foo3 ( -- )
                   3346:   [ comp' + postpone, ] ;
                   3347: see foo3
                   3348: @end example
1.30      anton    3349: 
1.51      pazsan   3350: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3351: @code{comp'} is particularly useful for words that have no
                   3352: interpretation semantics:
1.29      crook    3353: 
1.30      anton    3354: @example
1.48      anton    3355: ' if
1.60      anton    3356: comp' if .s 2drop
1.30      anton    3357: @end example
                   3358: 
1.66      anton    3359: Reference: @ref{Tokens for Words}.
                   3360: 
1.29      crook    3361: 
1.48      anton    3362: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3363: @section Wordlists and Search Order
1.66      anton    3364: @cindex wordlists tutorial
                   3365: @cindex search order, tutorial
1.48      anton    3366: 
                   3367: The dictionary is not just a memory area that allows you to allocate
                   3368: memory with @code{allot}, it also contains the Forth words, arranged in
                   3369: several wordlists.  When searching for a word in a wordlist,
                   3370: conceptually you start searching at the youngest and proceed towards
                   3371: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3372: you define a word with the same name as an older word, the new word
                   3373: shadows the older word.
                   3374: 
                   3375: Which wordlists are searched in which order is determined by the search
                   3376: order.  You can display the search order with @code{order}.  It displays
                   3377: first the search order, starting with the wordlist searched first, then
                   3378: it displays the wordlist that will contain newly defined words.
1.21      crook    3379: 
1.48      anton    3380: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3381: 
1.48      anton    3382: @example
                   3383: wordlist constant mywords
                   3384: @end example
1.21      crook    3385: 
1.48      anton    3386: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3387: defined words (the @emph{current} wordlist):
1.21      crook    3388: 
1.48      anton    3389: @example
                   3390: mywords set-current
                   3391: order
                   3392: @end example
1.26      crook    3393: 
1.48      anton    3394: Gforth does not display a name for the wordlist in @code{mywords}
                   3395: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3396: 
1.48      anton    3397: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3398: you want to put something into a specific wordlist without overall
                   3399: effect on the current wordlist, this typically looks like this:
1.21      crook    3400: 
1.48      anton    3401: @example
                   3402: get-current mywords set-current ( wid )
                   3403: create someword
                   3404: ( wid ) set-current
                   3405: @end example
1.21      crook    3406: 
1.48      anton    3407: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3408: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3409: searched wordlist is topmost.
1.21      crook    3410: 
1.48      anton    3411: @example
                   3412: get-order mywords swap 1+ set-order
                   3413: order
                   3414: @end example
1.21      crook    3415: 
1.48      anton    3416: Yes, the order of wordlists in the output of @code{order} is reversed
                   3417: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3418: 
1.48      anton    3419: @assignment
                   3420: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3421: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3422: removes the first searched wordlist from the search order.  Experiment
                   3423: with boundary conditions (you will see some crashes or situations that
                   3424: are hard or impossible to leave).
                   3425: @endassignment
1.21      crook    3426: 
1.48      anton    3427: The search order is a powerful foundation for providing features similar
                   3428: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3429: programs in this way has disadvantages for debugging and reuse/factoring
                   3430: that overcome the advantages in my experience (I don't do huge projects,
1.55      anton    3431: though).  These disadvantages are not so clear in other
1.48      anton    3432: languages/programming environments, because these langauges are not so
                   3433: strong in debugging and reuse.
1.21      crook    3434: 
1.66      anton    3435: @c !! example
                   3436: 
                   3437: Reference: @ref{Word Lists}.
1.21      crook    3438: 
1.29      crook    3439: @c ******************************************************************
1.48      anton    3440: @node Introduction, Words, Tutorial, Top
1.29      crook    3441: @comment node-name,     next,           previous, up
                   3442: @chapter An Introduction to ANS Forth
                   3443: @cindex Forth - an introduction
1.21      crook    3444: 
1.29      crook    3445: The primary purpose of this manual is to document Gforth. However, since
                   3446: Forth is not a widely-known language and there is a lack of up-to-date
                   3447: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3448: material.  For other sources of Forth-related
                   3449: information, see @ref{Forth-related information}.
1.21      crook    3450: 
1.29      crook    3451: The examples in this section should work on any ANS Forth; the
                   3452: output shown was produced using Gforth. Each example attempts to
                   3453: reproduce the exact output that Gforth produces. If you try out the
                   3454: examples (and you should), what you should type is shown @kbd{like this}
                   3455: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3456: that, where the example shows @key{RET} it means that you should
1.29      crook    3457: press the ``carriage return'' key. Unfortunately, some output formats for
                   3458: this manual cannot show the difference between @kbd{this} and
                   3459: @code{this} which will make trying out the examples harder (but not
                   3460: impossible).
1.21      crook    3461: 
1.29      crook    3462: Forth is an unusual language. It provides an interactive development
                   3463: environment which includes both an interpreter and compiler. Forth
                   3464: programming style encourages you to break a problem down into many
                   3465: @cindex factoring
                   3466: small fragments (@dfn{factoring}), and then to develop and test each
                   3467: fragment interactively. Forth advocates assert that breaking the
                   3468: edit-compile-test cycle used by conventional programming languages can
                   3469: lead to great productivity improvements.
1.21      crook    3470: 
1.29      crook    3471: @menu
1.67      anton    3472: * Introducing the Text Interpreter::  
                   3473: * Stacks and Postfix notation::  
                   3474: * Your first definition::       
                   3475: * How does that work?::         
                   3476: * Forth is written in Forth::   
                   3477: * Review - elements of a Forth system::  
                   3478: * Where to go next::            
                   3479: * Exercises::                   
1.29      crook    3480: @end menu
1.21      crook    3481: 
1.29      crook    3482: @comment ----------------------------------------------
                   3483: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3484: @section Introducing the Text Interpreter
                   3485: @cindex text interpreter
                   3486: @cindex outer interpreter
1.21      crook    3487: 
1.30      anton    3488: @c IMO this is too detailed and the pace is too slow for
                   3489: @c an introduction.  If you know German, take a look at
                   3490: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3491: @c to see how I do it - anton 
                   3492: 
1.44      crook    3493: @c nac-> Where I have accepted your comments 100% and modified the text
                   3494: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3495: @c response like this to attempt to rationalise what I have done. Of
                   3496: @c course, this is a very clumsy mechanism for something that would be
                   3497: @c done far more efficiently over a beer. Please delete any dialogue
                   3498: @c you consider closed.
                   3499: 
1.29      crook    3500: When you invoke the Forth image, you will see a startup banner printed
                   3501: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3502: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3503: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3504: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3505: about the text interpreter as you read through this chapter, for more
                   3506: detail @pxref{The Text Interpreter}).
1.21      crook    3507: 
1.29      crook    3508: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3509: input. Type a number and press the @key{RET} key:
1.21      crook    3510: 
1.26      crook    3511: @example
1.30      anton    3512: @kbd{45@key{RET}}  ok
1.26      crook    3513: @end example
1.21      crook    3514: 
1.29      crook    3515: Rather than give you a prompt to invite you to input something, the text
                   3516: interpreter prints a status message @i{after} it has processed a line
                   3517: of input. The status message in this case (``@code{ ok}'' followed by
                   3518: carriage-return) indicates that the text interpreter was able to process
                   3519: all of your input successfully. Now type something illegal:
                   3520: 
                   3521: @example
1.30      anton    3522: @kbd{qwer341@key{RET}}
1.29      crook    3523: :1: Undefined word
                   3524: qwer341
                   3525: ^^^^^^^
                   3526: $400D2BA8 Bounce
                   3527: $400DBDA8 no.extensions
                   3528: @end example
1.23      crook    3529: 
1.29      crook    3530: The exact text, other than the ``Undefined word'' may differ slightly on
                   3531: your system, but the effect is the same; when the text interpreter
                   3532: detects an error, it discards any remaining text on a line, resets
1.49      anton    3533: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
                   3534: messages}.
1.23      crook    3535: 
1.29      crook    3536: The text interpreter waits for you to press carriage-return, and then
                   3537: processes your input line. Starting at the beginning of the line, it
                   3538: breaks the line into groups of characters separated by spaces. For each
                   3539: group of characters in turn, it makes two attempts to do something:
1.23      crook    3540: 
1.29      crook    3541: @itemize @bullet
                   3542: @item
1.44      crook    3543: @cindex name dictionary
1.29      crook    3544: It tries to treat it as a command. It does this by searching a @dfn{name
                   3545: dictionary}. If the group of characters matches an entry in the name
                   3546: dictionary, the name dictionary provides the text interpreter with
                   3547: information that allows the text interpreter perform some actions. In
                   3548: Forth jargon, we say that the group
                   3549: @cindex word
                   3550: @cindex definition
                   3551: @cindex execution token
                   3552: @cindex xt
                   3553: of characters names a @dfn{word}, that the dictionary search returns an
                   3554: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3555: word, and that the text interpreter executes the xt. Often, the terms
                   3556: @dfn{word} and @dfn{definition} are used interchangeably.
                   3557: @item
                   3558: If the text interpreter fails to find a match in the name dictionary, it
                   3559: tries to treat the group of characters as a number in the current number
                   3560: base (when you start up Forth, the current number base is base 10). If
                   3561: the group of characters legitimately represents a number, the text
                   3562: interpreter pushes the number onto a stack (we'll learn more about that
                   3563: in the next section).
                   3564: @end itemize
1.23      crook    3565: 
1.29      crook    3566: If the text interpreter is unable to do either of these things with any
                   3567: group of characters, it discards the group of characters and the rest of
                   3568: the line, then prints an error message. If the text interpreter reaches
                   3569: the end of the line without error, it prints the status message ``@code{ ok}''
                   3570: followed by carriage-return.
1.21      crook    3571: 
1.29      crook    3572: This is the simplest command we can give to the text interpreter:
1.23      crook    3573: 
                   3574: @example
1.30      anton    3575: @key{RET}  ok
1.23      crook    3576: @end example
1.21      crook    3577: 
1.29      crook    3578: The text interpreter did everything we asked it to do (nothing) without
                   3579: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3580: command:
1.21      crook    3581: 
1.23      crook    3582: @example
1.30      anton    3583: @kbd{12 dup fred dup@key{RET}}
1.29      crook    3584: :1: Undefined word
                   3585: 12 dup fred dup
                   3586:        ^^^^
                   3587: $400D2BA8 Bounce
                   3588: $400DBDA8 no.extensions
1.23      crook    3589: @end example
1.21      crook    3590: 
1.29      crook    3591: When you press the carriage-return key, the text interpreter starts to
                   3592: work its way along the line:
1.21      crook    3593: 
1.29      crook    3594: @itemize @bullet
                   3595: @item
                   3596: When it gets to the space after the @code{2}, it takes the group of
                   3597: characters @code{12} and looks them up in the name
                   3598: dictionary@footnote{We can't tell if it found them or not, but assume
                   3599: for now that it did not}. There is no match for this group of characters
                   3600: in the name dictionary, so it tries to treat them as a number. It is
                   3601: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3602: (whatever that means).
                   3603: @item
                   3604: The text interpreter resumes scanning the line and gets the next group
                   3605: of characters, @code{dup}. It looks it up in the name dictionary and
                   3606: (you'll have to take my word for this) finds it, and executes the word
                   3607: @code{dup} (whatever that means).
                   3608: @item
                   3609: Once again, the text interpreter resumes scanning the line and gets the
                   3610: group of characters @code{fred}. It looks them up in the name
                   3611: dictionary, but can't find them. It tries to treat them as a number, but
                   3612: they don't represent any legal number.
                   3613: @end itemize
1.21      crook    3614: 
1.29      crook    3615: At this point, the text interpreter gives up and prints an error
                   3616: message. The error message shows exactly how far the text interpreter
                   3617: got in processing the line. In particular, it shows that the text
                   3618: interpreter made no attempt to do anything with the final character
                   3619: group, @code{dup}, even though we have good reason to believe that the
                   3620: text interpreter would have no problem looking that word up and
                   3621: executing it a second time.
1.21      crook    3622: 
                   3623: 
1.29      crook    3624: @comment ----------------------------------------------
                   3625: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3626: @section Stacks, postfix notation and parameter passing
                   3627: @cindex text interpreter
                   3628: @cindex outer interpreter
1.21      crook    3629: 
1.29      crook    3630: In procedural programming languages (like C and Pascal), the
                   3631: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3632: functions or procedures are called with @dfn{explicit parameters}. For
                   3633: example, in C we might write:
1.21      crook    3634: 
1.23      crook    3635: @example
1.29      crook    3636: total = total + new_volume(length,height,depth);
1.23      crook    3637: @end example
1.21      crook    3638: 
1.23      crook    3639: @noindent
1.29      crook    3640: where new_volume is a function-call to another piece of code, and total,
                   3641: length, height and depth are all variables. length, height and depth are
                   3642: parameters to the function-call.
1.21      crook    3643: 
1.29      crook    3644: In Forth, the equivalent of the function or procedure is the
                   3645: @dfn{definition} and parameters are implicitly passed between
                   3646: definitions using a shared stack that is visible to the
                   3647: programmer. Although Forth does support variables, the existence of the
                   3648: stack means that they are used far less often than in most other
                   3649: programming languages. When the text interpreter encounters a number, it
                   3650: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3651: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3652: used for any operation is implied unambiguously by the operation being
                   3653: performed. The stack used for all integer operations is called the @dfn{data
                   3654: stack} and, since this is the stack used most commonly, references to
                   3655: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3656: 
1.29      crook    3657: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3658: 
1.23      crook    3659: @example
1.30      anton    3660: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3661: @end example
1.21      crook    3662: 
1.29      crook    3663: Then this instructs the text interpreter to placed three numbers on the
                   3664: (data) stack. An analogy for the behaviour of the stack is to take a
                   3665: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3666: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3667: you take a card off the pile then, unless you're prepared to fiddle a
                   3668: bit, the card that you take off will be the 3 (``first-out''). The
                   3669: number that will be first-out of the stack is called the @dfn{top of
                   3670: stack}, which
                   3671: @cindex TOS definition
                   3672: is often abbreviated to @dfn{TOS}.
1.21      crook    3673: 
1.29      crook    3674: To understand how parameters are passed in Forth, consider the
                   3675: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3676: be surprised to learn that this definition performs addition. More
                   3677: precisely, it adds two number together and produces a result. Where does
                   3678: it get the two numbers from? It takes the top two numbers off the
                   3679: stack. Where does it place the result? On the stack. You can act-out the
                   3680: behaviour of @code{+} with your playing cards like this:
1.21      crook    3681: 
                   3682: @itemize @bullet
                   3683: @item
1.29      crook    3684: Pick up two cards from the stack on the table
1.21      crook    3685: @item
1.29      crook    3686: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3687: numbers''
1.21      crook    3688: @item
1.29      crook    3689: Decide that the answer is 5
1.21      crook    3690: @item
1.29      crook    3691: Shuffle the two cards back into the pack and find a 5
1.21      crook    3692: @item
1.29      crook    3693: Put a 5 on the remaining ace that's on the table.
1.21      crook    3694: @end itemize
                   3695: 
1.29      crook    3696: If you don't have a pack of cards handy but you do have Forth running,
                   3697: you can use the definition @code{.s} to show the current state of the stack,
                   3698: without affecting the stack. Type:
1.21      crook    3699: 
                   3700: @example
1.30      anton    3701: @kbd{clearstack 1 2 3@key{RET}} ok
                   3702: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3703: @end example
                   3704: 
1.29      crook    3705: The text interpreter looks up the word @code{clearstack} and executes
                   3706: it; it tidies up the stack and removes any entries that may have been
                   3707: left on it by earlier examples. The text interpreter pushes each of the
                   3708: three numbers in turn onto the stack. Finally, the text interpreter
                   3709: looks up the word @code{.s} and executes it. The effect of executing
                   3710: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3711: followed by a list of all the items on the stack; the item on the far
                   3712: right-hand side is the TOS.
1.21      crook    3713: 
1.29      crook    3714: You can now type:
1.21      crook    3715: 
1.29      crook    3716: @example
1.30      anton    3717: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3718: @end example
1.21      crook    3719: 
1.29      crook    3720: @noindent
                   3721: which is correct; there are now 2 items on the stack and the result of
                   3722: the addition is 5.
1.23      crook    3723: 
1.29      crook    3724: If you're playing with cards, try doing a second addition: pick up the
                   3725: two cards, work out that their sum is 6, shuffle them into the pack,
                   3726: look for a 6 and place that on the table. You now have just one item on
                   3727: the stack. What happens if you try to do a third addition? Pick up the
                   3728: first card, pick up the second card -- ah! There is no second card. This
                   3729: is called a @dfn{stack underflow} and consitutes an error. If you try to
                   3730: do the same thing with Forth it will report an error (probably a Stack
                   3731: Underflow or an Invalid Memory Address error).
1.23      crook    3732: 
1.29      crook    3733: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3734: which simply accepts that there is a finite amount of storage space
                   3735: reserved for the stack. To stretch the playing card analogy, if you had
                   3736: enough packs of cards and you piled the cards up on the table, you would
                   3737: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3738: allows you to set the maximum size of the stacks. In general, the only
                   3739: time that you will get a stack overflow is because a definition has a
                   3740: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3741: 
1.29      crook    3742: There's one final use for the playing card analogy. If you model your
                   3743: stack using a pack of playing cards, the maximum number of items on
                   3744: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3745: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3746: possible numbers are positive integer numbers 1 through 13; you can't
                   3747: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3748: think about some of the cards, you can accommodate different
                   3749: numbers. For example, you could think of the Jack as representing 0,
                   3750: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3751: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3752: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3753: 
1.29      crook    3754: In that analogy, the limit was the amount of information that a single
                   3755: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3756: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3757: implementation dependent and affects the maximum value that a stack
                   3758: entry can hold. A Standard Forth provides a cell size of at least
                   3759: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3760: 
1.29      crook    3761: Forth does not do any type checking for you, so you are free to
                   3762: manipulate and combine stack items in any way you wish. A convenient way
                   3763: of treating stack items is as 2's complement signed integers, and that
                   3764: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3765: 
1.29      crook    3766: @example
1.30      anton    3767: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3768: @end example
1.21      crook    3769: 
1.29      crook    3770: If you use numbers and definitions like @code{+} in order to turn Forth
                   3771: into a great big pocket calculator, you will realise that it's rather
                   3772: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3773: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3774: result). The terminology used to describe this difference is to say that
                   3775: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3776: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3777: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3778: 
1.29      crook    3779: Whilst postfix notation might look confusing to begin with, it has
                   3780: several important advantages:
1.21      crook    3781: 
1.23      crook    3782: @itemize @bullet
                   3783: @item
1.29      crook    3784: it is unambiguous
1.23      crook    3785: @item
1.29      crook    3786: it is more concise
1.23      crook    3787: @item
1.29      crook    3788: it fits naturally with a stack-based system
1.23      crook    3789: @end itemize
1.21      crook    3790: 
1.29      crook    3791: To examine these claims in more detail, consider these sums:
1.21      crook    3792: 
1.29      crook    3793: @example
                   3794: 6 + 5 * 4 =
                   3795: 4 * 5 + 6 =
                   3796: @end example
1.21      crook    3797: 
1.29      crook    3798: If you're just learning maths or your maths is very rusty, you will
                   3799: probably come up with the answer 44 for the first and 26 for the
                   3800: second. If you are a bit of a whizz at maths you will remember the
                   3801: @i{convention} that multiplication takes precendence over addition, and
                   3802: you'd come up with the answer 26 both times. To explain the answer 26
                   3803: to someone who got the answer 44, you'd probably rewrite the first sum
                   3804: like this:
1.21      crook    3805: 
1.29      crook    3806: @example
                   3807: 6 + (5 * 4) =
                   3808: @end example
1.21      crook    3809: 
1.29      crook    3810: If what you really wanted was to perform the addition before the
                   3811: multiplication, you would have to use parentheses to force it.
1.21      crook    3812: 
1.29      crook    3813: If you did the first two sums on a pocket calculator you would probably
                   3814: get the right answers, unless you were very cautious and entered them using
                   3815: these keystroke sequences:
1.21      crook    3816: 
1.29      crook    3817: 6 + 5 = * 4 =
                   3818: 4 * 5 = + 6 =
1.21      crook    3819: 
1.29      crook    3820: Postfix notation is unambiguous because the order that the operators
                   3821: are applied is always explicit; that also means that parentheses are
                   3822: never required. The operators are @i{active} (the act of quoting the
                   3823: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3824: 
1.29      crook    3825: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3826: equivalent ways:
1.26      crook    3827: 
                   3828: @example
1.29      crook    3829: 6 5 4 * +      or:
                   3830: 5 4 * 6 +
1.26      crook    3831: @end example
1.23      crook    3832: 
1.29      crook    3833: An important thing that you should notice about this notation is that
                   3834: the @i{order} of the numbers does not change; if you want to subtract
                   3835: 2 from 10 you type @code{10 2 -}.
1.1       anton    3836: 
1.29      crook    3837: The reason that Forth uses postfix notation is very simple to explain: it
                   3838: makes the implementation extremely simple, and it follows naturally from
                   3839: using the stack as a mechanism for passing parameters. Another way of
                   3840: thinking about this is to realise that all Forth definitions are
                   3841: @i{active}; they execute as they are encountered by the text
                   3842: interpreter. The result of this is that the syntax of Forth is trivially
                   3843: simple.
1.1       anton    3844: 
                   3845: 
                   3846: 
1.29      crook    3847: @comment ----------------------------------------------
                   3848: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3849: @section Your first Forth definition
                   3850: @cindex first definition
1.1       anton    3851: 
1.29      crook    3852: Until now, the examples we've seen have been trivial; we've just been
                   3853: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3854: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3855: again@footnote{That's not quite true. If you press the up-arrow key on
                   3856: your keyboard you should be able to scroll back to any earlier command,
                   3857: edit it and re-enter it.} In this section we'll see how to add new
                   3858: words to Forth's vocabulary.
1.1       anton    3859: 
1.29      crook    3860: The easiest way to create a new word is to use a @dfn{colon
                   3861: definition}. We'll define a few and try them out before worrying too
                   3862: much about how they work. Try typing in these examples; be careful to
                   3863: copy the spaces accurately:
1.1       anton    3864: 
1.29      crook    3865: @example
                   3866: : add-two 2 + . ;
                   3867: : greet ." Hello and welcome" ;
                   3868: : demo 5 add-two ;
                   3869: @end example
1.1       anton    3870: 
1.29      crook    3871: @noindent
                   3872: Now try them out:
1.1       anton    3873: 
1.29      crook    3874: @example
1.30      anton    3875: @kbd{greet@key{RET}} Hello and welcome  ok
                   3876: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3877: @kbd{4 add-two@key{RET}} 6  ok
                   3878: @kbd{demo@key{RET}} 7  ok
                   3879: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3880: @end example
1.1       anton    3881: 
1.29      crook    3882: The first new thing that we've introduced here is the pair of words
                   3883: @code{:} and @code{;}. These are used to start and terminate a new
                   3884: definition, respectively. The first word after the @code{:} is the name
                   3885: for the new definition.
1.1       anton    3886: 
1.29      crook    3887: As you can see from the examples, a definition is built up of words that
                   3888: have already been defined; Forth makes no distinction between
                   3889: definitions that existed when you started the system up, and those that
                   3890: you define yourself.
1.1       anton    3891: 
1.29      crook    3892: The examples also introduce the words @code{.} (dot), @code{."}
                   3893: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3894: the stack and displays it. It's like @code{.s} except that it only
                   3895: displays the top item of the stack and it is destructive; after it has
                   3896: executed, the number is no longer on the stack. There is always one
                   3897: space printed after the number, and no spaces before it. Dot-quote
                   3898: defines a string (a sequence of characters) that will be printed when
                   3899: the word is executed. The string can contain any printable characters
                   3900: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3901: word but it acts as a delimiter (the way that delimiters work is
                   3902: described in the next section). Finally, @code{dup} duplicates the value
                   3903: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3904: 
1.29      crook    3905: We already know that the text interpreter searches through the
                   3906: dictionary to locate names. If you've followed the examples earlier, you
                   3907: will already have a definition called @code{add-two}. Lets try modifying
                   3908: it by typing in a new definition:
1.1       anton    3909: 
1.29      crook    3910: @example
1.30      anton    3911: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3912: @end example
1.5       anton    3913: 
1.29      crook    3914: Forth recognised that we were defining a word that already exists, and
                   3915: printed a message to warn us of that fact. Let's try out the new
                   3916: definition:
1.5       anton    3917: 
1.29      crook    3918: @example
1.30      anton    3919: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3920: @end example
1.1       anton    3921: 
1.29      crook    3922: @noindent
                   3923: All that we've actually done here, though, is to create a new
                   3924: definition, with a particular name. The fact that there was already a
                   3925: definition with the same name did not make any difference to the way
                   3926: that the new definition was created (except that Forth printed a warning
                   3927: message). The old definition of add-two still exists (try @code{demo}
                   3928: again to see that this is true). Any new definition will use the new
                   3929: definition of @code{add-two}, but old definitions continue to use the
                   3930: version that already existed at the time that they were @code{compiled}.
1.1       anton    3931: 
1.29      crook    3932: Before you go on to the next section, try defining and redefining some
                   3933: words of your own.
1.1       anton    3934: 
1.29      crook    3935: @comment ----------------------------------------------
                   3936: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3937: @section How does that work?
                   3938: @cindex parsing words
1.1       anton    3939: 
1.30      anton    3940: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3941: 
                   3942: @c Is it a good idea to talk about the interpretation semantics of a
                   3943: @c number? We don't have an xt to go along with it. - anton
                   3944: 
                   3945: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3946: @c be better to keep them (or add run-time semantics), to make it easier to
                   3947: @c explain what compilation semantics usually does. - anton
                   3948: 
1.44      crook    3949: @c nac-> I removed the term ``default compilation sematics'' from the
                   3950: @c introductory chapter. Removing ``execution semantics'' was making
                   3951: @c everything simpler to explain, then I think the use of this term made
                   3952: @c everything more complex again. I replaced it with ``default
                   3953: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3954: @c ``a definition that has neither the immediate nor the compile-only
                   3955: @c flag set''. I reworded big chunks of the ``how does that work''
                   3956: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3957: @c what you think -- I know I have not addressed your primary concern
                   3958: @c that it is too heavy-going for an introduction. From what I understood
                   3959: @c of your course notes it looks as though they might be a good framework. 
                   3960: @c Things that I've tried to capture here are some things that came as a
                   3961: @c great revelation here when I first understood them. Also, I like the
                   3962: @c fact that a very simple code example shows up almost all of the issues
                   3963: @c that you need to understand to see how Forth works. That's unique and
                   3964: @c worthwhile to emphasise.
                   3965: 
1.29      crook    3966: Now we're going to take another look at the definition of @code{add-two}
                   3967: from the previous section. From our knowledge of the way that the text
                   3968: interpreter works, we would have expected this result when we tried to
                   3969: define @code{add-two}:
1.21      crook    3970: 
1.29      crook    3971: @example
1.44      crook    3972: @kbd{: add-two 2 + . ;@key{RET}}
1.29      crook    3973:   ^^^^^^^
                   3974: Error: Undefined word
                   3975: @end example
1.28      crook    3976: 
1.29      crook    3977: The reason that this didn't happen is bound up in the way that @code{:}
                   3978: works. The word @code{:} does two special things. The first special
                   3979: thing that it does prevents the text interpreter from ever seeing the
                   3980: characters @code{add-two}. The text interpreter uses a variable called
                   3981: @cindex modifying >IN
1.44      crook    3982: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    3983: input line. When it encounters the word @code{:} it behaves in exactly
                   3984: the same way as it does for any other word; it looks it up in the name
                   3985: dictionary, finds its xt and executes it. When @code{:} executes, it
                   3986: looks at the input buffer, finds the word @code{add-two} and advances the
                   3987: value of @code{>IN} to point past it. It then does some other stuff
                   3988: associated with creating the new definition (including creating an entry
                   3989: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   3990: completes, control returns to the text interpreter, which is oblivious
                   3991: to the fact that it has been tricked into ignoring part of the input
                   3992: line.
1.21      crook    3993: 
1.29      crook    3994: @cindex parsing words
                   3995: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   3996: prevent the text interpreter from acting on the whole of the input line
                   3997: -- are called @dfn{parsing words}.
1.21      crook    3998: 
1.29      crook    3999: @cindex @code{state} - effect on the text interpreter
                   4000: @cindex text interpreter - effect of state
                   4001: The second special thing that @code{:} does is change the value of a
                   4002: variable called @code{state}, which affects the way that the text
                   4003: interpreter behaves. When Gforth starts up, @code{state} has the value
                   4004: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   4005: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    4006: the text interpreter is said to be @dfn{compiling}.
                   4007: 
                   4008: In this example, the text interpreter is compiling when it processes the
                   4009: string ``@code{2 + . ;}''. It still breaks the string down into
                   4010: character sequences in the same way. However, instead of pushing the
                   4011: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   4012: into the definition of @code{add-two} that will make the number @code{2} get
                   4013: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   4014: the behaviours of @code{+} and @code{.} are also compiled into the
                   4015: definition.
                   4016: 
                   4017: One category of words don't get compiled. These so-called @dfn{immediate
                   4018: words} get executed (performed @i{now}) regardless of whether the text
                   4019: interpreter is interpreting or compiling. The word @code{;} is an
                   4020: immediate word. Rather than being compiled into the definition, it
                   4021: executes. Its effect is to terminate the current definition, which
                   4022: includes changing the value of @code{state} back to 0.
                   4023: 
                   4024: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   4025: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   4026: definition.
1.28      crook    4027: 
1.30      anton    4028: In Forth, every word or number can be described in terms of two
1.29      crook    4029: properties:
1.28      crook    4030: 
                   4031: @itemize @bullet
                   4032: @item
1.29      crook    4033: @cindex interpretation semantics
1.44      crook    4034: Its @dfn{interpretation semantics} describe how it will behave when the
                   4035: text interpreter encounters it in @dfn{interpret} state. The
                   4036: interpretation semantics of a word are represented by an @dfn{execution
                   4037: token}.
1.28      crook    4038: @item
1.29      crook    4039: @cindex compilation semantics
1.44      crook    4040: Its @dfn{compilation semantics} describe how it will behave when the
                   4041: text interpreter encounters it in @dfn{compile} state. The compilation
                   4042: semantics of a word are represented in an implementation-dependent way;
                   4043: Gforth uses a @dfn{compilation token}.
1.29      crook    4044: @end itemize
                   4045: 
                   4046: @noindent
                   4047: Numbers are always treated in a fixed way:
                   4048: 
                   4049: @itemize @bullet
1.28      crook    4050: @item
1.44      crook    4051: When the number is @dfn{interpreted}, its behaviour is to push the
                   4052: number onto the stack.
1.28      crook    4053: @item
1.30      anton    4054: When the number is @dfn{compiled}, a piece of code is appended to the
                   4055: current definition that pushes the number when it runs. (In other words,
                   4056: the compilation semantics of a number are to postpone its interpretation
                   4057: semantics until the run-time of the definition that it is being compiled
                   4058: into.)
1.29      crook    4059: @end itemize
                   4060: 
1.44      crook    4061: Words don't behave in such a regular way, but most have @i{default
                   4062: semantics} which means that they behave like this:
1.29      crook    4063: 
                   4064: @itemize @bullet
1.28      crook    4065: @item
1.30      anton    4066: The @dfn{interpretation semantics} of the word are to do something useful.
                   4067: @item
1.29      crook    4068: The @dfn{compilation semantics} of the word are to append its
1.30      anton    4069: @dfn{interpretation semantics} to the current definition (so that its
                   4070: run-time behaviour is to do something useful).
1.28      crook    4071: @end itemize
                   4072: 
1.30      anton    4073: @cindex immediate words
1.44      crook    4074: The actual behaviour of any particular word can be controlled by using
                   4075: the words @code{immediate} and @code{compile-only} when the word is
                   4076: defined. These words set flags in the name dictionary entry of the most
                   4077: recently defined word, and these flags are retrieved by the text
                   4078: interpreter when it finds the word in the name dictionary.
                   4079: 
                   4080: A word that is marked as @dfn{immediate} has compilation semantics that
                   4081: are identical to its interpretation semantics. In other words, it
                   4082: behaves like this:
1.29      crook    4083: 
                   4084: @itemize @bullet
                   4085: @item
1.30      anton    4086: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    4087: @item
1.30      anton    4088: The @dfn{compilation semantics} of the word are to do something useful
                   4089: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    4090: @end itemize
1.28      crook    4091: 
1.44      crook    4092: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   4093: performing the interpretation semantics of the word directly; an attempt
                   4094: to do so will generate an error. It is never necessary to use
                   4095: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   4096: provided by many implementations) but it is good etiquette to apply it
                   4097: to a word that will not behave correctly (and might have unexpected
                   4098: side-effects) in interpret state. For example, it is only legal to use
                   4099: the conditional word @code{IF} within a definition. If you forget this
                   4100: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   4101: @code{compile-only} allows the text interpreter to generate a helpful
                   4102: error message rather than subjecting you to the consequences of your
                   4103: folly.
                   4104: 
1.29      crook    4105: This example shows the difference between an immediate and a
                   4106: non-immediate word:
1.28      crook    4107: 
1.29      crook    4108: @example
                   4109: : show-state state @@ . ;
                   4110: : show-state-now show-state ; immediate
                   4111: : word1 show-state ;
                   4112: : word2 show-state-now ;
1.28      crook    4113: @end example
1.23      crook    4114: 
1.29      crook    4115: The word @code{immediate} after the definition of @code{show-state-now}
                   4116: makes that word an immediate word. These definitions introduce a new
                   4117: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   4118: variable, and leaves it on the stack. Therefore, the behaviour of
                   4119: @code{show-state} is to print a number that represents the current value
                   4120: of @code{state}.
1.28      crook    4121: 
1.29      crook    4122: When you execute @code{word1}, it prints the number 0, indicating that
                   4123: the system is interpreting. When the text interpreter compiled the
                   4124: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    4125: compilation semantics are to append its interpretation semantics to the
1.29      crook    4126: current definition. When you execute @code{word1}, it performs the
1.30      anton    4127: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    4128: (and therefore @code{show-state}) are executed, the system is
                   4129: interpreting.
1.28      crook    4130: 
1.30      anton    4131: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    4132: you should have seen the number -1 printed, followed by ``@code{
                   4133: ok}''. When the text interpreter compiled the definition of
                   4134: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    4135: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4136: semantics. It is executed straight away (even before the text
                   4137: interpreter has moved on to process another group of characters; the
                   4138: @code{;} in this example). The effect of executing it are to display the
                   4139: value of @code{state} @i{at the time that the definition of}
                   4140: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4141: system is compiling at this time. If you execute @code{word2} it does
                   4142: nothing at all.
1.28      crook    4143: 
1.29      crook    4144: @cindex @code{."}, how it works
                   4145: Before leaving the subject of immediate words, consider the behaviour of
                   4146: @code{."} in the definition of @code{greet}, in the previous
                   4147: section. This word is both a parsing word and an immediate word. Notice
                   4148: that there is a space between @code{."} and the start of the text
                   4149: @code{Hello and welcome}, but that there is no space between the last
                   4150: letter of @code{welcome} and the @code{"} character. The reason for this
                   4151: is that @code{."} is a Forth word; it must have a space after it so that
                   4152: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4153: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4154: is displayed, there is neither a space before the @code{H} nor after the
                   4155: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4156: that @code{greet} is defined. When it executes, its behaviour is to
                   4157: search forward in the input line looking for the delimiter. When it
                   4158: finds the delimiter, it updates @code{>IN} to point past the
                   4159: delimiter. It also compiles some magic code into the definition of
                   4160: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4161: compiles the string @code{Hello and welcome} into memory so that it is
                   4162: available to be printed later. When the text interpreter gains control,
                   4163: the next word it finds in the input stream is @code{;} and so it
                   4164: terminates the definition of @code{greet}.
1.28      crook    4165: 
                   4166: 
                   4167: @comment ----------------------------------------------
1.29      crook    4168: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4169: @section Forth is written in Forth
                   4170: @cindex structure of Forth programs
                   4171: 
                   4172: When you start up a Forth compiler, a large number of definitions
                   4173: already exist. In Forth, you develop a new application using bottom-up
                   4174: programming techniques to create new definitions that are defined in
                   4175: terms of existing definitions. As you create each definition you can
                   4176: test and debug it interactively.
                   4177: 
                   4178: If you have tried out the examples in this section, you will probably
                   4179: have typed them in by hand; when you leave Gforth, your definitions will
                   4180: be lost. You can avoid this by using a text editor to enter Forth source
                   4181: code into a file, and then loading code from the file using
1.49      anton    4182: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    4183: processed by the text interpreter, just as though you had typed it in by
                   4184: hand@footnote{Actually, there are some subtle differences -- see
                   4185: @ref{The Text Interpreter}.}.
                   4186: 
                   4187: Gforth also supports the traditional Forth alternative to using text
1.49      anton    4188: files for program entry (@pxref{Blocks}).
1.28      crook    4189: 
1.29      crook    4190: In common with many, if not most, Forth compilers, most of Gforth is
                   4191: actually written in Forth. All of the @file{.fs} files in the
                   4192: installation directory@footnote{For example,
1.30      anton    4193: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4194: study to see examples of Forth programming.
1.28      crook    4195: 
1.29      crook    4196: Gforth maintains a history file that records every line that you type to
                   4197: the text interpreter. This file is preserved between sessions, and is
                   4198: used to provide a command-line recall facility. If you enter long
                   4199: definitions by hand, you can use a text editor to paste them out of the
                   4200: history file into a Forth source file for reuse at a later time
1.49      anton    4201: (for more information @pxref{Command-line editing}).
1.28      crook    4202: 
                   4203: 
                   4204: @comment ----------------------------------------------
1.29      crook    4205: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4206: @section Review - elements of a Forth system
                   4207: @cindex elements of a Forth system
1.28      crook    4208: 
1.29      crook    4209: To summarise this chapter:
1.28      crook    4210: 
                   4211: @itemize @bullet
                   4212: @item
1.29      crook    4213: Forth programs use @dfn{factoring} to break a problem down into small
                   4214: fragments called @dfn{words} or @dfn{definitions}.
                   4215: @item
                   4216: Forth program development is an interactive process.
                   4217: @item
                   4218: The main command loop that accepts input, and controls both
                   4219: interpretation and compilation, is called the @dfn{text interpreter}
                   4220: (also known as the @dfn{outer interpreter}).
                   4221: @item
                   4222: Forth has a very simple syntax, consisting of words and numbers
                   4223: separated by spaces or carriage-return characters. Any additional syntax
                   4224: is imposed by @dfn{parsing words}.
                   4225: @item
                   4226: Forth uses a stack to pass parameters between words. As a result, it
                   4227: uses postfix notation.
                   4228: @item
                   4229: To use a word that has previously been defined, the text interpreter
                   4230: searches for the word in the @dfn{name dictionary}.
                   4231: @item
1.30      anton    4232: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4233: @item
1.29      crook    4234: The text interpreter uses the value of @code{state} to select between
                   4235: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4236: semantics} of a word that it encounters.
1.28      crook    4237: @item
1.30      anton    4238: The relationship between the @dfn{interpretation semantics} and
                   4239: @dfn{compilation semantics} for a word
1.29      crook    4240: depend upon the way in which the word was defined (for example, whether
                   4241: it is an @dfn{immediate} word).
1.28      crook    4242: @item
1.29      crook    4243: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4244: definitions}) or in some other way (usually a lower-level language and
                   4245: as a result often called @dfn{low-level definitions}, @dfn{code
                   4246: definitions} or @dfn{primitives}).
1.28      crook    4247: @item
1.29      crook    4248: Many Forth systems are implemented mainly in Forth.
1.28      crook    4249: @end itemize
                   4250: 
                   4251: 
1.29      crook    4252: @comment ----------------------------------------------
1.48      anton    4253: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4254: @section Where To Go Next
                   4255: @cindex where to go next
1.28      crook    4256: 
1.29      crook    4257: Amazing as it may seem, if you have read (and understood) this far, you
                   4258: know almost all the fundamentals about the inner workings of a Forth
                   4259: system. You certainly know enough to be able to read and understand the
                   4260: rest of this manual and the ANS Forth document, to learn more about the
                   4261: facilities that Forth in general and Gforth in particular provide. Even
                   4262: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4263: However, that's not a good idea just yet... better to try writing some
1.29      crook    4264: programs in Gforth.
1.28      crook    4265: 
1.29      crook    4266: Forth has such a rich vocabulary that it can be hard to know where to
                   4267: start in learning it. This section suggests a few sets of words that are
                   4268: enough to write small but useful programs. Use the word index in this
                   4269: document to learn more about each word, then try it out and try to write
                   4270: small definitions using it. Start by experimenting with these words:
1.28      crook    4271: 
                   4272: @itemize @bullet
                   4273: @item
1.29      crook    4274: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4275: @item
                   4276: Comparison: @code{MIN MAX =}
                   4277: @item
                   4278: Logic: @code{AND OR XOR NOT}
                   4279: @item
                   4280: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4281: @item
1.29      crook    4282: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4283: @item
1.29      crook    4284: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4285: @item
1.29      crook    4286: Defining words: @code{: ; CREATE}
1.28      crook    4287: @item
1.29      crook    4288: Memory allocation words: @code{ALLOT ,}
1.28      crook    4289: @item
1.29      crook    4290: Tools: @code{SEE WORDS .S MARKER}
                   4291: @end itemize
                   4292: 
                   4293: When you have mastered those, go on to:
                   4294: 
                   4295: @itemize @bullet
1.28      crook    4296: @item
1.29      crook    4297: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4298: @item
1.29      crook    4299: Memory access: @code{@@ !}
1.28      crook    4300: @end itemize
1.23      crook    4301: 
1.29      crook    4302: When you have mastered these, there's nothing for it but to read through
                   4303: the whole of this manual and find out what you've missed.
                   4304: 
                   4305: @comment ----------------------------------------------
1.48      anton    4306: @node Exercises,  , Where to go next, Introduction
1.29      crook    4307: @section Exercises
                   4308: @cindex exercises
                   4309: 
                   4310: TODO: provide a set of programming excercises linked into the stuff done
                   4311: already and into other sections of the manual. Provide solutions to all
                   4312: the exercises in a .fs file in the distribution.
                   4313: 
                   4314: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4315: 
                   4316: @c excercises:
                   4317: @c 1. take inches and convert to feet and inches.
                   4318: @c 2. take temperature and convert from fahrenheight to celcius;
                   4319: @c    may need to care about symmetric vs floored??
                   4320: @c 3. take input line and do character substitution
                   4321: @c    to encipher or decipher
                   4322: @c 4. as above but work on a file for in and out
                   4323: @c 5. take input line and convert to pig-latin 
                   4324: @c
                   4325: @c thing of sets of things to exercise then come up with
                   4326: @c problems that need those things.
                   4327: 
                   4328: 
1.26      crook    4329: @c ******************************************************************
1.29      crook    4330: @node Words, Error messages, Introduction, Top
1.1       anton    4331: @chapter Forth Words
1.26      crook    4332: @cindex words
1.1       anton    4333: 
                   4334: @menu
                   4335: * Notation::                    
1.65      anton    4336: * Case insensitivity::          
                   4337: * Comments::                    
                   4338: * Boolean Flags::               
1.1       anton    4339: * Arithmetic::                  
                   4340: * Stack Manipulation::          
1.5       anton    4341: * Memory::                      
1.1       anton    4342: * Control Structures::          
                   4343: * Defining Words::              
1.65      anton    4344: * Interpretation and Compilation Semantics::  
1.47      crook    4345: * Tokens for Words::            
1.65      anton    4346: * The Text Interpreter::        
                   4347: * Word Lists::                  
                   4348: * Environmental Queries::       
1.12      anton    4349: * Files::                       
                   4350: * Blocks::                      
                   4351: * Other I/O::                   
1.78      anton    4352: * Locals::                      
                   4353: * Structures::                  
                   4354: * Object-oriented Forth::       
1.12      anton    4355: * Programming Tools::           
                   4356: * Assembler and Code Words::    
                   4357: * Threading Words::             
1.65      anton    4358: * Passing Commands to the OS::  
                   4359: * Keeping track of Time::       
                   4360: * Miscellaneous Words::         
1.1       anton    4361: @end menu
                   4362: 
1.65      anton    4363: @node Notation, Case insensitivity, Words, Words
1.1       anton    4364: @section Notation
                   4365: @cindex notation of glossary entries
                   4366: @cindex format of glossary entries
                   4367: @cindex glossary notation format
                   4368: @cindex word glossary entry format
                   4369: 
                   4370: The Forth words are described in this section in the glossary notation
1.67      anton    4371: that has become a de-facto standard for Forth texts:
1.1       anton    4372: 
                   4373: @format
1.29      crook    4374: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4375: @end format
1.29      crook    4376: @i{Description}
1.1       anton    4377: 
                   4378: @table @var
                   4379: @item word
1.28      crook    4380: The name of the word.
1.1       anton    4381: 
                   4382: @item Stack effect
                   4383: @cindex stack effect
1.29      crook    4384: The stack effect is written in the notation @code{@i{before} --
                   4385: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4386: stack entries before and after the execution of the word. The rest of
                   4387: the stack is not touched by the word. The top of stack is rightmost,
                   4388: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4389: uses a separate floating point stack, but a unified stack
1.29      crook    4390: notation. Also, return stack effects are not shown in @i{stack
                   4391: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4392: the type and/or the function of the item. See below for a discussion of
                   4393: the types.
                   4394: 
                   4395: All words have two stack effects: A compile-time stack effect and a
                   4396: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4397: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4398: this standard behaviour, or the word does other unusual things at
                   4399: compile time, both stack effects are shown; otherwise only the run-time
                   4400: stack effect is shown.
                   4401: 
                   4402: @cindex pronounciation of words
                   4403: @item pronunciation
                   4404: How the word is pronounced.
                   4405: 
                   4406: @cindex wordset
1.67      anton    4407: @cindex environment wordset
1.1       anton    4408: @item wordset
1.21      crook    4409: The ANS Forth standard is divided into several word sets. A standard
                   4410: system need not support all of them. Therefore, in theory, the fewer
                   4411: word sets your program uses the more portable it will be. However, we
                   4412: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4413: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4414: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4415: describes words that will work in future releases of Gforth;
                   4416: @code{gforth-internal} words are more volatile. Environmental query
                   4417: strings are also displayed like words; you can recognize them by the
1.21      crook    4418: @code{environment} in the word set field.
1.1       anton    4419: 
                   4420: @item Description
                   4421: A description of the behaviour of the word.
                   4422: @end table
                   4423: 
                   4424: @cindex types of stack items
                   4425: @cindex stack item types
                   4426: The type of a stack item is specified by the character(s) the name
                   4427: starts with:
                   4428: 
                   4429: @table @code
                   4430: @item f
                   4431: @cindex @code{f}, stack item type
                   4432: Boolean flags, i.e. @code{false} or @code{true}.
                   4433: @item c
                   4434: @cindex @code{c}, stack item type
                   4435: Char
                   4436: @item w
                   4437: @cindex @code{w}, stack item type
                   4438: Cell, can contain an integer or an address
                   4439: @item n
                   4440: @cindex @code{n}, stack item type
                   4441: signed integer
                   4442: @item u
                   4443: @cindex @code{u}, stack item type
                   4444: unsigned integer
                   4445: @item d
                   4446: @cindex @code{d}, stack item type
                   4447: double sized signed integer
                   4448: @item ud
                   4449: @cindex @code{ud}, stack item type
                   4450: double sized unsigned integer
                   4451: @item r
                   4452: @cindex @code{r}, stack item type
                   4453: Float (on the FP stack)
1.21      crook    4454: @item a-
1.1       anton    4455: @cindex @code{a_}, stack item type
                   4456: Cell-aligned address
1.21      crook    4457: @item c-
1.1       anton    4458: @cindex @code{c_}, stack item type
                   4459: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4460: @item f-
1.1       anton    4461: @cindex @code{f_}, stack item type
                   4462: Float-aligned address
1.21      crook    4463: @item df-
1.1       anton    4464: @cindex @code{df_}, stack item type
                   4465: Address aligned for IEEE double precision float
1.21      crook    4466: @item sf-
1.1       anton    4467: @cindex @code{sf_}, stack item type
                   4468: Address aligned for IEEE single precision float
                   4469: @item xt
                   4470: @cindex @code{xt}, stack item type
                   4471: Execution token, same size as Cell
                   4472: @item wid
                   4473: @cindex @code{wid}, stack item type
1.21      crook    4474: Word list ID, same size as Cell
1.68      anton    4475: @item ior, wior
                   4476: @cindex ior type description
                   4477: @cindex wior type description
                   4478: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
1.1       anton    4479: @item f83name
                   4480: @cindex @code{f83name}, stack item type
                   4481: Pointer to a name structure
                   4482: @item "
                   4483: @cindex @code{"}, stack item type
1.12      anton    4484: string in the input stream (not on the stack). The terminating character
                   4485: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4486: quotes.
                   4487: @end table
                   4488: 
1.65      anton    4489: @comment ----------------------------------------------
                   4490: @node Case insensitivity, Comments, Notation, Words
                   4491: @section Case insensitivity
                   4492: @cindex case sensitivity
                   4493: @cindex upper and lower case
                   4494: 
                   4495: Gforth is case-insensitive; you can enter definitions and invoke
                   4496: Standard words using upper, lower or mixed case (however,
                   4497: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   4498: options}).
                   4499: 
                   4500: ANS Forth only @i{requires} implementations to recognise Standard words
                   4501: when they are typed entirely in upper case. Therefore, a Standard
                   4502: program must use upper case for all Standard words. You can use whatever
                   4503: case you like for words that you define, but in a Standard program you
                   4504: have to use the words in the same case that you defined them.
                   4505: 
                   4506: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   4507: wordlists, @pxref{Word Lists}).
                   4508: 
                   4509: Two people have asked how to convert Gforth to be case-sensitive; while
                   4510: we think this is a bad idea, you can change all wordlists into tables
                   4511: like this:
                   4512: 
                   4513: @example
                   4514: ' table-find forth-wordlist wordlist-map @ !
                   4515: @end example
                   4516: 
                   4517: Note that you now have to type the predefined words in the same case
                   4518: that we defined them, which are varying.  You may want to convert them
                   4519: to your favourite case before doing this operation (I won't explain how,
                   4520: because if you are even contemplating doing this, you'd better have
                   4521: enough knowledge of Forth systems to know this already).
                   4522: 
                   4523: @node Comments, Boolean Flags, Case insensitivity, Words
1.21      crook    4524: @section Comments
1.26      crook    4525: @cindex comments
1.21      crook    4526: 
1.29      crook    4527: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4528: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4529: 
1.44      crook    4530: 
1.23      crook    4531: doc-(
1.21      crook    4532: doc-\
1.23      crook    4533: doc-\G
1.21      crook    4534: 
1.44      crook    4535: 
1.21      crook    4536: @node Boolean Flags, Arithmetic, Comments, Words
                   4537: @section Boolean Flags
1.26      crook    4538: @cindex Boolean flags
1.21      crook    4539: 
                   4540: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4541: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4542: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4543: a cell that has @i{any} bit set as @code{true}.
1.67      anton    4544: @c on and off to Memory? 
                   4545: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44      crook    4546: 
1.21      crook    4547: doc-true
                   4548: doc-false
1.29      crook    4549: doc-on
                   4550: doc-off
1.21      crook    4551: 
1.44      crook    4552: 
1.21      crook    4553: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4554: @section Arithmetic
                   4555: @cindex arithmetic words
                   4556: 
                   4557: @cindex division with potentially negative operands
                   4558: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4559: overflow on addition or multiplication, you may hear about division by
                   4560: zero if you are lucky. The operator is written after the operands, but
                   4561: the operands are still in the original order. I.e., the infix @code{2-1}
                   4562: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4563: operators. If you perform division with potentially negative operands,
                   4564: you do not want to use @code{/} or @code{/mod} with its undefined
                   4565: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4566: former, @pxref{Mixed precision}).
1.26      crook    4567: @comment TODO discuss the different division forms and the std approach
1.1       anton    4568: 
                   4569: @menu
                   4570: * Single precision::            
1.67      anton    4571: * Double precision::            Double-cell integer arithmetic
1.1       anton    4572: * Bitwise operations::          
1.67      anton    4573: * Numeric comparison::          
1.29      crook    4574: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4575: * Floating Point::              
                   4576: @end menu
                   4577: 
1.67      anton    4578: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1       anton    4579: @subsection Single precision
                   4580: @cindex single precision arithmetic words
                   4581: 
1.67      anton    4582: @c !! cell undefined
                   4583: 
                   4584: By default, numbers in Forth are single-precision integers that are one
1.26      crook    4585: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4586: treat them. For the rules used by the text interpreter for recognising
                   4587: single-precision integers see @ref{Number Conversion}.
1.21      crook    4588: 
1.67      anton    4589: These words are all defined for signed operands, but some of them also
                   4590: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
                   4591: @code{*}.
1.44      crook    4592: 
1.1       anton    4593: doc-+
1.21      crook    4594: doc-1+
1.1       anton    4595: doc--
1.21      crook    4596: doc-1-
1.1       anton    4597: doc-*
                   4598: doc-/
                   4599: doc-mod
                   4600: doc-/mod
                   4601: doc-negate
                   4602: doc-abs
                   4603: doc-min
                   4604: doc-max
1.27      crook    4605: doc-floored
1.1       anton    4606: 
1.44      crook    4607: 
1.67      anton    4608: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21      crook    4609: @subsection Double precision
                   4610: @cindex double precision arithmetic words
                   4611: 
1.49      anton    4612: For the rules used by the text interpreter for
                   4613: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4614: 
                   4615: A double precision number is represented by a cell pair, with the most
1.67      anton    4616: significant cell at the TOS. It is trivial to convert an unsigned single
                   4617: to a double: simply push a @code{0} onto the TOS. Since numbers are
                   4618: represented by Gforth using 2's complement arithmetic, converting a
                   4619: signed single to a (signed) double requires sign-extension across the
                   4620: most significant cell. This can be achieved using @code{s>d}. The moral
                   4621: of the story is that you cannot convert a number without knowing whether
                   4622: it represents an unsigned or a signed number.
1.21      crook    4623: 
1.67      anton    4624: These words are all defined for signed operands, but some of them also
                   4625: work for unsigned numbers: @code{d+}, @code{d-}.
1.44      crook    4626: 
1.21      crook    4627: doc-s>d
1.67      anton    4628: doc-d>s
1.21      crook    4629: doc-d+
                   4630: doc-d-
                   4631: doc-dnegate
                   4632: doc-dabs
                   4633: doc-dmin
                   4634: doc-dmax
                   4635: 
1.44      crook    4636: 
1.67      anton    4637: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
                   4638: @subsection Bitwise operations
                   4639: @cindex bitwise operation words
                   4640: 
                   4641: 
                   4642: doc-and
                   4643: doc-or
                   4644: doc-xor
                   4645: doc-invert
                   4646: doc-lshift
                   4647: doc-rshift
                   4648: doc-2*
                   4649: doc-d2*
                   4650: doc-2/
                   4651: doc-d2/
                   4652: 
                   4653: 
                   4654: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21      crook    4655: @subsection Numeric comparison
                   4656: @cindex numeric comparison words
                   4657: 
1.67      anton    4658: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
                   4659: d0= d0<>}) work for for both signed and unsigned numbers.
1.44      crook    4660: 
1.28      crook    4661: doc-<
                   4662: doc-<=
                   4663: doc-<>
                   4664: doc-=
                   4665: doc->
                   4666: doc->=
                   4667: 
1.21      crook    4668: doc-0<
1.23      crook    4669: doc-0<=
1.21      crook    4670: doc-0<>
                   4671: doc-0=
1.23      crook    4672: doc-0>
                   4673: doc-0>=
1.28      crook    4674: 
                   4675: doc-u<
                   4676: doc-u<=
1.44      crook    4677: @c u<> and u= exist but are the same as <> and =
1.31      anton    4678: @c doc-u<>
                   4679: @c doc-u=
1.28      crook    4680: doc-u>
                   4681: doc-u>=
                   4682: 
                   4683: doc-within
                   4684: 
                   4685: doc-d<
                   4686: doc-d<=
                   4687: doc-d<>
                   4688: doc-d=
                   4689: doc-d>
                   4690: doc-d>=
1.23      crook    4691: 
1.21      crook    4692: doc-d0<
1.23      crook    4693: doc-d0<=
                   4694: doc-d0<>
1.21      crook    4695: doc-d0=
1.23      crook    4696: doc-d0>
                   4697: doc-d0>=
                   4698: 
1.21      crook    4699: doc-du<
1.28      crook    4700: doc-du<=
1.44      crook    4701: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4702: @c doc-du<>
                   4703: @c doc-du=
1.28      crook    4704: doc-du>
                   4705: doc-du>=
1.1       anton    4706: 
1.44      crook    4707: 
1.21      crook    4708: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4709: @subsection Mixed precision
                   4710: @cindex mixed precision arithmetic words
                   4711: 
1.44      crook    4712: 
1.1       anton    4713: doc-m+
                   4714: doc-*/
                   4715: doc-*/mod
                   4716: doc-m*
                   4717: doc-um*
                   4718: doc-m*/
                   4719: doc-um/mod
                   4720: doc-fm/mod
                   4721: doc-sm/rem
                   4722: 
1.44      crook    4723: 
1.21      crook    4724: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4725: @subsection Floating Point
                   4726: @cindex floating point arithmetic words
                   4727: 
1.49      anton    4728: For the rules used by the text interpreter for
                   4729: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4730: 
1.67      anton    4731: Gforth has a separate floating point stack, but the documentation uses
                   4732: the unified notation.@footnote{It's easy to generate the separate
                   4733: notation from that by just separating the floating-point numbers out:
                   4734: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
                   4735: r3 )}.}
1.1       anton    4736: 
                   4737: @cindex floating-point arithmetic, pitfalls
                   4738: Floating point numbers have a number of unpleasant surprises for the
                   4739: unwary (e.g., floating point addition is not associative) and even a few
                   4740: for the wary. You should not use them unless you know what you are doing
                   4741: or you don't care that the results you get are totally bogus. If you
                   4742: want to learn about the problems of floating point numbers (and how to
1.66      anton    4743: avoid them), you might start with @cite{David Goldberg,
                   4744: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
                   4745: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
                   4746: Surveys 23(1):5@minus{}48, March 1991}.
1.1       anton    4747: 
1.44      crook    4748: 
1.21      crook    4749: doc-d>f
                   4750: doc-f>d
1.1       anton    4751: doc-f+
                   4752: doc-f-
                   4753: doc-f*
                   4754: doc-f/
                   4755: doc-fnegate
                   4756: doc-fabs
                   4757: doc-fmax
                   4758: doc-fmin
                   4759: doc-floor
                   4760: doc-fround
                   4761: doc-f**
                   4762: doc-fsqrt
                   4763: doc-fexp
                   4764: doc-fexpm1
                   4765: doc-fln
                   4766: doc-flnp1
                   4767: doc-flog
                   4768: doc-falog
1.32      anton    4769: doc-f2*
                   4770: doc-f2/
                   4771: doc-1/f
                   4772: doc-precision
                   4773: doc-set-precision
                   4774: 
                   4775: @cindex angles in trigonometric operations
                   4776: @cindex trigonometric operations
                   4777: Angles in floating point operations are given in radians (a full circle
                   4778: has 2 pi radians).
                   4779: 
1.1       anton    4780: doc-fsin
                   4781: doc-fcos
                   4782: doc-fsincos
                   4783: doc-ftan
                   4784: doc-fasin
                   4785: doc-facos
                   4786: doc-fatan
                   4787: doc-fatan2
                   4788: doc-fsinh
                   4789: doc-fcosh
                   4790: doc-ftanh
                   4791: doc-fasinh
                   4792: doc-facosh
                   4793: doc-fatanh
1.21      crook    4794: doc-pi
1.28      crook    4795: 
1.32      anton    4796: @cindex equality of floats
                   4797: @cindex floating-point comparisons
1.31      anton    4798: One particular problem with floating-point arithmetic is that comparison
                   4799: for equality often fails when you would expect it to succeed.  For this
                   4800: reason approximate equality is often preferred (but you still have to
1.67      anton    4801: know what you are doing).  Also note that IEEE NaNs may compare
1.68      anton    4802: differently from what you might expect.  The comparison words are:
1.31      anton    4803: 
                   4804: doc-f~rel
                   4805: doc-f~abs
1.68      anton    4806: doc-f~
1.31      anton    4807: doc-f=
                   4808: doc-f<>
                   4809: 
                   4810: doc-f<
                   4811: doc-f<=
                   4812: doc-f>
                   4813: doc-f>=
                   4814: 
1.21      crook    4815: doc-f0<
1.28      crook    4816: doc-f0<=
                   4817: doc-f0<>
1.21      crook    4818: doc-f0=
1.28      crook    4819: doc-f0>
                   4820: doc-f0>=
                   4821: 
1.1       anton    4822: 
                   4823: @node Stack Manipulation, Memory, Arithmetic, Words
                   4824: @section Stack Manipulation
                   4825: @cindex stack manipulation words
                   4826: 
                   4827: @cindex floating-point stack in the standard
1.21      crook    4828: Gforth maintains a number of separate stacks:
                   4829: 
1.29      crook    4830: @cindex data stack
                   4831: @cindex parameter stack
1.21      crook    4832: @itemize @bullet
                   4833: @item
1.29      crook    4834: A data stack (also known as the @dfn{parameter stack}) -- for
                   4835: characters, cells, addresses, and double cells.
1.21      crook    4836: 
1.29      crook    4837: @cindex floating-point stack
1.21      crook    4838: @item
1.44      crook    4839: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4840: 
1.29      crook    4841: @cindex return stack
1.21      crook    4842: @item
1.44      crook    4843: A return stack -- for holding the return addresses of colon
1.32      anton    4844: definitions and other (non-FP) data.
1.21      crook    4845: 
1.29      crook    4846: @cindex locals stack
1.21      crook    4847: @item
1.44      crook    4848: A locals stack -- for holding local variables.
1.21      crook    4849: @end itemize
                   4850: 
1.1       anton    4851: @menu
                   4852: * Data stack::                  
                   4853: * Floating point stack::        
                   4854: * Return stack::                
                   4855: * Locals stack::                
                   4856: * Stack pointer manipulation::  
                   4857: @end menu
                   4858: 
                   4859: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4860: @subsection Data stack
                   4861: @cindex data stack manipulation words
                   4862: @cindex stack manipulations words, data stack
                   4863: 
1.44      crook    4864: 
1.1       anton    4865: doc-drop
                   4866: doc-nip
                   4867: doc-dup
                   4868: doc-over
                   4869: doc-tuck
                   4870: doc-swap
1.21      crook    4871: doc-pick
1.1       anton    4872: doc-rot
                   4873: doc--rot
                   4874: doc-?dup
                   4875: doc-roll
                   4876: doc-2drop
                   4877: doc-2nip
                   4878: doc-2dup
                   4879: doc-2over
                   4880: doc-2tuck
                   4881: doc-2swap
                   4882: doc-2rot
                   4883: 
1.44      crook    4884: 
1.1       anton    4885: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4886: @subsection Floating point stack
                   4887: @cindex floating-point stack manipulation words
                   4888: @cindex stack manipulation words, floating-point stack
                   4889: 
1.32      anton    4890: Whilst every sane Forth has a separate floating-point stack, it is not
                   4891: strictly required; an ANS Forth system could theoretically keep
                   4892: floating-point numbers on the data stack. As an additional difficulty,
                   4893: you don't know how many cells a floating-point number takes. It is
                   4894: reportedly possible to write words in a way that they work also for a
                   4895: unified stack model, but we do not recommend trying it. Instead, just
                   4896: say that your program has an environmental dependency on a separate
                   4897: floating-point stack.
                   4898: 
                   4899: doc-floating-stack
                   4900: 
1.1       anton    4901: doc-fdrop
                   4902: doc-fnip
                   4903: doc-fdup
                   4904: doc-fover
                   4905: doc-ftuck
                   4906: doc-fswap
1.21      crook    4907: doc-fpick
1.1       anton    4908: doc-frot
                   4909: 
1.44      crook    4910: 
1.1       anton    4911: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4912: @subsection Return stack
                   4913: @cindex return stack manipulation words
                   4914: @cindex stack manipulation words, return stack
                   4915: 
1.32      anton    4916: @cindex return stack and locals
                   4917: @cindex locals and return stack
                   4918: A Forth system is allowed to keep local variables on the
                   4919: return stack. This is reasonable, as local variables usually eliminate
                   4920: the need to use the return stack explicitly. So, if you want to produce
                   4921: a standard compliant program and you are using local variables in a
                   4922: word, forget about return stack manipulations in that word (refer to the
                   4923: standard document for the exact rules).
                   4924: 
1.1       anton    4925: doc->r
                   4926: doc-r>
                   4927: doc-r@
                   4928: doc-rdrop
                   4929: doc-2>r
                   4930: doc-2r>
                   4931: doc-2r@
                   4932: doc-2rdrop
                   4933: 
1.44      crook    4934: 
1.1       anton    4935: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4936: @subsection Locals stack
                   4937: 
1.78      anton    4938: Gforth uses an extra locals stack.  It is described, along with the
                   4939: reasons for its existence, in @ref{Locals implementation}.
1.21      crook    4940: 
1.1       anton    4941: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4942: @subsection Stack pointer manipulation
                   4943: @cindex stack pointer manipulation words
                   4944: 
1.44      crook    4945: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    4946: doc-sp0
1.1       anton    4947: doc-sp@
                   4948: doc-sp!
1.21      crook    4949: doc-fp0
1.1       anton    4950: doc-fp@
                   4951: doc-fp!
1.21      crook    4952: doc-rp0
1.1       anton    4953: doc-rp@
                   4954: doc-rp!
1.21      crook    4955: doc-lp0
1.1       anton    4956: doc-lp@
                   4957: doc-lp!
                   4958: 
1.44      crook    4959: 
1.1       anton    4960: @node Memory, Control Structures, Stack Manipulation, Words
                   4961: @section Memory
1.26      crook    4962: @cindex memory words
1.1       anton    4963: 
1.32      anton    4964: @menu
                   4965: * Memory model::                
                   4966: * Dictionary allocation::       
                   4967: * Heap Allocation::             
                   4968: * Memory Access::               
                   4969: * Address arithmetic::          
                   4970: * Memory Blocks::               
                   4971: @end menu
                   4972: 
1.67      anton    4973: In addition to the standard Forth memory allocation words, there is also
                   4974: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   4975: garbage collector}.
                   4976: 
1.32      anton    4977: @node Memory model, Dictionary allocation, Memory, Memory
                   4978: @subsection ANS Forth and Gforth memory models
                   4979: 
                   4980: @c The ANS Forth description is a mess (e.g., is the heap part of
                   4981: @c the dictionary?), so let's not stick to closely with it.
                   4982: 
1.67      anton    4983: ANS Forth considers a Forth system as consisting of several address
                   4984: spaces, of which only @dfn{data space} is managed and accessible with
                   4985: the memory words.  Memory not necessarily in data space includes the
                   4986: stacks, the code (called code space) and the headers (called name
                   4987: space). In Gforth everything is in data space, but the code for the
                   4988: primitives is usually read-only.
1.32      anton    4989: 
                   4990: Data space is divided into a number of areas: The (data space portion of
                   4991: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   4992: refer to the search data structure embodied in word lists and headers,
                   4993: because it is used for looking up names, just as you would in a
                   4994: conventional dictionary.}, the heap, and a number of system-allocated
                   4995: buffers.
                   4996: 
1.68      anton    4997: @cindex address arithmetic restrictions, ANS vs. Gforth
                   4998: @cindex contiguous regions, ANS vs. Gforth
1.32      anton    4999: In ANS Forth data space is also divided into contiguous regions.  You
                   5000: can only use address arithmetic within a contiguous region, not between
                   5001: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    5002: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    5003: allocation}).
                   5004: 
                   5005: Gforth provides one big address space, and address arithmetic can be
                   5006: performed between any addresses. However, in the dictionary headers or
                   5007: code are interleaved with data, so almost the only contiguous data space
                   5008: regions there are those described by ANS Forth as contiguous; but you
                   5009: can be sure that the dictionary is allocated towards increasing
                   5010: addresses even between contiguous regions.  The memory order of
                   5011: allocations in the heap is platform-dependent (and possibly different
                   5012: from one run to the next).
                   5013: 
1.27      crook    5014: 
1.32      anton    5015: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   5016: @subsection Dictionary allocation
1.27      crook    5017: @cindex reserving data space
                   5018: @cindex data space - reserving some
                   5019: 
1.32      anton    5020: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   5021: you want to deallocate X, you also deallocate everything
                   5022: allocated after X.
                   5023: 
1.68      anton    5024: @cindex contiguous regions in dictionary allocation
1.32      anton    5025: The allocations using the words below are contiguous and grow the region
                   5026: towards increasing addresses.  Other words that allocate dictionary
                   5027: memory of any kind (i.e., defining words including @code{:noname}) end
                   5028: the contiguous region and start a new one.
                   5029: 
                   5030: In ANS Forth only @code{create}d words are guaranteed to produce an
                   5031: address that is the start of the following contiguous region.  In
                   5032: particular, the cell allocated by @code{variable} is not guaranteed to
                   5033: be contiguous with following @code{allot}ed memory.
                   5034: 
                   5035: You can deallocate memory by using @code{allot} with a negative argument
                   5036: (with some restrictions, see @code{allot}). For larger deallocations use
                   5037: @code{marker}.
1.27      crook    5038: 
1.29      crook    5039: 
1.27      crook    5040: doc-here
                   5041: doc-unused
                   5042: doc-allot
                   5043: doc-c,
1.29      crook    5044: doc-f,
1.27      crook    5045: doc-,
                   5046: doc-2,
                   5047: 
1.32      anton    5048: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   5049: course you should allocate memory in an aligned way, too. I.e., before
                   5050: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   5051: The words below align @code{here} if it is not already.  Basically it is
                   5052: only already aligned for a type, if the last allocation was a multiple
                   5053: of the size of this type and if @code{here} was aligned for this type
                   5054: before.
                   5055: 
                   5056: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   5057: ANS Forth (@code{maxalign}ed in Gforth).
                   5058: 
                   5059: doc-align
                   5060: doc-falign
                   5061: doc-sfalign
                   5062: doc-dfalign
                   5063: doc-maxalign
                   5064: doc-cfalign
                   5065: 
                   5066: 
                   5067: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   5068: @subsection Heap allocation
                   5069: @cindex heap allocation
                   5070: @cindex dynamic allocation of memory
                   5071: @cindex memory-allocation word set
                   5072: 
1.68      anton    5073: @cindex contiguous regions and heap allocation
1.32      anton    5074: Heap allocation supports deallocation of allocated memory in any
                   5075: order. Dictionary allocation is not affected by it (i.e., it does not
                   5076: end a contiguous region). In Gforth, these words are implemented using
                   5077: the standard C library calls malloc(), free() and resize().
                   5078: 
1.68      anton    5079: The memory region produced by one invocation of @code{allocate} or
                   5080: @code{resize} is internally contiguous.  There is no contiguity between
                   5081: such a region and any other region (including others allocated from the
                   5082: heap).
                   5083: 
1.32      anton    5084: doc-allocate
                   5085: doc-free
                   5086: doc-resize
                   5087: 
1.27      crook    5088: 
1.32      anton    5089: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    5090: @subsection Memory Access
                   5091: @cindex memory access words
                   5092: 
                   5093: doc-@
                   5094: doc-!
                   5095: doc-+!
                   5096: doc-c@
                   5097: doc-c!
                   5098: doc-2@
                   5099: doc-2!
                   5100: doc-f@
                   5101: doc-f!
                   5102: doc-sf@
                   5103: doc-sf!
                   5104: doc-df@
                   5105: doc-df!
                   5106: 
1.68      anton    5107: 
1.32      anton    5108: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   5109: @subsection Address arithmetic
1.1       anton    5110: @cindex address arithmetic words
                   5111: 
1.67      anton    5112: Address arithmetic is the foundation on which you can build data
                   5113: structures like arrays, records (@pxref{Structures}) and objects
                   5114: (@pxref{Object-oriented Forth}).
1.32      anton    5115: 
1.68      anton    5116: @cindex address unit
                   5117: @cindex au (address unit)
1.1       anton    5118: ANS Forth does not specify the sizes of the data types. Instead, it
                   5119: offers a number of words for computing sizes and doing address
1.29      crook    5120: arithmetic. Address arithmetic is performed in terms of address units
                   5121: (aus); on most systems the address unit is one byte. Note that a
                   5122: character may have more than one au, so @code{chars} is no noop (on
1.68      anton    5123: platforms where it is a noop, it compiles to nothing).
1.1       anton    5124: 
1.67      anton    5125: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
                   5126: you have the address of a cell, perform @code{1 cells +}, and you will
                   5127: have the address of the next cell.
                   5128: 
1.68      anton    5129: @cindex contiguous regions and address arithmetic
1.67      anton    5130: In ANS Forth you can perform address arithmetic only within a contiguous
                   5131: region, i.e., if you have an address into one region, you can only add
                   5132: and subtract such that the result is still within the region; you can
                   5133: only subtract or compare addresses from within the same contiguous
                   5134: region.  Reasons: several contiguous regions can be arranged in memory
                   5135: in any way; on segmented systems addresses may have unusual
                   5136: representations, such that address arithmetic only works within a
                   5137: region.  Gforth provides a few more guarantees (linear address space,
                   5138: dictionary grows upwards), but in general I have found it easy to stay
                   5139: within contiguous regions (exception: computing and comparing to the
                   5140: address just beyond the end of an array).
                   5141: 
1.1       anton    5142: @cindex alignment of addresses for types
                   5143: ANS Forth also defines words for aligning addresses for specific
                   5144: types. Many computers require that accesses to specific data types
                   5145: must only occur at specific addresses; e.g., that cells may only be
                   5146: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5147: accesses, it can usually perform aligned accesses faster. 
                   5148: 
                   5149: For the performance-conscious: alignment operations are usually only
                   5150: necessary during the definition of a data structure, not during the
                   5151: (more frequent) accesses to it.
                   5152: 
                   5153: ANS Forth defines no words for character-aligning addresses. This is not
                   5154: an oversight, but reflects the fact that addresses that are not
                   5155: char-aligned have no use in the standard and therefore will not be
                   5156: created.
                   5157: 
                   5158: @cindex @code{CREATE} and alignment
1.29      crook    5159: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5160: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5161: are aligned for all purposes.
                   5162: 
1.26      crook    5163: Note that the ANS Forth word @code{char} has nothing to do with address
                   5164: arithmetic.
1.1       anton    5165: 
1.44      crook    5166: 
1.1       anton    5167: doc-chars
                   5168: doc-char+
                   5169: doc-cells
                   5170: doc-cell+
                   5171: doc-cell
                   5172: doc-aligned
                   5173: doc-floats
                   5174: doc-float+
                   5175: doc-float
                   5176: doc-faligned
                   5177: doc-sfloats
                   5178: doc-sfloat+
                   5179: doc-sfaligned
                   5180: doc-dfloats
                   5181: doc-dfloat+
                   5182: doc-dfaligned
                   5183: doc-maxaligned
                   5184: doc-cfaligned
                   5185: doc-address-unit-bits
                   5186: 
1.44      crook    5187: 
1.32      anton    5188: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5189: @subsection Memory Blocks
                   5190: @cindex memory block words
1.27      crook    5191: @cindex character strings - moving and copying
                   5192: 
1.49      anton    5193: Memory blocks often represent character strings; For ways of storing
                   5194: character strings in memory see @ref{String Formats}.  For other
                   5195: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5196: 
1.67      anton    5197: A few of these words work on address unit blocks.  In that case, you
                   5198: usually have to insert @code{CHARS} before the word when working on
                   5199: character strings.  Most words work on character blocks, and expect a
                   5200: char-aligned address.
                   5201: 
                   5202: When copying characters between overlapping memory regions, use
                   5203: @code{chars move} or choose carefully between @code{cmove} and
                   5204: @code{cmove>}.
1.44      crook    5205: 
1.1       anton    5206: doc-move
                   5207: doc-erase
                   5208: doc-cmove
                   5209: doc-cmove>
                   5210: doc-fill
                   5211: doc-blank
1.21      crook    5212: doc-compare
                   5213: doc-search
1.27      crook    5214: doc--trailing
                   5215: doc-/string
                   5216: 
1.44      crook    5217: 
1.27      crook    5218: @comment TODO examples
                   5219: 
1.1       anton    5220: 
1.26      crook    5221: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5222: @section Control Structures
                   5223: @cindex control structures
                   5224: 
1.33      anton    5225: Control structures in Forth cannot be used interpretively, only in a
                   5226: colon definition@footnote{To be precise, they have no interpretation
                   5227: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5228: not like this limitation, but have not seen a satisfying way around it
                   5229: yet, although many schemes have been proposed.
1.1       anton    5230: 
                   5231: @menu
1.33      anton    5232: * Selection::                   IF ... ELSE ... ENDIF
                   5233: * Simple Loops::                BEGIN ...
1.29      crook    5234: * Counted Loops::               DO
1.67      anton    5235: * Arbitrary control structures::  
                   5236: * Calls and returns::           
1.1       anton    5237: * Exception Handling::          
                   5238: @end menu
                   5239: 
                   5240: @node Selection, Simple Loops, Control Structures, Control Structures
                   5241: @subsection Selection
                   5242: @cindex selection control structures
                   5243: @cindex control structures for selection
                   5244: 
                   5245: @cindex @code{IF} control structure
                   5246: @example
1.29      crook    5247: @i{flag}
1.1       anton    5248: IF
1.29      crook    5249:   @i{code}
1.1       anton    5250: ENDIF
                   5251: @end example
1.21      crook    5252: @noindent
1.33      anton    5253: 
1.44      crook    5254: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5255: with any bit set represents truth) @i{code} is executed.
1.33      anton    5256: 
1.1       anton    5257: @example
1.29      crook    5258: @i{flag}
1.1       anton    5259: IF
1.29      crook    5260:   @i{code1}
1.1       anton    5261: ELSE
1.29      crook    5262:   @i{code2}
1.1       anton    5263: ENDIF
                   5264: @end example
                   5265: 
1.44      crook    5266: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5267: executed.
1.33      anton    5268: 
1.1       anton    5269: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5270: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5271: recommend using @code{ENDIF}, because it is less confusing for people
                   5272: who also know other languages (and is not prone to reinforcing negative
                   5273: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5274: system that only supplies @code{THEN} is simple:
                   5275: @example
1.21      crook    5276: : ENDIF   POSTPONE THEN ; immediate
1.1       anton    5277: @end example
                   5278: 
                   5279: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5280: (adv.)}  has the following meanings:
                   5281: @quotation
                   5282: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5283: (if you were there, then you saw them).
                   5284: @end quotation
                   5285: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5286: and many other programming languages has the meaning 3d.]
                   5287: 
1.21      crook    5288: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5289: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5290: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5291: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5292: @file{compat/control.fs}.
                   5293: 
                   5294: @cindex @code{CASE} control structure
                   5295: @example
1.29      crook    5296: @i{n}
1.1       anton    5297: CASE
1.29      crook    5298:   @i{n1} OF @i{code1} ENDOF
                   5299:   @i{n2} OF @i{code2} ENDOF
1.1       anton    5300:   @dots{}
1.68      anton    5301:   ( n ) @i{default-code} ( n )
1.1       anton    5302: ENDCASE
                   5303: @end example
                   5304: 
1.68      anton    5305: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If no
                   5306: @i{ni} matches, the optional @i{default-code} is executed. The optional
                   5307: default case can be added by simply writing the code after the last
                   5308: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
                   5309: not consume it.
1.1       anton    5310: 
1.69      anton    5311: @progstyle
                   5312: To keep the code understandable, you should ensure that on all paths
                   5313: through a selection construct the stack is changed in the same way
                   5314: (wrt. number and types of stack items consumed and pushed).
                   5315: 
1.1       anton    5316: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5317: @subsection Simple Loops
                   5318: @cindex simple loops
                   5319: @cindex loops without count 
                   5320: 
                   5321: @cindex @code{WHILE} loop
                   5322: @example
                   5323: BEGIN
1.29      crook    5324:   @i{code1}
                   5325:   @i{flag}
1.1       anton    5326: WHILE
1.29      crook    5327:   @i{code2}
1.1       anton    5328: REPEAT
                   5329: @end example
                   5330: 
1.29      crook    5331: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5332: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5333: false, execution continues after the @code{REPEAT}.
                   5334: 
                   5335: @cindex @code{UNTIL} loop
                   5336: @example
                   5337: BEGIN
1.29      crook    5338:   @i{code}
                   5339:   @i{flag}
1.1       anton    5340: UNTIL
                   5341: @end example
                   5342: 
1.29      crook    5343: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5344: 
1.69      anton    5345: @progstyle
                   5346: To keep the code understandable, a complete iteration of the loop should
                   5347: not change the number and types of the items on the stacks.
                   5348: 
1.1       anton    5349: @cindex endless loop
                   5350: @cindex loops, endless
                   5351: @example
                   5352: BEGIN
1.29      crook    5353:   @i{code}
1.1       anton    5354: AGAIN
                   5355: @end example
                   5356: 
                   5357: This is an endless loop.
                   5358: 
                   5359: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5360: @subsection Counted Loops
                   5361: @cindex counted loops
                   5362: @cindex loops, counted
                   5363: @cindex @code{DO} loops
                   5364: 
                   5365: The basic counted loop is:
                   5366: @example
1.29      crook    5367: @i{limit} @i{start}
1.1       anton    5368: ?DO
1.29      crook    5369:   @i{body}
1.1       anton    5370: LOOP
                   5371: @end example
                   5372: 
1.29      crook    5373: This performs one iteration for every integer, starting from @i{start}
                   5374: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5375: accessed with @code{i}. For example, the loop:
1.1       anton    5376: @example
                   5377: 10 0 ?DO
                   5378:   i .
                   5379: LOOP
                   5380: @end example
1.21      crook    5381: @noindent
                   5382: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5383: 
1.1       anton    5384: The index of the innermost loop can be accessed with @code{i}, the index
                   5385: of the next loop with @code{j}, and the index of the third loop with
                   5386: @code{k}.
                   5387: 
1.44      crook    5388: 
1.1       anton    5389: doc-i
                   5390: doc-j
                   5391: doc-k
                   5392: 
1.44      crook    5393: 
1.1       anton    5394: The loop control data are kept on the return stack, so there are some
1.21      crook    5395: restrictions on mixing return stack accesses and counted loop words. In
                   5396: particuler, if you put values on the return stack outside the loop, you
                   5397: cannot read them inside the loop@footnote{well, not in a way that is
                   5398: portable.}. If you put values on the return stack within a loop, you
                   5399: have to remove them before the end of the loop and before accessing the
                   5400: index of the loop.
1.1       anton    5401: 
                   5402: There are several variations on the counted loop:
                   5403: 
1.21      crook    5404: @itemize @bullet
                   5405: @item
                   5406: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5407: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5408: 
                   5409: @example
                   5410: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5411: @end example
                   5412: prints @code{0 1 2 3}
                   5413: 
1.1       anton    5414: 
1.21      crook    5415: @item
                   5416: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5417: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5418: return stack so @code{EXIT} can get to its return address. For example:
                   5419: 
                   5420: @example
                   5421: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5422: @end example
                   5423: prints @code{0 1 2 3}
                   5424: 
                   5425: 
                   5426: @item
1.29      crook    5427: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5428: (and @code{LOOP} iterates until they become equal by wrap-around
                   5429: arithmetic). This behaviour is usually not what you want. Therefore,
                   5430: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5431: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5432: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5433: unsigned loop parameters.
                   5434: 
1.21      crook    5435: @item
                   5436: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5437: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5438: if you know that the loop is entered in any case. Such knowledge tends
                   5439: to become invalid during maintenance of a program, and then the
                   5440: @code{DO} will make trouble.
                   5441: 
                   5442: @item
1.29      crook    5443: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5444: index by @i{n} instead of by 1. The loop is terminated when the border
                   5445: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5446: 
1.21      crook    5447: @example
                   5448: 4 0 +DO  i .  2 +LOOP
                   5449: @end example
                   5450: @noindent
                   5451: prints @code{0 2}
                   5452: 
                   5453: @example
                   5454: 4 1 +DO  i .  2 +LOOP
                   5455: @end example
                   5456: @noindent
                   5457: prints @code{1 3}
1.1       anton    5458: 
1.68      anton    5459: @item
1.1       anton    5460: @cindex negative increment for counted loops
                   5461: @cindex counted loops with negative increment
1.29      crook    5462: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5463: 
1.21      crook    5464: @example
                   5465: -1 0 ?DO  i .  -1 +LOOP
                   5466: @end example
                   5467: @noindent
                   5468: prints @code{0 -1}
1.1       anton    5469: 
1.21      crook    5470: @example
                   5471: 0 0 ?DO  i .  -1 +LOOP
                   5472: @end example
                   5473: prints nothing.
1.1       anton    5474: 
1.29      crook    5475: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5476: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5477: index by @i{u} each iteration. The loop is terminated when the border
                   5478: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5479: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5480: 
1.21      crook    5481: @example
                   5482: -2 0 -DO  i .  1 -LOOP
                   5483: @end example
                   5484: @noindent
                   5485: prints @code{0 -1}
1.1       anton    5486: 
1.21      crook    5487: @example
                   5488: -1 0 -DO  i .  1 -LOOP
                   5489: @end example
                   5490: @noindent
                   5491: prints @code{0}
                   5492: 
                   5493: @example
                   5494: 0 0 -DO  i .  1 -LOOP
                   5495: @end example
                   5496: @noindent
                   5497: prints nothing.
1.1       anton    5498: 
1.21      crook    5499: @end itemize
1.1       anton    5500: 
                   5501: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5502: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5503: for these words that uses only standard words is provided in
                   5504: @file{compat/loops.fs}.
1.1       anton    5505: 
                   5506: 
                   5507: @cindex @code{FOR} loops
1.26      crook    5508: Another counted loop is:
1.1       anton    5509: @example
1.29      crook    5510: @i{n}
1.1       anton    5511: FOR
1.29      crook    5512:   @i{body}
1.1       anton    5513: NEXT
                   5514: @end example
                   5515: This is the preferred loop of native code compiler writers who are too
1.26      crook    5516: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5517: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5518: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5519: Forth systems may behave differently, even if they support @code{FOR}
                   5520: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5521: 
                   5522: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5523: @subsection Arbitrary control structures
                   5524: @cindex control structures, user-defined
                   5525: 
                   5526: @cindex control-flow stack
                   5527: ANS Forth permits and supports using control structures in a non-nested
                   5528: way. Information about incomplete control structures is stored on the
                   5529: control-flow stack. This stack may be implemented on the Forth data
                   5530: stack, and this is what we have done in Gforth.
                   5531: 
                   5532: @cindex @code{orig}, control-flow stack item
                   5533: @cindex @code{dest}, control-flow stack item
                   5534: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5535: entry represents a backward branch target. A few words are the basis for
                   5536: building any control structure possible (except control structures that
                   5537: need storage, like calls, coroutines, and backtracking).
                   5538: 
1.44      crook    5539: 
1.1       anton    5540: doc-if
                   5541: doc-ahead
                   5542: doc-then
                   5543: doc-begin
                   5544: doc-until
                   5545: doc-again
                   5546: doc-cs-pick
                   5547: doc-cs-roll
                   5548: 
1.44      crook    5549: 
1.21      crook    5550: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5551: manipulate the control-flow stack in a portable way. Without them, you
                   5552: would need to know how many stack items are occupied by a control-flow
                   5553: entry (many systems use one cell. In Gforth they currently take three,
                   5554: but this may change in the future).
                   5555: 
1.1       anton    5556: Some standard control structure words are built from these words:
                   5557: 
1.44      crook    5558: 
1.1       anton    5559: doc-else
                   5560: doc-while
                   5561: doc-repeat
                   5562: 
1.44      crook    5563: 
                   5564: @noindent
1.1       anton    5565: Gforth adds some more control-structure words:
                   5566: 
1.44      crook    5567: 
1.1       anton    5568: doc-endif
                   5569: doc-?dup-if
                   5570: doc-?dup-0=-if
                   5571: 
1.44      crook    5572: 
                   5573: @noindent
1.1       anton    5574: Counted loop words constitute a separate group of words:
                   5575: 
1.44      crook    5576: 
1.1       anton    5577: doc-?do
                   5578: doc-+do
                   5579: doc-u+do
                   5580: doc--do
                   5581: doc-u-do
                   5582: doc-do
                   5583: doc-for
                   5584: doc-loop
                   5585: doc-+loop
                   5586: doc--loop
                   5587: doc-next
                   5588: doc-leave
                   5589: doc-?leave
                   5590: doc-unloop
                   5591: doc-done
                   5592: 
1.44      crook    5593: 
1.21      crook    5594: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5595: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5596: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5597: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5598: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5599: resolved (by using one of the loop-ending words or @code{DONE}).
                   5600: 
1.44      crook    5601: @noindent
1.26      crook    5602: Another group of control structure words are:
1.1       anton    5603: 
1.44      crook    5604: 
1.1       anton    5605: doc-case
                   5606: doc-endcase
                   5607: doc-of
                   5608: doc-endof
                   5609: 
1.44      crook    5610: 
1.21      crook    5611: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5612: @code{CS-ROLL}.
1.1       anton    5613: 
                   5614: @subsubsection Programming Style
1.47      crook    5615: @cindex control structures programming style
                   5616: @cindex programming style, arbitrary control structures
1.1       anton    5617: 
                   5618: In order to ensure readability we recommend that you do not create
                   5619: arbitrary control structures directly, but define new control structure
                   5620: words for the control structure you want and use these words in your
1.26      crook    5621: program. For example, instead of writing:
1.1       anton    5622: 
                   5623: @example
1.26      crook    5624: BEGIN
1.1       anton    5625:   ...
1.26      crook    5626: IF [ 1 CS-ROLL ]
1.1       anton    5627:   ...
1.26      crook    5628: AGAIN THEN
1.1       anton    5629: @end example
                   5630: 
1.21      crook    5631: @noindent
1.1       anton    5632: we recommend defining control structure words, e.g.,
                   5633: 
                   5634: @example
1.26      crook    5635: : WHILE ( DEST -- ORIG DEST )
                   5636:  POSTPONE IF
                   5637:  1 CS-ROLL ; immediate
                   5638: 
                   5639: : REPEAT ( orig dest -- )
                   5640:  POSTPONE AGAIN
                   5641:  POSTPONE THEN ; immediate
1.1       anton    5642: @end example
                   5643: 
1.21      crook    5644: @noindent
1.1       anton    5645: and then using these to create the control structure:
                   5646: 
                   5647: @example
1.26      crook    5648: BEGIN
1.1       anton    5649:   ...
1.26      crook    5650: WHILE
1.1       anton    5651:   ...
1.26      crook    5652: REPEAT
1.1       anton    5653: @end example
                   5654: 
                   5655: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5656: @code{WHILE} are predefined, so in this example it would not be
                   5657: necessary to define them.
                   5658: 
                   5659: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5660: @subsection Calls and returns
                   5661: @cindex calling a definition
                   5662: @cindex returning from a definition
                   5663: 
1.3       anton    5664: @cindex recursive definitions
                   5665: A definition can be called simply be writing the name of the definition
1.26      crook    5666: to be called. Normally a definition is invisible during its own
1.3       anton    5667: definition. If you want to write a directly recursive definition, you
1.26      crook    5668: can use @code{recursive} to make the current definition visible, or
                   5669: @code{recurse} to call the current definition directly.
1.3       anton    5670: 
1.44      crook    5671: 
1.3       anton    5672: doc-recursive
                   5673: doc-recurse
                   5674: 
1.44      crook    5675: 
1.21      crook    5676: @comment TODO add example of the two recursion methods
1.12      anton    5677: @quotation
                   5678: @progstyle
                   5679: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5680: definition by name is more descriptive (if the name is well-chosen) than
                   5681: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5682: implementation, it is much better to read (and think) ``now sort the
                   5683: partitions'' than to read ``now do a recursive call''.
                   5684: @end quotation
1.3       anton    5685: 
1.29      crook    5686: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5687: 
                   5688: @example
1.28      crook    5689: Defer foo
1.3       anton    5690: 
                   5691: : bar ( ... -- ... )
                   5692:  ... foo ... ;
                   5693: 
                   5694: :noname ( ... -- ... )
                   5695:  ... bar ... ;
                   5696: IS foo
                   5697: @end example
                   5698: 
1.44      crook    5699: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33      anton    5700: 
1.26      crook    5701: The current definition returns control to the calling definition when
1.33      anton    5702: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5703: 
                   5704: doc-exit
                   5705: doc-;s
                   5706: 
1.44      crook    5707: 
1.1       anton    5708: @node Exception Handling,  , Calls and returns, Control Structures
                   5709: @subsection Exception Handling
1.26      crook    5710: @cindex exceptions
1.1       anton    5711: 
1.68      anton    5712: @c quit is a very bad idea for error handling, 
                   5713: @c because it does not translate into a THROW
                   5714: @c it also does not belong into this chapter
                   5715: 
                   5716: If a word detects an error condition that it cannot handle, it can
                   5717: @code{throw} an exception.  In the simplest case, this will terminate
                   5718: your program, and report an appropriate error.
1.21      crook    5719: 
1.68      anton    5720: doc-throw
1.1       anton    5721: 
1.69      anton    5722: @code{Throw} consumes a cell-sized error number on the stack. There are
                   5723: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
                   5724: Gforth (and most other systems) you can use the iors produced by various
                   5725: words as error numbers (e.g., a typical use of @code{allocate} is
                   5726: @code{allocate throw}).  Gforth also provides the word @code{exception}
                   5727: to define your own error numbers (with decent error reporting); an ANS
                   5728: Forth version of this word (but without the error messages) is available
                   5729: in @code{compat/except.fs}.  And finally, you can use your own error
1.68      anton    5730: numbers (anything outside the range -4095..0), but won't get nice error
                   5731: messages, only numbers.  For example, try:
                   5732: 
                   5733: @example
1.69      anton    5734: -10 throw                    \ ANS defined
                   5735: -267 throw                   \ system defined
                   5736: s" my error" exception throw \ user defined
                   5737: 7 throw                      \ arbitrary number
1.68      anton    5738: @end example
                   5739: 
                   5740: doc---exception-exception
1.1       anton    5741: 
1.69      anton    5742: A common idiom to @code{THROW} a specific error if a flag is true is
                   5743: this:
                   5744: 
                   5745: @example
                   5746: @code{( flag ) 0<> @i{errno} and throw}
                   5747: @end example
                   5748: 
                   5749: Your program can provide exception handlers to catch exceptions.  An
                   5750: exception handler can be used to correct the problem, or to clean up
                   5751: some data structures and just throw the exception to the next exception
                   5752: handler.  Note that @code{throw} jumps to the dynamically innermost
                   5753: exception handler.  The system's exception handler is outermost, and just
                   5754: prints an error and restarts command-line interpretation (or, in batch
                   5755: mode (i.e., while processing the shell command line), leaves Gforth).
1.1       anton    5756: 
1.68      anton    5757: The ANS Forth way to catch exceptions is @code{catch}:
1.1       anton    5758: 
1.68      anton    5759: doc-catch
                   5760: 
                   5761: The most common use of exception handlers is to clean up the state when
                   5762: an error happens.  E.g.,
1.1       anton    5763: 
1.26      crook    5764: @example
1.68      anton    5765: base @ >r hex \ actually the hex should be inside foo, or we h
                   5766: ['] foo catch ( nerror|0 )
                   5767: r> base !
1.69      anton    5768: ( nerror|0 ) throw \ pass it on
1.26      crook    5769: @end example
1.1       anton    5770: 
1.69      anton    5771: A use of @code{catch} for handling the error @code{myerror} might look
                   5772: like this:
1.44      crook    5773: 
1.68      anton    5774: @example
1.69      anton    5775: ['] foo catch
                   5776: CASE
                   5777:   myerror OF ... ( do something about it ) ENDOF
                   5778:   dup throw \ default: pass other errors on, do nothing on non-errors
                   5779: ENDCASE
1.68      anton    5780: @end example
1.44      crook    5781: 
1.68      anton    5782: Having to wrap the code into a separate word is often cumbersome,
                   5783: therefore Gforth provides an alternative syntax:
1.1       anton    5784: 
                   5785: @example
1.69      anton    5786: TRY
1.68      anton    5787:   @i{code1}
1.69      anton    5788: RECOVER     \ optional
1.68      anton    5789:   @i{code2} \ optional
1.69      anton    5790: ENDTRY
1.1       anton    5791: @end example
                   5792: 
1.68      anton    5793: This performs @i{Code1}.  If @i{code1} completes normally, execution
                   5794: continues after the @code{endtry}.  If @i{Code1} throws, the stacks are
                   5795: reset to the state during @code{try}, the throw value is pushed on the
                   5796: data stack, and execution constinues at @i{code2}, and finally falls
                   5797: through the @code{endtry} into the following code. If there is no
                   5798: @code{recover} clause, this works like an empty recover clause.
1.26      crook    5799: 
1.68      anton    5800: doc-try
                   5801: doc-recover
                   5802: doc-endtry
1.26      crook    5803: 
1.69      anton    5804: The cleanup example from above in this syntax:
1.26      crook    5805: 
1.68      anton    5806: @example
1.69      anton    5807: base @ >r TRY
1.68      anton    5808:   hex foo \ now the hex is placed correctly
1.69      anton    5809:   0       \ value for throw
                   5810: ENDTRY
1.68      anton    5811: r> base ! throw
1.1       anton    5812: @end example
                   5813: 
1.69      anton    5814: And here's the error handling example:
1.1       anton    5815: 
1.68      anton    5816: @example
1.69      anton    5817: TRY
1.68      anton    5818:   foo
1.69      anton    5819: RECOVER
                   5820:   CASE
                   5821:     myerror OF ... ( do something about it ) ENDOF
                   5822:     throw \ pass other errors on
                   5823:   ENDCASE
                   5824: ENDTRY
1.68      anton    5825: @end example
1.1       anton    5826: 
1.69      anton    5827: @progstyle
                   5828: As usual, you should ensure that the stack depth is statically known at
                   5829: the end: either after the @code{throw} for passing on errors, or after
                   5830: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
                   5831: selection construct for handling the error).
                   5832: 
1.68      anton    5833: There are two alternatives to @code{throw}: @code{Abort"} is conditional
                   5834: and you can provide an error message.  @code{Abort} just produces an
                   5835: ``Aborted'' error.
1.1       anton    5836: 
1.68      anton    5837: The problem with these words is that exception handlers cannot
                   5838: differentiate between different @code{abort"}s; they just look like
                   5839: @code{-2 throw} to them (the error message cannot be accessed by
                   5840: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
                   5841: exception handlers.
1.44      crook    5842: 
1.68      anton    5843: doc-abort"
1.26      crook    5844: doc-abort
1.29      crook    5845: 
                   5846: 
1.44      crook    5847: 
1.29      crook    5848: @c -------------------------------------------------------------
1.47      crook    5849: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    5850: @section Defining Words
                   5851: @cindex defining words
                   5852: 
1.47      crook    5853: Defining words are used to extend Forth by creating new entries in the dictionary.
                   5854: 
1.29      crook    5855: @menu
1.67      anton    5856: * CREATE::                      
1.44      crook    5857: * Variables::                   Variables and user variables
1.67      anton    5858: * Constants::                   
1.44      crook    5859: * Values::                      Initialised variables
1.67      anton    5860: * Colon Definitions::           
1.44      crook    5861: * Anonymous Definitions::       Definitions without names
1.69      anton    5862: * Supplying names::             Passing definition names as strings
1.67      anton    5863: * User-defined Defining Words::  
1.44      crook    5864: * Deferred words::              Allow forward references
1.67      anton    5865: * Aliases::                     
1.29      crook    5866: @end menu
                   5867: 
1.44      crook    5868: @node CREATE, Variables, Defining Words, Defining Words
                   5869: @subsection @code{CREATE}
1.29      crook    5870: @cindex simple defining words
                   5871: @cindex defining words, simple
                   5872: 
                   5873: Defining words are used to create new entries in the dictionary. The
                   5874: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   5875: this:
                   5876: 
                   5877: @example
                   5878: CREATE new-word1
                   5879: @end example
                   5880: 
1.69      anton    5881: @code{CREATE} is a parsing word, i.e., it takes an argument from the
                   5882: input stream (@code{new-word1} in our example).  It generates a
                   5883: dictionary entry for @code{new-word1}. When @code{new-word1} is
                   5884: executed, all that it does is leave an address on the stack. The address
                   5885: represents the value of the data space pointer (@code{HERE}) at the time
                   5886: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
                   5887: associating a name with the address of a region of memory.
1.29      crook    5888: 
1.34      anton    5889: doc-create
                   5890: 
1.69      anton    5891: Note that in ANS Forth guarantees only for @code{create} that its body
                   5892: is in dictionary data space (i.e., where @code{here}, @code{allot}
                   5893: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
                   5894: @code{create}d words can be modified with @code{does>}
                   5895: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
                   5896: can only be applied to @code{create}d words.
                   5897: 
1.29      crook    5898: By extending this example to reserve some memory in data space, we end
1.69      anton    5899: up with something like a @i{variable}. Here are two different ways to do
                   5900: it:
1.29      crook    5901: 
                   5902: @example
                   5903: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   5904: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   5905: @end example
                   5906: 
                   5907: The variable can be examined and modified using @code{@@} (``fetch'') and
                   5908: @code{!} (``store'') like this:
                   5909: 
                   5910: @example
                   5911: new-word2 @@ .      \ get address, fetch from it and display
                   5912: 1234 new-word2 !   \ new value, get address, store to it
                   5913: @end example
                   5914: 
1.44      crook    5915: @cindex arrays
                   5916: A similar mechanism can be used to create arrays. For example, an
                   5917: 80-character text input buffer:
1.29      crook    5918: 
                   5919: @example
1.44      crook    5920: CREATE text-buf 80 chars allot
                   5921: 
                   5922: text-buf 0 chars c@@ \ the 1st character (offset 0)
                   5923: text-buf 3 chars c@@ \ the 4th character (offset 3)
                   5924: @end example
1.29      crook    5925: 
1.44      crook    5926: You can build arbitrarily complex data structures by allocating
1.49      anton    5927: appropriate areas of memory. For further discussions of this, and to
1.66      anton    5928: learn about some Gforth tools that make it easier,
1.49      anton    5929: @xref{Structures}.
1.44      crook    5930: 
                   5931: 
                   5932: @node Variables, Constants, CREATE, Defining Words
                   5933: @subsection Variables
                   5934: @cindex variables
                   5935: 
                   5936: The previous section showed how a sequence of commands could be used to
                   5937: generate a variable.  As a final refinement, the whole code sequence can
                   5938: be wrapped up in a defining word (pre-empting the subject of the next
                   5939: section), making it easier to create new variables:
                   5940: 
                   5941: @example
                   5942: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   5943: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   5944: 
                   5945: myvariableX foo \ variable foo starts off with an unknown value
                   5946: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    5947: 
                   5948: 45 3 * foo !   \ set foo to 135
                   5949: 1234 joe !     \ set joe to 1234
                   5950: 3 joe +!       \ increment joe by 3.. to 1237
                   5951: @end example
                   5952: 
                   5953: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    5954: Forth already has a definition @code{Variable}. ANS Forth does not
1.69      anton    5955: guarantee that a @code{Variable} is initialised when it is created
                   5956: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
                   5957: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
                   5958: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    5959: @code{fvariable} for double and floating-point variables, respectively
1.69      anton    5960: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47      crook    5961: store a boolean, you can use @code{on} and @code{off} to toggle its
                   5962: state.
1.29      crook    5963: 
1.34      anton    5964: doc-variable
                   5965: doc-2variable
                   5966: doc-fvariable
                   5967: 
1.29      crook    5968: @cindex user variables
                   5969: @cindex user space
                   5970: The defining word @code{User} behaves in the same way as @code{Variable}.
                   5971: The difference is that it reserves space in @i{user (data) space} rather
                   5972: than normal data space. In a Forth system that has a multi-tasker, each
                   5973: task has its own set of user variables.
                   5974: 
1.34      anton    5975: doc-user
1.67      anton    5976: @c doc-udp
                   5977: @c doc-uallot
1.34      anton    5978: 
1.29      crook    5979: @comment TODO is that stuff about user variables strictly correct? Is it
                   5980: @comment just terminal tasks that have user variables?
                   5981: @comment should document tasker.fs (with some examples) elsewhere
                   5982: @comment in this manual, then expand on user space and user variables.
                   5983: 
1.44      crook    5984: @node Constants, Values, Variables, Defining Words
                   5985: @subsection Constants
                   5986: @cindex constants
                   5987: 
                   5988: @code{Constant} allows you to declare a fixed value and refer to it by
                   5989: name. For example:
1.29      crook    5990: 
                   5991: @example
                   5992: 12 Constant INCHES-PER-FOOT
                   5993: 3E+08 fconstant SPEED-O-LIGHT
                   5994: @end example
                   5995: 
                   5996: A @code{Variable} can be both read and written, so its run-time
                   5997: behaviour is to supply an address through which its current value can be
                   5998: manipulated. In contrast, the value of a @code{Constant} cannot be
                   5999: changed once it has been declared@footnote{Well, often it can be -- but
                   6000: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   6001: on).} so it's not necessary to supply the address -- it is more
                   6002: efficient to return the value of the constant directly. That's exactly
                   6003: what happens; the run-time effect of a constant is to put its value on
1.49      anton    6004: the top of the stack (You can find one
                   6005: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    6006: 
1.69      anton    6007: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29      crook    6008: double and floating-point constants, respectively.
                   6009: 
1.34      anton    6010: doc-constant
                   6011: doc-2constant
                   6012: doc-fconstant
                   6013: 
                   6014: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    6015: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   6016: @c constant, use it and then delete the definition of the constant..
1.69      anton    6017: 
                   6018: @c anton->An ANS Forth system can compile a constant to a literal; On
                   6019: @c decompilation you would see only the number, just as if it had been used
                   6020: @c in the first place.  The word will stay, of course, but it will only be
                   6021: @c used by the text interpreter (no run-time duties, except when it is 
                   6022: @c POSTPONEd or somesuch).
                   6023: 
                   6024: @c nac:
1.44      crook    6025: @c I agree that it's rather deep, but IMO it is an important difference
                   6026: @c relative to other programming languages.. often it's annoying: it
                   6027: @c certainly changes my programming style relative to C.
                   6028: 
1.69      anton    6029: @c anton: In what way?
                   6030: 
1.29      crook    6031: Constants in Forth behave differently from their equivalents in other
                   6032: programming languages. In other languages, a constant (such as an EQU in
                   6033: assembler or a #define in C) only exists at compile-time; in the
                   6034: executable program the constant has been translated into an absolute
                   6035: number and, unless you are using a symbolic debugger, it's impossible to
                   6036: know what abstract thing that number represents. In Forth a constant has
1.44      crook    6037: an entry in the header space and remains there after the code that uses
                   6038: it has been defined. In fact, it must remain in the dictionary since it
                   6039: has run-time duties to perform. For example:
1.29      crook    6040: 
                   6041: @example
                   6042: 12 Constant INCHES-PER-FOOT
                   6043: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   6044: @end example
                   6045: 
                   6046: @cindex in-lining of constants
                   6047: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   6048: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   6049: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   6050: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   6051: attempt to optimise constants by in-lining them where they are used. You
                   6052: can force Gforth to in-line a constant like this:
                   6053: 
                   6054: @example
                   6055: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   6056: @end example
                   6057: 
                   6058: If you use @code{see} to decompile @i{this} version of
                   6059: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    6060: longer present. To understand how this works, read
                   6061: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    6062: 
                   6063: In-lining constants in this way might improve execution time
                   6064: fractionally, and can ensure that a constant is now only referenced at
                   6065: compile-time. However, the definition of the constant still remains in
                   6066: the dictionary. Some Forth compilers provide a mechanism for controlling
                   6067: a second dictionary for holding transient words such that this second
                   6068: dictionary can be deleted later in order to recover memory
                   6069: space. However, there is no standard way of doing this.
                   6070: 
                   6071: 
1.44      crook    6072: @node Values, Colon Definitions, Constants, Defining Words
                   6073: @subsection Values
                   6074: @cindex values
1.34      anton    6075: 
1.69      anton    6076: A @code{Value} behaves like a @code{Constant}, but it can be changed.
                   6077: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
                   6078: (not in ANS Forth) you can access (and change) a @code{value} also with
                   6079: @code{>body}.
                   6080: 
                   6081: Here are some
                   6082: examples:
1.29      crook    6083: 
                   6084: @example
1.69      anton    6085: 12 Value APPLES     \ Define APPLES with an initial value of 12
                   6086: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
                   6087: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
                   6088: APPLES              \ puts 35 on the top of the stack.
1.29      crook    6089: @end example
                   6090: 
1.44      crook    6091: doc-value
                   6092: doc-to
1.29      crook    6093: 
1.35      anton    6094: 
1.69      anton    6095: 
1.44      crook    6096: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   6097: @subsection Colon Definitions
                   6098: @cindex colon definitions
1.35      anton    6099: 
                   6100: @example
1.44      crook    6101: : name ( ... -- ... )
                   6102:     word1 word2 word3 ;
1.29      crook    6103: @end example
                   6104: 
1.44      crook    6105: @noindent
                   6106: Creates a word called @code{name} that, upon execution, executes
                   6107: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    6108: 
1.49      anton    6109: The explanation above is somewhat superficial. For simple examples of
                   6110: colon definitions see @ref{Your first definition}.  For an in-depth
1.66      anton    6111: discussion of some of the issues involved, @xref{Interpretation and
1.49      anton    6112: Compilation Semantics}.
1.29      crook    6113: 
1.44      crook    6114: doc-:
                   6115: doc-;
1.1       anton    6116: 
1.34      anton    6117: 
1.69      anton    6118: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44      crook    6119: @subsection Anonymous Definitions
                   6120: @cindex colon definitions
                   6121: @cindex defining words without name
1.34      anton    6122: 
1.44      crook    6123: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   6124: name. You can do this with:
1.1       anton    6125: 
1.44      crook    6126: doc-:noname
1.1       anton    6127: 
1.44      crook    6128: This leaves the execution token for the word on the stack after the
                   6129: closing @code{;}. Here's an example in which a deferred word is
                   6130: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6131: 
1.29      crook    6132: @example
1.44      crook    6133: Defer deferred
                   6134: :noname ( ... -- ... )
                   6135:   ... ;
                   6136: IS deferred
1.29      crook    6137: @end example
1.26      crook    6138: 
1.44      crook    6139: @noindent
                   6140: Gforth provides an alternative way of doing this, using two separate
                   6141: words:
1.27      crook    6142: 
1.44      crook    6143: doc-noname
                   6144: @cindex execution token of last defined word
                   6145: doc-lastxt
1.1       anton    6146: 
1.44      crook    6147: @noindent
                   6148: The previous example can be rewritten using @code{noname} and
                   6149: @code{lastxt}:
1.1       anton    6150: 
1.26      crook    6151: @example
1.44      crook    6152: Defer deferred
                   6153: noname : ( ... -- ... )
                   6154:   ... ;
                   6155: lastxt IS deferred
1.26      crook    6156: @end example
1.1       anton    6157: 
1.29      crook    6158: @noindent
1.44      crook    6159: @code{noname} works with any defining word, not just @code{:}.
                   6160: 
                   6161: @code{lastxt} also works when the last word was not defined as
1.71      anton    6162: @code{noname}.  It does not work for combined words, though.  It also has
                   6163: the useful property that is is valid as soon as the header for a
                   6164: definition has been built. Thus:
1.44      crook    6165: 
                   6166: @example
                   6167: lastxt . : foo [ lastxt . ] ; ' foo .
                   6168: @end example
1.1       anton    6169: 
1.44      crook    6170: @noindent
                   6171: prints 3 numbers; the last two are the same.
1.26      crook    6172: 
1.69      anton    6173: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
                   6174: @subsection Supplying the name of a defined word
                   6175: @cindex names for defined words
                   6176: @cindex defining words, name given in a string
                   6177: 
                   6178: By default, a defining word takes the name for the defined word from the
                   6179: input stream. Sometimes you want to supply the name from a string. You
                   6180: can do this with:
                   6181: 
                   6182: doc-nextname
                   6183: 
                   6184: For example:
                   6185: 
                   6186: @example
                   6187: s" foo" nextname create
                   6188: @end example
                   6189: 
                   6190: @noindent
                   6191: is equivalent to:
                   6192: 
                   6193: @example
                   6194: create foo
                   6195: @end example
                   6196: 
                   6197: @noindent
                   6198: @code{nextname} works with any defining word.
                   6199: 
1.1       anton    6200: 
1.69      anton    6201: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26      crook    6202: @subsection User-defined Defining Words
                   6203: @cindex user-defined defining words
                   6204: @cindex defining words, user-defined
1.1       anton    6205: 
1.29      crook    6206: You can create a new defining word by wrapping defining-time code around
                   6207: an existing defining word and putting the sequence in a colon
1.69      anton    6208: definition. 
                   6209: 
                   6210: @c anton: This example is very complex and leads in a quite different
                   6211: @c direction from the CREATE-DOES> stuff that follows.  It should probably
                   6212: @c be done elsewhere, or as a subsubsection of this subsection (or as a
                   6213: @c subsection of Defining Words)
                   6214: 
                   6215: For example, suppose that you have a word @code{stats} that
1.29      crook    6216: gathers statistics about colon definitions given the @i{xt} of the
                   6217: definition, and you want every colon definition in your application to
                   6218: make a call to @code{stats}. You can define and use a new version of
                   6219: @code{:} like this:
                   6220: 
                   6221: @example
                   6222: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6223:   ... ;  \ other code
                   6224: 
                   6225: : my: : lastxt postpone literal ['] stats compile, ;
                   6226: 
                   6227: my: foo + - ;
                   6228: @end example
                   6229: 
                   6230: When @code{foo} is defined using @code{my:} these steps occur:
                   6231: 
                   6232: @itemize @bullet
                   6233: @item
                   6234: @code{my:} is executed.
                   6235: @item
                   6236: The @code{:} within the definition (the one between @code{my:} and
                   6237: @code{lastxt}) is executed, and does just what it always does; it parses
                   6238: the input stream for a name, builds a dictionary header for the name
                   6239: @code{foo} and switches @code{state} from interpret to compile.
                   6240: @item
                   6241: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
                   6242: being defined -- @code{foo} -- onto the stack.
                   6243: @item
                   6244: The code that was produced by @code{postpone literal} is executed; this
                   6245: causes the value on the stack to be compiled as a literal in the code
                   6246: area of @code{foo}.
                   6247: @item
                   6248: The code @code{['] stats} compiles a literal into the definition of
                   6249: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6250: execution token for @code{stats} -- is layed down in the code area of
                   6251: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6252: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6253: in the code area is implementation-dependent. A threaded implementation
                   6254: might spit out the execution token directly whilst another
                   6255: implementation might spit out a native code sequence.}.
                   6256: @item
                   6257: At this point, the execution of @code{my:} is complete, and control
                   6258: returns to the text interpreter. The text interpreter is in compile
                   6259: state, so subsequent text @code{+ -} is compiled into the definition of
                   6260: @code{foo} and the @code{;} terminates the definition as always.
                   6261: @end itemize
                   6262: 
                   6263: You can use @code{see} to decompile a word that was defined using
                   6264: @code{my:} and see how it is different from a normal @code{:}
                   6265: definition. For example:
                   6266: 
                   6267: @example
                   6268: : bar + - ;  \ like foo but using : rather than my:
                   6269: see bar
                   6270: : bar
                   6271:   + - ;
                   6272: see foo
                   6273: : foo
                   6274:   107645672 stats + - ;
                   6275: 
                   6276: \ use ' stats . to show that 107645672 is the xt for stats
                   6277: @end example
                   6278: 
                   6279: You can use techniques like this to make new defining words in terms of
                   6280: @i{any} existing defining word.
1.1       anton    6281: 
                   6282: 
1.29      crook    6283: @cindex defining defining words
1.26      crook    6284: @cindex @code{CREATE} ... @code{DOES>}
                   6285: If you want the words defined with your defining words to behave
                   6286: differently from words defined with standard defining words, you can
                   6287: write your defining word like this:
1.1       anton    6288: 
                   6289: @example
1.26      crook    6290: : def-word ( "name" -- )
1.29      crook    6291:     CREATE @i{code1}
1.26      crook    6292: DOES> ( ... -- ... )
1.29      crook    6293:     @i{code2} ;
1.26      crook    6294: 
                   6295: def-word name
1.1       anton    6296: @end example
                   6297: 
1.29      crook    6298: @cindex child words
                   6299: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6300: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6301: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6302: is not executed at this time. The word @code{name} is sometimes called a
                   6303: @dfn{child} of @code{def-word}.
                   6304: 
                   6305: When you execute @code{name}, the address of the body of @code{name} is
                   6306: put on the data stack and @i{code2} is executed (the address of the body
                   6307: of @code{name} is the address @code{HERE} returns immediately after the
1.69      anton    6308: @code{CREATE}, i.e., the address a @code{create}d word returns by
                   6309: default).
                   6310: 
                   6311: @c anton:
                   6312: @c www.dictionary.com says:
                   6313: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
                   6314: @c several generations of absence, usually caused by the chance
                   6315: @c recombination of genes.  2.An individual or a part that exhibits
                   6316: @c atavism. Also called throwback.  3.The return of a trait or recurrence
                   6317: @c of previous behavior after a period of absence.
                   6318: @c
                   6319: @c Doesn't seem to fit.
1.29      crook    6320: 
1.69      anton    6321: @c @cindex atavism in child words
1.33      anton    6322: You can use @code{def-word} to define a set of child words that behave
1.69      anton    6323: similarly; they all have a common run-time behaviour determined by
                   6324: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
                   6325: body of the child word. The structure of the data is common to all
                   6326: children of @code{def-word}, but the data values are specific -- and
                   6327: private -- to each child word. When a child word is executed, the
                   6328: address of its private data area is passed as a parameter on TOS to be
                   6329: used and manipulated@footnote{It is legitimate both to read and write to
                   6330: this data area.} by @i{code2}.
1.29      crook    6331: 
                   6332: The two fragments of code that make up the defining words act (are
                   6333: executed) at two completely separate times:
1.1       anton    6334: 
1.29      crook    6335: @itemize @bullet
                   6336: @item
                   6337: At @i{define time}, the defining word executes @i{code1} to generate a
                   6338: child word
                   6339: @item
                   6340: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6341: is executed, using parameters (data) that are private and specific to
                   6342: the child word.
                   6343: @end itemize
                   6344: 
1.44      crook    6345: Another way of understanding the behaviour of @code{def-word} and
                   6346: @code{name} is to say that, if you make the following definitions:
1.33      anton    6347: @example
                   6348: : def-word1 ( "name" -- )
                   6349:     CREATE @i{code1} ;
                   6350: 
                   6351: : action1 ( ... -- ... )
                   6352:     @i{code2} ;
                   6353: 
                   6354: def-word1 name1
                   6355: @end example
                   6356: 
1.44      crook    6357: @noindent
                   6358: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6359: 
1.29      crook    6360: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6361: 
1.1       anton    6362: @example
1.29      crook    6363: : CONSTANT ( w "name" -- )
                   6364:     CREATE ,
1.26      crook    6365: DOES> ( -- w )
                   6366:     @@ ;
1.1       anton    6367: @end example
                   6368: 
1.29      crook    6369: @comment There is a beautiful description of how this works and what
                   6370: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6371: @comment commentary on the Counting Fruits problem.
                   6372: 
                   6373: When you create a constant with @code{5 CONSTANT five}, a set of
                   6374: define-time actions take place; first a new word @code{five} is created,
                   6375: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6376: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6377: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6378: no code of its own; it simply contains a data field and a pointer to the
                   6379: code that follows @code{DOES>} in its defining word. That makes words
                   6380: created in this way very compact.
                   6381: 
                   6382: The final example in this section is intended to remind you that space
                   6383: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6384: both read and written by a Standard program@footnote{Exercise: use this
                   6385: example as a starting point for your own implementation of @code{Value}
                   6386: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6387: @code{[']}.}:
                   6388: 
                   6389: @example
                   6390: : foo ( "name" -- )
                   6391:     CREATE -1 ,
                   6392: DOES> ( -- )
1.33      anton    6393:     @@ . ;
1.29      crook    6394: 
                   6395: foo first-word
                   6396: foo second-word
                   6397: 
                   6398: 123 ' first-word >BODY !
                   6399: @end example
                   6400: 
                   6401: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6402: have executed it to get the address of its data field. However, since it
                   6403: was defined to have @code{DOES>} actions, its execution semantics are to
                   6404: perform those @code{DOES>} actions. To get the address of its data field
                   6405: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6406: translate the xt into the address of the data field.  When you execute
                   6407: @code{first-word}, it will display @code{123}. When you execute
                   6408: @code{second-word} it will display @code{-1}.
1.26      crook    6409: 
                   6410: @cindex stack effect of @code{DOES>}-parts
                   6411: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6412: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6413: the stack effect of the defined words, not the stack effect of the
                   6414: following code (the following code expects the address of the body on
                   6415: the top of stack, which is not reflected in the stack comment). This is
                   6416: the convention that I use and recommend (it clashes a bit with using
                   6417: locals declarations for stack effect specification, though).
1.1       anton    6418: 
1.53      anton    6419: @menu
                   6420: * CREATE..DOES> applications::  
                   6421: * CREATE..DOES> details::       
1.63      anton    6422: * Advanced does> usage example::  
1.53      anton    6423: @end menu
                   6424: 
                   6425: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26      crook    6426: @subsubsection Applications of @code{CREATE..DOES>}
                   6427: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6428: 
1.26      crook    6429: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6430: 
1.26      crook    6431: @cindex factoring similar colon definitions
                   6432: When you see a sequence of code occurring several times, and you can
                   6433: identify a meaning, you will factor it out as a colon definition. When
                   6434: you see similar colon definitions, you can factor them using
                   6435: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6436: that look very similar:
1.1       anton    6437: @example
1.26      crook    6438: : ori, ( reg-target reg-source n -- )
                   6439:     0 asm-reg-reg-imm ;
                   6440: : andi, ( reg-target reg-source n -- )
                   6441:     1 asm-reg-reg-imm ;
1.1       anton    6442: @end example
                   6443: 
1.26      crook    6444: @noindent
                   6445: This could be factored with:
                   6446: @example
                   6447: : reg-reg-imm ( op-code -- )
                   6448:     CREATE ,
                   6449: DOES> ( reg-target reg-source n -- )
                   6450:     @@ asm-reg-reg-imm ;
                   6451: 
                   6452: 0 reg-reg-imm ori,
                   6453: 1 reg-reg-imm andi,
                   6454: @end example
1.1       anton    6455: 
1.26      crook    6456: @cindex currying
                   6457: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6458: supply a part of the parameters for a word (known as @dfn{currying} in
                   6459: the functional language community). E.g., @code{+} needs two
                   6460: parameters. Creating versions of @code{+} with one parameter fixed can
                   6461: be done like this:
1.1       anton    6462: @example
1.26      crook    6463: : curry+ ( n1 -- )
                   6464:     CREATE ,
                   6465: DOES> ( n2 -- n1+n2 )
                   6466:     @@ + ;
                   6467: 
                   6468:  3 curry+ 3+
                   6469: -2 curry+ 2-
1.1       anton    6470: @end example
                   6471: 
1.63      anton    6472: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6473: @subsubsection The gory details of @code{CREATE..DOES>}
                   6474: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6475: 
1.26      crook    6476: doc-does>
1.1       anton    6477: 
1.26      crook    6478: @cindex @code{DOES>} in a separate definition
                   6479: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6480: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6481: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6482: @example
                   6483: : does1 
                   6484: DOES> ( ... -- ... )
1.44      crook    6485:     ... ;
                   6486: 
                   6487: : does2
                   6488: DOES> ( ... -- ... )
                   6489:     ... ;
                   6490: 
                   6491: : def-word ( ... -- ... )
                   6492:     create ...
                   6493:     IF
                   6494:        does1
                   6495:     ELSE
                   6496:        does2
                   6497:     ENDIF ;
                   6498: @end example
                   6499: 
                   6500: In this example, the selection of whether to use @code{does1} or
1.69      anton    6501: @code{does2} is made at definition-time; at the time that the child word is
1.44      crook    6502: @code{CREATE}d.
                   6503: 
                   6504: @cindex @code{DOES>} in interpretation state
                   6505: In a standard program you can apply a @code{DOES>}-part only if the last
                   6506: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6507: will override the behaviour of the last word defined in any case. In a
                   6508: standard program, you can use @code{DOES>} only in a colon
                   6509: definition. In Gforth, you can also use it in interpretation state, in a
                   6510: kind of one-shot mode; for example:
                   6511: @example
                   6512: CREATE name ( ... -- ... )
                   6513:   @i{initialization}
                   6514: DOES>
                   6515:   @i{code} ;
                   6516: @end example
                   6517: 
                   6518: @noindent
                   6519: is equivalent to the standard:
                   6520: @example
                   6521: :noname
                   6522: DOES>
                   6523:     @i{code} ;
                   6524: CREATE name EXECUTE ( ... -- ... )
                   6525:     @i{initialization}
                   6526: @end example
                   6527: 
1.53      anton    6528: doc->body
                   6529: 
1.63      anton    6530: @node Advanced does> usage example,  , CREATE..DOES> details, User-defined Defining Words
                   6531: @subsubsection Advanced does> usage example
                   6532: 
                   6533: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
                   6534: for disassembling instructions, that follow a very repetetive scheme:
                   6535: 
                   6536: @example
                   6537: :noname @var{disasm-operands} s" @var{inst-name}" type ;
                   6538: @var{entry-num} cells @var{table} + !
                   6539: @end example
                   6540: 
                   6541: Of course, this inspires the idea to factor out the commonalities to
                   6542: allow a definition like
                   6543: 
                   6544: @example
                   6545: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
                   6546: @end example
                   6547: 
                   6548: The parameters @var{disasm-operands} and @var{table} are usually
1.69      anton    6549: correlated.  Moreover, before I wrote the disassembler, there already
                   6550: existed code that defines instructions like this:
1.63      anton    6551: 
                   6552: @example
                   6553: @var{entry-num} @var{inst-format} @var{inst-name}
                   6554: @end example
                   6555: 
                   6556: This code comes from the assembler and resides in
                   6557: @file{arch/mips/insts.fs}.
                   6558: 
                   6559: So I had to define the @var{inst-format} words that performed the scheme
                   6560: above when executed.  At first I chose to use run-time code-generation:
                   6561: 
                   6562: @example
                   6563: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
                   6564:   :noname Postpone @var{disasm-operands}
                   6565:   name Postpone sliteral Postpone type Postpone ;
                   6566:   swap cells @var{table} + ! ;
                   6567: @end example
                   6568: 
                   6569: Note that this supplies the other two parameters of the scheme above.
1.44      crook    6570: 
1.63      anton    6571: An alternative would have been to write this using
                   6572: @code{create}/@code{does>}:
                   6573: 
                   6574: @example
                   6575: : @var{inst-format} ( entry-num "name" -- )
                   6576:   here name string, ( entry-num c-addr ) \ parse and save "name"
                   6577:   noname create , ( entry-num )
                   6578:   lastxt swap cells @var{table} + !
                   6579: does> ( addr w -- )
                   6580:   \ disassemble instruction w at addr
                   6581:   @@ >r 
                   6582:   @var{disasm-operands}
                   6583:   r> count type ;
                   6584: @end example
                   6585: 
                   6586: Somehow the first solution is simpler, mainly because it's simpler to
                   6587: shift a string from definition-time to use-time with @code{sliteral}
                   6588: than with @code{string,} and friends.
                   6589: 
                   6590: I wrote a lot of words following this scheme and soon thought about
                   6591: factoring out the commonalities among them.  Note that this uses a
                   6592: two-level defining word, i.e., a word that defines ordinary defining
                   6593: words.
                   6594: 
                   6595: This time a solution involving @code{postpone} and friends seemed more
                   6596: difficult (try it as an exercise), so I decided to use a
                   6597: @code{create}/@code{does>} word; since I was already at it, I also used
                   6598: @code{create}/@code{does>} for the lower level (try using
                   6599: @code{postpone} etc. as an exercise), resulting in the following
                   6600: definition:
                   6601: 
                   6602: @example
                   6603: : define-format ( disasm-xt table-xt -- )
                   6604:     \ define an instruction format that uses disasm-xt for
                   6605:     \ disassembling and enters the defined instructions into table
                   6606:     \ table-xt
                   6607:     create 2,
                   6608: does> ( u "inst" -- )
                   6609:     \ defines an anonymous word for disassembling instruction inst,
                   6610:     \ and enters it as u-th entry into table-xt
                   6611:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
                   6612:     noname create 2,      \ define anonymous word
                   6613:     execute lastxt swap ! \ enter xt of defined word into table-xt
                   6614: does> ( addr w -- )
                   6615:     \ disassemble instruction w at addr
                   6616:     2@@ >r ( addr w disasm-xt R: c-addr )
                   6617:     execute ( R: c-addr ) \ disassemble operands
                   6618:     r> count type ; \ print name 
                   6619: @end example
                   6620: 
                   6621: Note that the tables here (in contrast to above) do the @code{cells +}
                   6622: by themselves (that's why you have to pass an xt).  This word is used in
                   6623: the following way:
                   6624: 
                   6625: @example
                   6626: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
                   6627: @end example
                   6628: 
1.71      anton    6629: As shown above, the defined instruction format is then used like this:
                   6630: 
                   6631: @example
                   6632: @var{entry-num} @var{inst-format} @var{inst-name}
                   6633: @end example
                   6634: 
1.63      anton    6635: In terms of currying, this kind of two-level defining word provides the
                   6636: parameters in three stages: first @var{disasm-operands} and @var{table},
                   6637: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
                   6638: the instruction to be disassembled.  
                   6639: 
                   6640: Of course this did not quite fit all the instruction format names used
                   6641: in @file{insts.fs}, so I had to define a few wrappers that conditioned
                   6642: the parameters into the right form.
                   6643: 
                   6644: If you have trouble following this section, don't worry.  First, this is
                   6645: involved and takes time (and probably some playing around) to
                   6646: understand; second, this is the first two-level
                   6647: @code{create}/@code{does>} word I have written in seventeen years of
                   6648: Forth; and if I did not have @file{insts.fs} to start with, I may well
                   6649: have elected to use just a one-level defining word (with some repeating
                   6650: of parameters when using the defining word). So it is not necessary to
                   6651: understand this, but it may improve your understanding of Forth.
1.44      crook    6652: 
                   6653: 
                   6654: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
                   6655: @subsection Deferred words
                   6656: @cindex deferred words
                   6657: 
                   6658: The defining word @code{Defer} allows you to define a word by name
                   6659: without defining its behaviour; the definition of its behaviour is
                   6660: deferred. Here are two situation where this can be useful:
                   6661: 
                   6662: @itemize @bullet
                   6663: @item
                   6664: Where you want to allow the behaviour of a word to be altered later, and
                   6665: for all precompiled references to the word to change when its behaviour
                   6666: is changed.
                   6667: @item
                   6668: For mutual recursion; @xref{Calls and returns}.
                   6669: @end itemize
                   6670: 
                   6671: In the following example, @code{foo} always invokes the version of
                   6672: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6673: always invokes the version that prints ``@code{Hello}''. There is no way
                   6674: of getting @code{foo} to use the later version without re-ordering the
                   6675: source code and recompiling it.
                   6676: 
                   6677: @example
                   6678: : greet ." Good morning" ;
                   6679: : foo ... greet ... ;
                   6680: : greet ." Hello" ;
                   6681: : bar ... greet ... ;
                   6682: @end example
                   6683: 
                   6684: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6685: word. The behaviour of a @code{Defer}red word can be defined and
                   6686: redefined at any time by using @code{IS} to associate the xt of a
                   6687: previously-defined word with it. The previous example becomes:
                   6688: 
                   6689: @example
1.69      anton    6690: Defer greet ( -- )
1.44      crook    6691: : foo ... greet ... ;
                   6692: : bar ... greet ... ;
1.69      anton    6693: : greet1 ( -- ) ." Good morning" ;
                   6694: : greet2 ( -- ) ." Hello" ;
1.44      crook    6695: ' greet2 <IS> greet  \ make greet behave like greet2
                   6696: @end example
                   6697: 
1.69      anton    6698: @progstyle
                   6699: You should write a stack comment for every deferred word, and put only
                   6700: XTs into deferred words that conform to this stack effect.  Otherwise
                   6701: it's too difficult to use the deferred word.
                   6702: 
1.44      crook    6703: A deferred word can be used to improve the statistics-gathering example
                   6704: from @ref{User-defined Defining Words}; rather than edit the
                   6705: application's source code to change every @code{:} to a @code{my:}, do
                   6706: this:
                   6707: 
                   6708: @example
                   6709: : real: : ;     \ retain access to the original
                   6710: defer :         \ redefine as a deferred word
1.69      anton    6711: ' my: <IS> :      \ use special version of :
1.44      crook    6712: \
                   6713: \ load application here
                   6714: \
1.69      anton    6715: ' real: <IS> :    \ go back to the original
1.44      crook    6716: @end example
                   6717: 
                   6718: 
                   6719: One thing to note is that @code{<IS>} consumes its name when it is
                   6720: executed.  If you want to specify the name at compile time, use
                   6721: @code{[IS]}:
                   6722: 
                   6723: @example
                   6724: : set-greet ( xt -- )
                   6725:   [IS] greet ;
                   6726: 
                   6727: ' greet1 set-greet
                   6728: @end example
                   6729: 
1.69      anton    6730: A deferred word can only inherit execution semantics from the xt
                   6731: (because that is all that an xt can represent -- for more discussion of
                   6732: this @pxref{Tokens for Words}); by default it will have default
                   6733: interpretation and compilation semantics deriving from this execution
                   6734: semantics.  However, you can change the interpretation and compilation
                   6735: semantics of the deferred word in the usual ways:
1.44      crook    6736: 
                   6737: @example
                   6738: : bar .... ; compile-only
                   6739: Defer fred immediate
                   6740: Defer jim
                   6741: 
                   6742: ' bar <IS> jim  \ jim has default semantics
                   6743: ' bar <IS> fred \ fred is immediate
                   6744: @end example
                   6745: 
                   6746: doc-defer
                   6747: doc-<is>
                   6748: doc-[is]
                   6749: doc-is
                   6750: @comment TODO document these: what's defers [is]
                   6751: doc-what's
                   6752: doc-defers
                   6753: 
                   6754: @c Use @code{words-deferred} to see a list of deferred words.
                   6755: 
                   6756: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
                   6757: are provided in @file{compat/defer.fs}.
                   6758: 
                   6759: 
1.69      anton    6760: @node Aliases,  , Deferred words, Defining Words
1.44      crook    6761: @subsection Aliases
                   6762: @cindex aliases
1.1       anton    6763: 
1.44      crook    6764: The defining word @code{Alias} allows you to define a word by name that
                   6765: has the same behaviour as some other word. Here are two situation where
                   6766: this can be useful:
1.1       anton    6767: 
1.44      crook    6768: @itemize @bullet
                   6769: @item
                   6770: When you want access to a word's definition from a different word list
                   6771: (for an example of this, see the definition of the @code{Root} word list
                   6772: in the Gforth source).
                   6773: @item
                   6774: When you want to create a synonym; a definition that can be known by
                   6775: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   6776: aliases).
                   6777: @end itemize
1.1       anton    6778: 
1.69      anton    6779: Like deferred words, an alias has default compilation and interpretation
                   6780: semantics at the beginning (not the modifications of the other word),
                   6781: but you can change them in the usual ways (@code{immediate},
                   6782: @code{compile-only}). For example:
1.1       anton    6783: 
                   6784: @example
1.44      crook    6785: : foo ... ; immediate
                   6786: 
                   6787: ' foo Alias bar \ bar is not an immediate word
                   6788: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    6789: @end example
                   6790: 
1.44      crook    6791: Words that are aliases have the same xt, different headers in the
                   6792: dictionary, and consequently different name tokens (@pxref{Tokens for
                   6793: Words}) and possibly different immediate flags.  An alias can only have
                   6794: default or immediate compilation semantics; you can define aliases for
                   6795: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    6796: 
1.44      crook    6797: doc-alias
1.1       anton    6798: 
                   6799: 
1.47      crook    6800: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   6801: @section Interpretation and Compilation Semantics
1.26      crook    6802: @cindex semantics, interpretation and compilation
1.1       anton    6803: 
1.71      anton    6804: @c !! state and ' are used without explanation
                   6805: @c example for immediate/compile-only? or is the tutorial enough
                   6806: 
1.26      crook    6807: @cindex interpretation semantics
1.71      anton    6808: The @dfn{interpretation semantics} of a (named) word are what the text
1.26      crook    6809: interpreter does when it encounters the word in interpret state. It also
                   6810: appears in some other contexts, e.g., the execution token returned by
1.71      anton    6811: @code{' @i{word}} identifies the interpretation semantics of @i{word}
                   6812: (in other words, @code{' @i{word} execute} is equivalent to
1.29      crook    6813: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    6814: 
1.26      crook    6815: @cindex compilation semantics
1.71      anton    6816: The @dfn{compilation semantics} of a (named) word are what the text
                   6817: interpreter does when it encounters the word in compile state. It also
                   6818: appears in other contexts, e.g, @code{POSTPONE @i{word}}
                   6819: compiles@footnote{In standard terminology, ``appends to the current
                   6820: definition''.} the compilation semantics of @i{word}.
1.1       anton    6821: 
1.26      crook    6822: @cindex execution semantics
                   6823: The standard also talks about @dfn{execution semantics}. They are used
                   6824: only for defining the interpretation and compilation semantics of many
                   6825: words. By default, the interpretation semantics of a word are to
                   6826: @code{execute} its execution semantics, and the compilation semantics of
                   6827: a word are to @code{compile,} its execution semantics.@footnote{In
                   6828: standard terminology: The default interpretation semantics are its
                   6829: execution semantics; the default compilation semantics are to append its
                   6830: execution semantics to the execution semantics of the current
                   6831: definition.}
                   6832: 
1.71      anton    6833: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
                   6834: the text interpreter, ticked, or @code{postpone}d, so they have no
                   6835: interpretation or compilation semantics.  Their behaviour is represented
                   6836: by their XT (@pxref{Tokens for Words}), and we call it execution
                   6837: semantics, too.
                   6838: 
1.26      crook    6839: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   6840: 
                   6841: @cindex immediate words
                   6842: @cindex compile-only words
                   6843: You can change the semantics of the most-recently defined word:
                   6844: 
1.44      crook    6845: 
1.26      crook    6846: doc-immediate
                   6847: doc-compile-only
                   6848: doc-restrict
                   6849: 
1.44      crook    6850: 
1.26      crook    6851: Note that ticking (@code{'}) a compile-only word gives an error
                   6852: (``Interpreting a compile-only word'').
1.1       anton    6853: 
1.47      crook    6854: @menu
1.67      anton    6855: * Combined words::              
1.47      crook    6856: @end menu
1.44      crook    6857: 
1.71      anton    6858: 
1.48      anton    6859: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    6860: @subsection Combined Words
                   6861: @cindex combined words
                   6862: 
                   6863: Gforth allows you to define @dfn{combined words} -- words that have an
                   6864: arbitrary combination of interpretation and compilation semantics.
                   6865: 
1.26      crook    6866: doc-interpret/compile:
1.1       anton    6867: 
1.26      crook    6868: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   6869: recommend that you do not define such words, as cute as they may be:
                   6870: they make it hard to get at both parts of the word in some contexts.
                   6871: E.g., assume you want to get an execution token for the compilation
                   6872: part. Instead, define two words, one that embodies the interpretation
                   6873: part, and one that embodies the compilation part.  Once you have done
                   6874: that, you can define a combined word with @code{interpret/compile:} for
                   6875: the convenience of your users.
1.1       anton    6876: 
1.26      crook    6877: You might try to use this feature to provide an optimizing
                   6878: implementation of the default compilation semantics of a word. For
                   6879: example, by defining:
1.1       anton    6880: @example
1.26      crook    6881: :noname
                   6882:    foo bar ;
                   6883: :noname
                   6884:    POSTPONE foo POSTPONE bar ;
1.29      crook    6885: interpret/compile: opti-foobar
1.1       anton    6886: @end example
1.26      crook    6887: 
1.23      crook    6888: @noindent
1.26      crook    6889: as an optimizing version of:
                   6890: 
1.1       anton    6891: @example
1.26      crook    6892: : foobar
                   6893:     foo bar ;
1.1       anton    6894: @end example
                   6895: 
1.26      crook    6896: Unfortunately, this does not work correctly with @code{[compile]},
                   6897: because @code{[compile]} assumes that the compilation semantics of all
                   6898: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    6899: opti-foobar} would compile compilation semantics, whereas
                   6900: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    6901: 
1.26      crook    6902: @cindex state-smart words (are a bad idea)
1.29      crook    6903: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    6904: by @code{interpret/compile:} (words are state-smart if they check
                   6905: @code{STATE} during execution). E.g., they would try to code
                   6906: @code{foobar} like this:
1.1       anton    6907: 
1.26      crook    6908: @example
                   6909: : foobar
                   6910:   STATE @@
                   6911:   IF ( compilation state )
                   6912:     POSTPONE foo POSTPONE bar
                   6913:   ELSE
                   6914:     foo bar
                   6915:   ENDIF ; immediate
                   6916: @end example
1.1       anton    6917: 
1.26      crook    6918: Although this works if @code{foobar} is only processed by the text
                   6919: interpreter, it does not work in other contexts (like @code{'} or
                   6920: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   6921: for a state-smart word, not for the interpretation semantics of the
                   6922: original @code{foobar}; when you execute this execution token (directly
                   6923: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   6924: state, the result will not be what you expected (i.e., it will not
                   6925: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   6926: write them@footnote{For a more detailed discussion of this topic, see
1.66      anton    6927: M. Anton Ertl,
                   6928: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
                   6929: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1       anton    6930: 
1.26      crook    6931: @cindex defining words with arbitrary semantics combinations
                   6932: It is also possible to write defining words that define words with
                   6933: arbitrary combinations of interpretation and compilation semantics. In
                   6934: general, they look like this:
1.1       anton    6935: 
1.26      crook    6936: @example
                   6937: : def-word
                   6938:     create-interpret/compile
1.29      crook    6939:     @i{code1}
1.26      crook    6940: interpretation>
1.29      crook    6941:     @i{code2}
1.26      crook    6942: <interpretation
                   6943: compilation>
1.29      crook    6944:     @i{code3}
1.26      crook    6945: <compilation ;
                   6946: @end example
1.1       anton    6947: 
1.29      crook    6948: For a @i{word} defined with @code{def-word}, the interpretation
                   6949: semantics are to push the address of the body of @i{word} and perform
                   6950: @i{code2}, and the compilation semantics are to push the address of
                   6951: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    6952: can also be defined like this (except that the defined constants don't
                   6953: behave correctly when @code{[compile]}d):
1.1       anton    6954: 
1.26      crook    6955: @example
                   6956: : constant ( n "name" -- )
                   6957:     create-interpret/compile
                   6958:     ,
                   6959: interpretation> ( -- n )
                   6960:     @@
                   6961: <interpretation
                   6962: compilation> ( compilation. -- ; run-time. -- n )
                   6963:     @@ postpone literal
                   6964: <compilation ;
                   6965: @end example
1.1       anton    6966: 
1.44      crook    6967: 
1.26      crook    6968: doc-create-interpret/compile
                   6969: doc-interpretation>
                   6970: doc-<interpretation
                   6971: doc-compilation>
                   6972: doc-<compilation
1.1       anton    6973: 
1.44      crook    6974: 
1.29      crook    6975: Words defined with @code{interpret/compile:} and
1.26      crook    6976: @code{create-interpret/compile} have an extended header structure that
                   6977: differs from other words; however, unless you try to access them with
                   6978: plain address arithmetic, you should not notice this. Words for
                   6979: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    6980: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   6981: with @code{create-interpret/compile}.
1.1       anton    6982: 
1.44      crook    6983: 
1.27      crook    6984: doc-postpone
1.44      crook    6985: 
1.29      crook    6986: @comment TODO -- expand glossary text for POSTPONE
1.27      crook    6987: 
1.47      crook    6988: 
                   6989: @c -------------------------------------------------------------
                   6990: @node Tokens for Words, The Text Interpreter, Interpretation and Compilation Semantics, Words
                   6991: @section Tokens for Words
                   6992: @cindex tokens for words
                   6993: 
                   6994: This section describes the creation and use of tokens that represent
                   6995: words.
                   6996: 
1.71      anton    6997: @menu
                   6998: * Execution token::             represents execution/interpretation semantics
                   6999: * Compilation token::           represents compilation semantics
                   7000: * Name token::                  represents named words
                   7001: @end menu
1.47      crook    7002: 
1.71      anton    7003: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
                   7004: @subsection Execution token
1.47      crook    7005: 
                   7006: @cindex xt
                   7007: @cindex execution token
1.71      anton    7008: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
                   7009: You can use @code{execute} to invoke this behaviour.
1.47      crook    7010: 
1.71      anton    7011: @cindex tick (')
                   7012: You can use @code{'} to get an execution token that represents the
                   7013: interpretation semantics of a named word:
1.47      crook    7014: 
                   7015: @example
1.71      anton    7016: 5 ' .
                   7017: execute
                   7018: @end example
1.47      crook    7019: 
1.71      anton    7020: doc-'
                   7021: 
                   7022: @code{'} parses at run-time; there is also a word @code{[']} that parses
                   7023: when it is compiled, and compiles the resulting XT:
                   7024: 
                   7025: @example
                   7026: : foo ['] . execute ;
                   7027: 5 foo
                   7028: : bar ' execute ; \ by contrast,
                   7029: 5 bar .           \ ' parses "." when bar executes
                   7030: @end example
                   7031: 
                   7032: doc-[']
                   7033: 
                   7034: If you want the execution token of @i{word}, write @code{['] @i{word}}
                   7035: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
                   7036: @code{'} and @code{[']} behave somewhat unusually by complaining about
                   7037: compile-only words (because these words have no interpretation
                   7038: semantics).  You might get what you want by using @code{COMP' @i{word}
                   7039: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
                   7040: token}).
                   7041: 
                   7042: Another way to get an XT is @code{:noname} or @code{lastxt}
                   7043: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
                   7044: for the only behaviour the word has (the execution semantics).  For
                   7045: named words, @code{lastxt} produces an XT for the same behaviour it
                   7046: would produce if the word was defined anonymously.
                   7047: 
                   7048: @example
                   7049: :noname ." hello" ;
                   7050: execute
1.47      crook    7051: @end example
                   7052: 
1.71      anton    7053: An XT occupies one cell and can be manipulated like any other cell.
                   7054: 
1.47      crook    7055: @cindex code field address
                   7056: @cindex CFA
1.71      anton    7057: In ANS Forth the XT is just an abstract data type (i.e., defined by the
                   7058: operations that produce or consume it).  For old hands: In Gforth, the
                   7059: XT is implemented as a code field address (CFA).
                   7060: 
                   7061: @c !! discuss "compile," some more (or in Macros).
                   7062: 
                   7063: doc-execute
                   7064: doc-perform
                   7065: doc-compile,
                   7066: 
                   7067: @node Compilation token, Name token, Execution token, Tokens for Words
                   7068: @subsection Compilation token
1.47      crook    7069: 
                   7070: @cindex compilation token
1.71      anton    7071: @cindex CT (compilation token)
                   7072: Gforth represents the compilation semantics of a named word by a
1.47      crook    7073: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   7074: @i{xt} is an execution token. The compilation semantics represented by
                   7075: the compilation token can be performed with @code{execute}, which
                   7076: consumes the whole compilation token, with an additional stack effect
                   7077: determined by the represented compilation semantics.
                   7078: 
                   7079: At present, the @i{w} part of a compilation token is an execution token,
                   7080: and the @i{xt} part represents either @code{execute} or
                   7081: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   7082: word. If the word has default compilation semantics, the @i{xt} will
                   7083: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   7084: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   7085: knowledge, unless necessary; future versions of Gforth may introduce
                   7086: unusual compilation tokens (e.g., a compilation token that represents
                   7087: the compilation semantics of a literal).
                   7088: 
1.71      anton    7089: You can perform the compilation semantics represented by the compilation
                   7090: token with @code{execute}.  You can compile the compilation semantics
                   7091: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
                   7092: equivalent to @code{postpone @i{word}}.
                   7093: 
                   7094: doc-[comp']
                   7095: doc-comp'
                   7096: doc-postpone,
                   7097: 
                   7098: @node Name token,  , Compilation token, Tokens for Words
                   7099: @subsection Name token
1.47      crook    7100: 
                   7101: @cindex name token
                   7102: @cindex name field address
                   7103: @cindex NFA
1.71      anton    7104: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
1.47      crook    7105: Gforth, the abstract data type @emph{name token} is implemented as a
                   7106: name field address (NFA).
                   7107: 
                   7108: doc-find-name
                   7109: doc-name>int
                   7110: doc-name?int
                   7111: doc-name>comp
                   7112: doc-name>string
                   7113: 
                   7114: 
1.26      crook    7115: @c ----------------------------------------------------------
1.47      crook    7116: @node The Text Interpreter, Word Lists, Tokens for Words, Words
1.26      crook    7117: @section  The Text Interpreter
                   7118: @cindex interpreter - outer
                   7119: @cindex text interpreter
                   7120: @cindex outer interpreter
1.1       anton    7121: 
1.34      anton    7122: @c Should we really describe all these ugly details?  IMO the text
                   7123: @c interpreter should be much cleaner, but that may not be possible within
                   7124: @c ANS Forth. - anton
1.44      crook    7125: @c nac-> I wanted to explain how it works to show how you can exploit
                   7126: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   7127: @c some of these gory details was very helpful to me. None of the textbooks
                   7128: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   7129: @c seems to positively avoid going into too much detail for some of
                   7130: @c the internals.
1.34      anton    7131: 
1.71      anton    7132: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
                   7133: @c it is; for the ugly details, I would prefer another place.  I wonder
                   7134: @c whether we should have a chapter before "Words" that describes some
                   7135: @c basic concepts referred to in words, and a chapter after "Words" that
                   7136: @c describes implementation details.
                   7137: 
1.29      crook    7138: The text interpreter@footnote{This is an expanded version of the
                   7139: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    7140: that processes input from the current input device. It is also called
                   7141: the outer interpreter, in contrast to the inner interpreter
                   7142: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   7143: implementations.
1.27      crook    7144: 
1.29      crook    7145: @cindex interpret state
                   7146: @cindex compile state
                   7147: The text interpreter operates in one of two states: @dfn{interpret
                   7148: state} and @dfn{compile state}. The current state is defined by the
1.71      anton    7149: aptly-named variable @code{state}.
1.29      crook    7150: 
                   7151: This section starts by describing how the text interpreter behaves when
                   7152: it is in interpret state, processing input from the user input device --
                   7153: the keyboard. This is the mode that a Forth system is in after it starts
                   7154: up.
                   7155: 
                   7156: @cindex input buffer
                   7157: @cindex terminal input buffer
                   7158: The text interpreter works from an area of memory called the @dfn{input
                   7159: buffer}@footnote{When the text interpreter is processing input from the
                   7160: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   7161: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   7162: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    7163: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    7164: leading spaces (called @dfn{delimiters}) then parses a string (a
                   7165: sequence of non-space characters) until it reaches either a space
                   7166: character or the end of the buffer. Having parsed a string, it makes two
                   7167: attempts to process it:
1.27      crook    7168: 
1.29      crook    7169: @cindex dictionary
1.27      crook    7170: @itemize @bullet
                   7171: @item
1.29      crook    7172: It looks for the string in a @dfn{dictionary} of definitions. If the
                   7173: string is found, the string names a @dfn{definition} (also known as a
                   7174: @dfn{word}) and the dictionary search returns information that allows
                   7175: the text interpreter to perform the word's @dfn{interpretation
                   7176: semantics}. In most cases, this simply means that the word will be
                   7177: executed.
1.27      crook    7178: @item
                   7179: If the string is not found in the dictionary, the text interpreter
1.29      crook    7180: attempts to treat it as a number, using the rules described in
                   7181: @ref{Number Conversion}. If the string represents a legal number in the
                   7182: current radix, the number is pushed onto a parameter stack (the data
                   7183: stack for integers, the floating-point stack for floating-point
                   7184: numbers).
                   7185: @end itemize
                   7186: 
                   7187: If both attempts fail, or if the word is found in the dictionary but has
                   7188: no interpretation semantics@footnote{This happens if the word was
                   7189: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   7190: remainder of the input buffer, issues an error message and waits for
                   7191: more input. If one of the attempts succeeds, the text interpreter
                   7192: repeats the parsing process until the whole of the input buffer has been
                   7193: processed, at which point it prints the status message ``@code{ ok}''
                   7194: and waits for more input.
                   7195: 
1.71      anton    7196: @c anton: this should be in the input stream subsection (or below it)
                   7197: 
1.29      crook    7198: @cindex parse area
                   7199: The text interpreter keeps track of its position in the input buffer by
                   7200: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   7201: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   7202: of the input buffer. The region from offset @code{>IN @@} to the end of
                   7203: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   7204: the text interpreter processes the contents of the input buffer by
                   7205: parsing strings from the parse area until the parse area is empty.}.
                   7206: This example shows how @code{>IN} changes as the text interpreter parses
                   7207: the input buffer:
                   7208: 
                   7209: @example
                   7210: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   7211:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   7212: 
                   7213: 1 2 3 remaining + remaining . 
                   7214: 
                   7215: : foo 1 2 3 remaining SWAP remaining ;
                   7216: @end example
                   7217: 
                   7218: @noindent
                   7219: The result is:
                   7220: 
                   7221: @example
                   7222: ->+ remaining .<-
                   7223: ->.<-5  ok
                   7224: 
                   7225: ->SWAP remaining ;-<
                   7226: ->;<-  ok
                   7227: @end example
                   7228: 
                   7229: @cindex parsing words
                   7230: The value of @code{>IN} can also be modified by a word in the input
                   7231: buffer that is executed by the text interpreter.  This means that a word
                   7232: can ``trick'' the text interpreter into either skipping a section of the
                   7233: input buffer@footnote{This is how parsing words work.} or into parsing a
                   7234: section twice. For example:
1.27      crook    7235: 
1.29      crook    7236: @example
1.71      anton    7237: : lat ." <<foo>>" ;
                   7238: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29      crook    7239: @end example
                   7240: 
                   7241: @noindent
                   7242: When @code{flat} is executed, this output is produced@footnote{Exercise
                   7243: for the reader: what would happen if the @code{3} were replaced with
                   7244: @code{4}?}:
                   7245: 
                   7246: @example
1.71      anton    7247: <<bar>><<foo>>
1.29      crook    7248: @end example
                   7249: 
1.71      anton    7250: This technique can be used to work around some of the interoperability
                   7251: problems of parsing words.  Of course, it's better to avoid parsing
                   7252: words where possible.
                   7253: 
1.29      crook    7254: @noindent
                   7255: Two important notes about the behaviour of the text interpreter:
1.27      crook    7256: 
                   7257: @itemize @bullet
                   7258: @item
                   7259: It processes each input string to completion before parsing additional
1.29      crook    7260: characters from the input buffer.
                   7261: @item
                   7262: It treats the input buffer as a read-only region (and so must your code).
                   7263: @end itemize
                   7264: 
                   7265: @noindent
                   7266: When the text interpreter is in compile state, its behaviour changes in
                   7267: these ways:
                   7268: 
                   7269: @itemize @bullet
                   7270: @item
                   7271: If a parsed string is found in the dictionary, the text interpreter will
                   7272: perform the word's @dfn{compilation semantics}. In most cases, this
                   7273: simply means that the execution semantics of the word will be appended
                   7274: to the current definition.
1.27      crook    7275: @item
1.29      crook    7276: When a number is encountered, it is compiled into the current definition
                   7277: (as a literal) rather than being pushed onto a parameter stack.
                   7278: @item
                   7279: If an error occurs, @code{state} is modified to put the text interpreter
                   7280: back into interpret state.
                   7281: @item
                   7282: Each time a line is entered from the keyboard, Gforth prints
                   7283: ``@code{ compiled}'' rather than `` @code{ok}''.
                   7284: @end itemize
                   7285: 
                   7286: @cindex text interpreter - input sources
                   7287: When the text interpreter is using an input device other than the
                   7288: keyboard, its behaviour changes in these ways:
                   7289: 
                   7290: @itemize @bullet
                   7291: @item
                   7292: When the parse area is empty, the text interpreter attempts to refill
                   7293: the input buffer from the input source. When the input source is
1.71      anton    7294: exhausted, the input source is set back to the previous input source.
1.29      crook    7295: @item
                   7296: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7297: time the parse area is emptied.
                   7298: @item
                   7299: If an error occurs, the input source is set back to the user input
                   7300: device.
1.27      crook    7301: @end itemize
1.21      crook    7302: 
1.49      anton    7303: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7304: 
1.26      crook    7305: doc->in
1.27      crook    7306: doc-source
                   7307: 
1.26      crook    7308: doc-tib
                   7309: doc-#tib
1.1       anton    7310: 
1.44      crook    7311: 
1.26      crook    7312: @menu
1.67      anton    7313: * Input Sources::               
                   7314: * Number Conversion::           
                   7315: * Interpret/Compile states::    
                   7316: * Literals::                    
                   7317: * Interpreter Directives::      
1.26      crook    7318: @end menu
1.1       anton    7319: 
1.29      crook    7320: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7321: @subsection Input Sources
                   7322: @cindex input sources
                   7323: @cindex text interpreter - input sources
                   7324: 
1.44      crook    7325: By default, the text interpreter processes input from the user input
1.29      crook    7326: device (the keyboard) when Forth starts up. The text interpreter can
                   7327: process input from any of these sources:
                   7328: 
                   7329: @itemize @bullet
                   7330: @item
                   7331: The user input device -- the keyboard.
                   7332: @item
                   7333: A file, using the words described in @ref{Forth source files}.
                   7334: @item
                   7335: A block, using the words described in @ref{Blocks}.
                   7336: @item
                   7337: A text string, using @code{evaluate}.
                   7338: @end itemize
                   7339: 
                   7340: A program can identify the current input device from the values of
                   7341: @code{source-id} and @code{blk}.
                   7342: 
1.44      crook    7343: 
1.29      crook    7344: doc-source-id
                   7345: doc-blk
                   7346: 
                   7347: doc-save-input
                   7348: doc-restore-input
                   7349: 
                   7350: doc-evaluate
1.1       anton    7351: 
1.29      crook    7352: 
1.44      crook    7353: 
1.29      crook    7354: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7355: @subsection Number Conversion
                   7356: @cindex number conversion
                   7357: @cindex double-cell numbers, input format
                   7358: @cindex input format for double-cell numbers
                   7359: @cindex single-cell numbers, input format
                   7360: @cindex input format for single-cell numbers
                   7361: @cindex floating-point numbers, input format
                   7362: @cindex input format for floating-point numbers
1.1       anton    7363: 
1.29      crook    7364: This section describes the rules that the text interpreter uses when it
                   7365: tries to convert a string into a number.
1.1       anton    7366: 
1.26      crook    7367: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7368: number base@footnote{For example, 0-9 when the number base is decimal or
                   7369: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7370: 
1.26      crook    7371: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7372: 
1.29      crook    7373: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7374: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7375: 
1.26      crook    7376: Let * represent any number of instances of the previous character
                   7377: (including none).
1.1       anton    7378: 
1.26      crook    7379: Let any other character represent itself.
1.1       anton    7380: 
1.29      crook    7381: @noindent
1.26      crook    7382: Now, the conversion rules are:
1.21      crook    7383: 
1.26      crook    7384: @itemize @bullet
                   7385: @item
                   7386: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7387: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7388: @item
                   7389: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7390: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7391: arithmetic. Examples are -45 -5681 -0
                   7392: @item
                   7393: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7394: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7395: (all three of these represent the same number).
1.26      crook    7396: @item
                   7397: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7398: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7399: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7400: -34.65 (all three of these represent the same number).
1.26      crook    7401: @item
1.29      crook    7402: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7403: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7404: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7405: number) +12.E-4
1.26      crook    7406: @end itemize
1.1       anton    7407: 
1.26      crook    7408: By default, the number base used for integer number conversion is given
1.35      anton    7409: by the contents of the variable @code{base}.  Note that a lot of
                   7410: confusion can result from unexpected values of @code{base}.  If you
                   7411: change @code{base} anywhere, make sure to save the old value and restore
                   7412: it afterwards.  In general I recommend keeping @code{base} decimal, and
                   7413: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7414: 
1.29      crook    7415: doc-dpl
1.26      crook    7416: doc-base
                   7417: doc-hex
                   7418: doc-decimal
1.1       anton    7419: 
1.44      crook    7420: 
1.26      crook    7421: @cindex '-prefix for character strings
                   7422: @cindex &-prefix for decimal numbers
                   7423: @cindex %-prefix for binary numbers
                   7424: @cindex $-prefix for hexadecimal numbers
1.35      anton    7425: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7426: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7427: implementing @code{$} etc. as parsing words that process the subsequent
                   7428: number in the input stream and push it onto the stack. For example, see
                   7429: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7430: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7431: is required between the prefix and the number.} before the first digit
                   7432: of an (integer) number. Four prefixes are supported:
1.1       anton    7433: 
1.26      crook    7434: @itemize @bullet
                   7435: @item
1.35      anton    7436: @code{&} -- decimal
1.26      crook    7437: @item
1.35      anton    7438: @code{%} -- binary
1.26      crook    7439: @item
1.35      anton    7440: @code{$} -- hexadecimal
1.26      crook    7441: @item
1.35      anton    7442: @code{'} -- base @code{max-char+1}
1.26      crook    7443: @end itemize
1.1       anton    7444: 
1.26      crook    7445: Here are some examples, with the equivalent decimal number shown after
                   7446: in braces:
1.1       anton    7447: 
1.26      crook    7448: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
                   7449: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
                   7450: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
                   7451: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    7452: 
1.26      crook    7453: @cindex number conversion - traps for the unwary
1.29      crook    7454: @noindent
1.26      crook    7455: Number conversion has a number of traps for the unwary:
1.1       anton    7456: 
1.26      crook    7457: @itemize @bullet
                   7458: @item
                   7459: You cannot determine the current number base using the code sequence
1.35      anton    7460: @code{base @@ .} -- the number base is always 10 in the current number
                   7461: base. Instead, use something like @code{base @@ dec.}
1.26      crook    7462: @item
                   7463: If the number base is set to a value greater than 14 (for example,
                   7464: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   7465: it to be intepreted as either a single-precision integer or a
                   7466: floating-point number (Gforth treats it as an integer). The ambiguity
                   7467: can be resolved by explicitly stating the sign of the mantissa and/or
                   7468: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   7469: ambiguity arises; either representation will be treated as a
                   7470: floating-point number.
                   7471: @item
1.29      crook    7472: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    7473: It is used to specify file types.
                   7474: @item
1.72      anton    7475: ANS Forth requires the @code{.} of a double-precision number to be the
                   7476: final character in the string.  Gforth allows the @code{.} to be
                   7477: anywhere after the first digit.
1.26      crook    7478: @item
                   7479: The number conversion process does not check for overflow.
                   7480: @item
1.72      anton    7481: In an ANS Forth program @code{base} is required to be decimal when
                   7482: converting floating-point numbers.  In Gforth, number conversion to
                   7483: floating-point numbers always uses base &10, irrespective of the value
                   7484: of @code{base}.
1.26      crook    7485: @end itemize
1.1       anton    7486: 
1.49      anton    7487: You can read numbers into your programs with the words described in
                   7488: @ref{Input}.
1.1       anton    7489: 
1.26      crook    7490: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
                   7491: @subsection Interpret/Compile states
                   7492: @cindex Interpret/Compile states
1.1       anton    7493: 
1.29      crook    7494: A standard program is not permitted to change @code{state}
                   7495: explicitly. However, it can change @code{state} implicitly, using the
                   7496: words @code{[} and @code{]}. When @code{[} is executed it switches
                   7497: @code{state} to interpret state, and therefore the text interpreter
                   7498: starts interpreting. When @code{]} is executed it switches @code{state}
                   7499: to compile state and therefore the text interpreter starts
1.44      crook    7500: compiling. The most common usage for these words is for switching into
                   7501: interpret state and back from within a colon definition; this technique
1.49      anton    7502: can be used to compile a literal (for an example, @pxref{Literals}) or
                   7503: for conditional compilation (for an example, @pxref{Interpreter
                   7504: Directives}).
1.44      crook    7505: 
1.35      anton    7506: 
                   7507: @c This is a bad example: It's non-standard, and it's not necessary.
                   7508: @c However, I can't think of a good example for switching into compile
                   7509: @c state when there is no current word (@code{state}-smart words are not a
                   7510: @c good reason).  So maybe we should use an example for switching into
                   7511: @c interpret @code{state} in a colon def. - anton
1.44      crook    7512: @c nac-> I agree. I started out by putting in the example, then realised
                   7513: @c that it was non-ANS, so wrote more words around it. I hope this
                   7514: @c re-written version is acceptable to you. I do want to keep the example
                   7515: @c as it is helpful for showing what is and what is not portable, particularly
                   7516: @c where it outlaws a style in common use.
                   7517: 
1.72      anton    7518: @c anton: it's more important to show what's portable.  After we have done
                   7519: @c that, we can also show what's not.  In any case, I intend to write a
                   7520: @c section Macros (or so) which will also deal with [ ].
1.35      anton    7521: 
1.44      crook    7522: @code{[} and @code{]} also give you the ability to switch into compile
                   7523: state and back, but we cannot think of any useful Standard application
                   7524: for this ability. Pre-ANS Forth textbooks have examples like this:
1.29      crook    7525: 
                   7526: @example
                   7527: : AA ." this is A" ;
                   7528: : BB ." this is B" ;
                   7529: : CC ." this is C" ;
                   7530: 
1.44      crook    7531: create table ] aa bb cc [
                   7532: 
1.29      crook    7533: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   7534:   cells table + @ execute ;
                   7535: @end example
                   7536: 
1.44      crook    7537: This example builds a jump table; @code{0 go} will display ``@code{this
                   7538: is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   7539: defining @code{table} like this:
1.29      crook    7540: 
                   7541: @example
1.44      crook    7542: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
1.29      crook    7543: @end example
                   7544: 
1.44      crook    7545: The problem with this code is that the definition of @code{table} is not
                   7546: portable -- it @i{compile}s execution tokens into code space. Whilst it
                   7547: @i{may} work on systems where code space and data space co-incide, the
1.29      crook    7548: Standard only allows data space to be assigned for a @code{CREATE}d
                   7549: word. In addition, the Standard only allows @code{@@} to access data
                   7550: space, whilst this example is using it to access code space. The only
                   7551: portable, Standard way to build this table is to build it in data space,
                   7552: like this:
                   7553: 
                   7554: @example
                   7555: create table ' aa , ' bb , ' cc ,
                   7556: @end example
                   7557: 
1.26      crook    7558: doc-state
                   7559: doc-[
                   7560: doc-]
1.1       anton    7561: 
1.44      crook    7562: 
1.26      crook    7563: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
                   7564: @subsection Literals
                   7565: @cindex Literals
1.21      crook    7566: 
1.29      crook    7567: Often, you want to use a number within a colon definition. When you do
                   7568: this, the text interpreter automatically compiles the number as a
                   7569: @i{literal}. A literal is a number whose run-time effect is to be pushed
                   7570: onto the stack.  If you had to do some maths to generate the number, you
                   7571: might write it like this:
                   7572: 
                   7573: @example
                   7574: : HOUR-TO-SEC ( n1 -- n2 )
                   7575:   60 *      \ to minutes
                   7576:   60 * ;    \ to seconds
                   7577: @end example
                   7578: 
                   7579: It is very clear what this definition is doing, but it's inefficient
                   7580: since it is performing 2 multiples at run-time. An alternative would be
                   7581: to write:
                   7582: 
                   7583: @example
                   7584: : HOUR-TO-SEC ( n1 -- n2 )
                   7585:   3600 * ;  \ to seconds
                   7586: @end example
                   7587: 
                   7588: Which does the same thing, and has the advantage of using a single
                   7589: multiply. Ideally, we'd like the efficiency of the second with the
                   7590: readability of the first.
                   7591: 
                   7592: @code{Literal} allows us to achieve that. It takes a number from the
                   7593: stack and lays it down in the current definition just as though the
                   7594: number had been typed directly into the definition. Our first attempt
                   7595: might look like this:
                   7596: 
                   7597: @example
                   7598: 60          \ mins per hour
                   7599: 60 *        \ seconds per minute
                   7600: : HOUR-TO-SEC ( n1 -- n2 )
                   7601:   Literal * ;  \ to seconds
                   7602: @end example
                   7603: 
                   7604: But this produces the error message @code{unstructured}. What happened?
                   7605: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
                   7606: @i{colon-sys} is implementation-defined. In other words, once we start a
                   7607: colon definition we can't portably access anything that was on the stack
                   7608: before the definition began@footnote{@cite{Two Problems in ANS Forth},
                   7609: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
                   7610: some situations where you might want to access stack items above
                   7611: colon-sys, and provides a solution to the problem.}. The correct way of
                   7612: solving this problem in this instance is to use @code{[ ]} like this:
                   7613: 
                   7614: @example
                   7615: : HOUR-TO-SEC ( n1 -- n2 )
                   7616:   [ 60          \ minutes per hour
                   7617:     60 * ]      \ seconds per minute
                   7618:   LITERAL * ;   \ to seconds
                   7619: @end example
1.23      crook    7620: 
1.44      crook    7621: 
1.26      crook    7622: doc-literal
                   7623: doc-]L
                   7624: doc-2literal
                   7625: doc-fliteral
1.1       anton    7626: 
1.44      crook    7627: 
1.48      anton    7628: @node Interpreter Directives,  , Literals, The Text Interpreter
1.26      crook    7629: @subsection Interpreter Directives
                   7630: @cindex interpreter directives
1.72      anton    7631: @cindex conditional compilation
1.1       anton    7632: 
1.29      crook    7633: These words are usually used in interpret state; typically to control
                   7634: which parts of a source file are processed by the text
1.26      crook    7635: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   7636: supplements these with a rich set of immediate control structure words
                   7637: to compensate for the fact that the non-immediate versions can only be
1.29      crook    7638: used in compile state (@pxref{Control Structures}). Typical usages:
                   7639: 
                   7640: @example
1.72      anton    7641: FALSE Constant HAVE-ASSEMBLER
1.29      crook    7642: .
                   7643: .
1.72      anton    7644: HAVE-ASSEMBLER [IF]
1.29      crook    7645: : ASSEMBLER-FEATURE
                   7646:   ...
                   7647: ;
                   7648: [ENDIF]
                   7649: .
                   7650: .
                   7651: : SEE
                   7652:   ... \ general-purpose SEE code
1.72      anton    7653:   [ HAVE-ASSEMBLER [IF] ]
1.29      crook    7654:   ... \ assembler-specific SEE code
                   7655:   [ [ENDIF] ]
                   7656: ;
                   7657: @end example
1.1       anton    7658: 
1.44      crook    7659: 
1.26      crook    7660: doc-[IF]
                   7661: doc-[ELSE]
                   7662: doc-[THEN]
                   7663: doc-[ENDIF]
1.1       anton    7664: 
1.26      crook    7665: doc-[IFDEF]
                   7666: doc-[IFUNDEF]
1.1       anton    7667: 
1.26      crook    7668: doc-[?DO]
                   7669: doc-[DO]
                   7670: doc-[FOR]
                   7671: doc-[LOOP]
                   7672: doc-[+LOOP]
                   7673: doc-[NEXT]
1.1       anton    7674: 
1.26      crook    7675: doc-[BEGIN]
                   7676: doc-[UNTIL]
                   7677: doc-[AGAIN]
                   7678: doc-[WHILE]
                   7679: doc-[REPEAT]
1.1       anton    7680: 
1.27      crook    7681: 
1.26      crook    7682: @c -------------------------------------------------------------
1.47      crook    7683: @node Word Lists, Environmental Queries, The Text Interpreter, Words
1.26      crook    7684: @section Word Lists
                   7685: @cindex word lists
1.32      anton    7686: @cindex header space
1.1       anton    7687: 
1.36      anton    7688: A wordlist is a list of named words; you can add new words and look up
                   7689: words by name (and you can remove words in a restricted way with
                   7690: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   7691: 
                   7692: @cindex search order stack
                   7693: The text interpreter searches the wordlists present in the search order
                   7694: (a stack of wordlists), from the top to the bottom.  Within each
                   7695: wordlist, the search starts conceptually at the newest word; i.e., if
                   7696: two words in a wordlist have the same name, the newer word is found.
1.1       anton    7697: 
1.26      crook    7698: @cindex compilation word list
1.36      anton    7699: New words are added to the @dfn{compilation wordlist} (aka current
                   7700: wordlist).
1.1       anton    7701: 
1.36      anton    7702: @cindex wid
                   7703: A word list is identified by a cell-sized word list identifier (@i{wid})
                   7704: in much the same way as a file is identified by a file handle. The
                   7705: numerical value of the wid has no (portable) meaning, and might change
                   7706: from session to session.
1.1       anton    7707: 
1.29      crook    7708: The ANS Forth ``Search order'' word set is intended to provide a set of
                   7709: low-level tools that allow various different schemes to be
1.74      anton    7710: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26      crook    7711: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    7712: Forth.
1.1       anton    7713: 
1.27      crook    7714: @comment TODO: locals section refers to here, saying that every word list (aka
                   7715: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78      anton    7716: @c anton: but better in a separate subsection on wordlist internals
1.1       anton    7717: 
1.45      crook    7718: @comment TODO: document markers, reveal, tables, mappedwordlist
                   7719: 
                   7720: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    7721: @comment word from the source files, rather than some alias.
1.44      crook    7722: 
1.26      crook    7723: doc-forth-wordlist
                   7724: doc-definitions
                   7725: doc-get-current
                   7726: doc-set-current
                   7727: doc-get-order
1.45      crook    7728: doc---gforthman-set-order
1.26      crook    7729: doc-wordlist
1.30      anton    7730: doc-table
1.79      anton    7731: doc->order
1.36      anton    7732: doc-previous
1.26      crook    7733: doc-also
1.45      crook    7734: doc---gforthman-forth
1.26      crook    7735: doc-only
1.45      crook    7736: doc---gforthman-order
1.15      anton    7737: 
1.26      crook    7738: doc-find
                   7739: doc-search-wordlist
1.15      anton    7740: 
1.26      crook    7741: doc-words
                   7742: doc-vlist
1.44      crook    7743: @c doc-words-deferred
1.1       anton    7744: 
1.74      anton    7745: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26      crook    7746: doc-root
                   7747: doc-vocabulary
                   7748: doc-seal
                   7749: doc-vocs
                   7750: doc-current
                   7751: doc-context
1.1       anton    7752: 
1.44      crook    7753: 
1.26      crook    7754: @menu
1.75      anton    7755: * Vocabularies::                
1.67      anton    7756: * Why use word lists?::         
1.75      anton    7757: * Word list example::           
1.26      crook    7758: @end menu
                   7759: 
1.75      anton    7760: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
                   7761: @subsection Vocabularies
                   7762: @cindex Vocabularies, detailed explanation
                   7763: 
                   7764: Here is an example of creating and using a new wordlist using ANS
                   7765: Forth words:
                   7766: 
                   7767: @example
                   7768: wordlist constant my-new-words-wordlist
                   7769: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
                   7770: 
                   7771: \ add it to the search order
                   7772: also my-new-words
                   7773: 
                   7774: \ alternatively, add it to the search order and make it
                   7775: \ the compilation word list
                   7776: also my-new-words definitions
                   7777: \ type "order" to see the problem
                   7778: @end example
                   7779: 
                   7780: The problem with this example is that @code{order} has no way to
                   7781: associate the name @code{my-new-words} with the wid of the word list (in
                   7782: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   7783: that has no associated name). There is no Standard way of associating a
                   7784: name with a wid.
                   7785: 
                   7786: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   7787: associates a name with a wid:
                   7788: 
                   7789: @example
                   7790: vocabulary my-new-words
                   7791: 
                   7792: \ add it to the search order
                   7793: also my-new-words
                   7794: 
                   7795: \ alternatively, add it to the search order and make it
                   7796: \ the compilation word list
                   7797: my-new-words definitions
                   7798: \ type "order" to see that the problem is solved
                   7799: @end example
                   7800: 
                   7801: 
                   7802: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26      crook    7803: @subsection Why use word lists?
                   7804: @cindex word lists - why use them?
                   7805: 
1.74      anton    7806: Here are some reasons why people use wordlists:
1.26      crook    7807: 
                   7808: @itemize @bullet
1.74      anton    7809: 
                   7810: @c anton: Gforth's hashing implementation makes the search speed
                   7811: @c independent from the number of words.  But it is linear with the number
                   7812: @c of wordlists that have to be searched, so in effect using more wordlists
                   7813: @c actually slows down compilation.
                   7814: 
                   7815: @c @item
                   7816: @c To improve compilation speed by reducing the number of header space
                   7817: @c entries that must be searched. This is achieved by creating a new
                   7818: @c word list that contains all of the definitions that are used in the
                   7819: @c definition of a Forth system but which would not usually be used by
                   7820: @c programs running on that system. That word list would be on the search
                   7821: @c list when the Forth system was compiled but would be removed from the
                   7822: @c search list for normal operation. This can be a useful technique for
                   7823: @c low-performance systems (for example, 8-bit processors in embedded
                   7824: @c systems) but is unlikely to be necessary in high-performance desktop
                   7825: @c systems.
                   7826: 
1.26      crook    7827: @item
                   7828: To prevent a set of words from being used outside the context in which
                   7829: they are valid. Two classic examples of this are an integrated editor
                   7830: (all of the edit commands are defined in a separate word list; the
                   7831: search order is set to the editor word list when the editor is invoked;
                   7832: the old search order is restored when the editor is terminated) and an
                   7833: integrated assembler (the op-codes for the machine are defined in a
                   7834: separate word list which is used when a @code{CODE} word is defined).
1.74      anton    7835: 
                   7836: @item
                   7837: To organize the words of an application or library into a user-visible
                   7838: set (in @code{forth-wordlist} or some other common wordlist) and a set
                   7839: of helper words used just for the implementation (hidden in a separate
1.75      anton    7840: wordlist).  This keeps @code{words}' output smaller, separates
                   7841: implementation and interface, and reduces the chance of name conflicts
                   7842: within the common wordlist.
1.74      anton    7843: 
1.26      crook    7844: @item
                   7845: To prevent a name-space clash between multiple definitions with the same
                   7846: name. For example, when building a cross-compiler you might have a word
                   7847: @code{IF} that generates conditional code for your target system. By
                   7848: placing this definition in a different word list you can control whether
                   7849: the host system's @code{IF} or the target system's @code{IF} get used in
                   7850: any particular context by controlling the order of the word lists on the
                   7851: search order stack.
1.74      anton    7852: 
1.26      crook    7853: @end itemize
1.1       anton    7854: 
1.74      anton    7855: The downsides of using wordlists are:
                   7856: 
                   7857: @itemize
                   7858: 
                   7859: @item
                   7860: Debugging becomes more cumbersome.
                   7861: 
                   7862: @item
                   7863: Name conflicts worked around with wordlists are still there, and you
                   7864: have to arrange the search order carefully to get the desired results;
                   7865: if you forget to do that, you get hard-to-find errors (as in any case
                   7866: where you read the code differently from the compiler; @code{see} can
1.75      anton    7867: help seeing which of several possible words the name resolves to in such
                   7868: cases).  @code{See} displays just the name of the words, not what
                   7869: wordlist they belong to, so it might be misleading.  Using unique names
                   7870: is a better approach to avoid name conflicts.
1.74      anton    7871: 
                   7872: @item
                   7873: You have to explicitly undo any changes to the search order.  In many
                   7874: cases it would be more convenient if this happened implicitly.  Gforth
                   7875: currently does not provide such a feature, but it may do so in the
                   7876: future.
                   7877: @end itemize
                   7878: 
                   7879: 
1.75      anton    7880: @node Word list example,  , Why use word lists?, Word Lists
                   7881: @subsection Word list example
                   7882: @cindex word lists - example
1.1       anton    7883: 
1.74      anton    7884: The following example is from the
                   7885: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   7886: garbage collector} and uses wordlists to separate public words from
                   7887: helper words:
                   7888: 
                   7889: @example
                   7890: get-current ( wid )
                   7891: vocabulary garbage-collector also garbage-collector definitions
                   7892: ... \ define helper words
                   7893: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
                   7894: ... \ define the public (i.e., API) words
                   7895:     \ they can refer to the helper words
                   7896: previous \ restore original search order (helper words become invisible)
                   7897: @end example
                   7898: 
1.26      crook    7899: @c -------------------------------------------------------------
                   7900: @node Environmental Queries, Files, Word Lists, Words
                   7901: @section Environmental Queries
                   7902: @cindex environmental queries
1.21      crook    7903: 
1.26      crook    7904: ANS Forth introduced the idea of ``environmental queries'' as a way
                   7905: for a program running on a system to determine certain characteristics of the system.
                   7906: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    7907: 
1.32      anton    7908: The Standard requires that the header space used for environmental queries
                   7909: be distinct from the header space used for definitions.
1.21      crook    7910: 
1.26      crook    7911: Typically, environmental queries are supported by creating a set of
1.29      crook    7912: definitions in a word list that is @i{only} used during environmental
1.26      crook    7913: queries; that is what Gforth does. There is no Standard way of adding
                   7914: definitions to the set of recognised environmental queries, but any
                   7915: implementation that supports the loading of optional word sets must have
                   7916: some mechanism for doing this (after loading the word set, the
                   7917: associated environmental query string must return @code{true}). In
                   7918: Gforth, the word list used to honour environmental queries can be
                   7919: manipulated just like any other word list.
1.21      crook    7920: 
1.44      crook    7921: 
1.26      crook    7922: doc-environment?
                   7923: doc-environment-wordlist
1.21      crook    7924: 
1.26      crook    7925: doc-gforth
                   7926: doc-os-class
1.21      crook    7927: 
1.44      crook    7928: 
1.26      crook    7929: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   7930: returning two items on the stack, querying it using @code{environment?}
                   7931: will return an additional item; the @code{true} flag that shows that the
                   7932: string was recognised.
1.21      crook    7933: 
1.26      crook    7934: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    7935: 
1.26      crook    7936: Here are some examples of using environmental queries:
1.21      crook    7937: 
1.26      crook    7938: @example
                   7939: s" address-unit-bits" environment? 0=
                   7940: [IF]
                   7941:      cr .( environmental attribute address-units-bits unknown... ) cr
1.75      anton    7942: [ELSE]
                   7943:      drop \ ensure balanced stack effect
1.26      crook    7944: [THEN]
1.21      crook    7945: 
1.75      anton    7946: \ this might occur in the prelude of a standard program that uses THROW
                   7947: s" exception" environment? [IF]
                   7948:    0= [IF]
                   7949:       : throw abort" exception thrown" ;
                   7950:    [THEN]
                   7951: [ELSE] \ we don't know, so make sure
                   7952:    : throw abort" exception thrown" ;
                   7953: [THEN]
1.21      crook    7954: 
1.26      crook    7955: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   7956:                         [ELSE] .( Not Gforth..) [THEN]
1.75      anton    7957: 
                   7958: \ a program using v*
                   7959: s" gforth" environment? [IF]
                   7960:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
                   7961:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   7962:      >r swap 2swap swap 0e r> 0 ?DO
                   7963:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
                   7964:      LOOP
                   7965:      2drop 2drop ; 
                   7966:   [THEN]
                   7967: [ELSE] \ 
                   7968:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   7969:   ...
                   7970: [THEN]
1.26      crook    7971: @end example
1.21      crook    7972: 
1.26      crook    7973: Here is an example of adding a definition to the environment word list:
1.21      crook    7974: 
1.26      crook    7975: @example
                   7976: get-current environment-wordlist set-current
                   7977: true constant block
                   7978: true constant block-ext
                   7979: set-current
                   7980: @end example
1.21      crook    7981: 
1.26      crook    7982: You can see what definitions are in the environment word list like this:
1.21      crook    7983: 
1.26      crook    7984: @example
1.79      anton    7985: environment-wordlist >order words previous
1.26      crook    7986: @end example
1.21      crook    7987: 
                   7988: 
1.26      crook    7989: @c -------------------------------------------------------------
                   7990: @node Files, Blocks, Environmental Queries, Words
                   7991: @section Files
1.28      crook    7992: @cindex files
                   7993: @cindex I/O - file-handling
1.21      crook    7994: 
1.26      crook    7995: Gforth provides facilities for accessing files that are stored in the
                   7996: host operating system's file-system. Files that are processed by Gforth
                   7997: can be divided into two categories:
1.21      crook    7998: 
1.23      crook    7999: @itemize @bullet
                   8000: @item
1.29      crook    8001: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    8002: @item
1.29      crook    8003: Files that are processed by some other program (@dfn{general files}).
1.26      crook    8004: @end itemize
                   8005: 
                   8006: @menu
1.48      anton    8007: * Forth source files::          
                   8008: * General files::               
                   8009: * Search Paths::                
1.26      crook    8010: @end menu
                   8011: 
                   8012: @c -------------------------------------------------------------
                   8013: @node Forth source files, General files, Files, Files
                   8014: @subsection Forth source files
                   8015: @cindex including files
                   8016: @cindex Forth source files
1.21      crook    8017: 
1.26      crook    8018: The simplest way to interpret the contents of a file is to use one of
                   8019: these two formats:
1.21      crook    8020: 
1.26      crook    8021: @example
                   8022: include mysource.fs
                   8023: s" mysource.fs" included
                   8024: @end example
1.21      crook    8025: 
1.75      anton    8026: You usually want to include a file only if it is not included already
1.26      crook    8027: (by, say, another source file). In that case, you can use one of these
1.45      crook    8028: three formats:
1.21      crook    8029: 
1.26      crook    8030: @example
                   8031: require mysource.fs
                   8032: needs mysource.fs
                   8033: s" mysource.fs" required
                   8034: @end example
1.21      crook    8035: 
1.26      crook    8036: @cindex stack effect of included files
                   8037: @cindex including files, stack effect
1.45      crook    8038: It is good practice to write your source files such that interpreting them
                   8039: does not change the stack. Source files designed in this way can be used with
1.26      crook    8040: @code{required} and friends without complications. For example:
1.21      crook    8041: 
1.26      crook    8042: @example
1.75      anton    8043: 1024 require foo.fs drop
1.26      crook    8044: @end example
1.21      crook    8045: 
1.75      anton    8046: Here you want to pass the argument 1024 (e.g., a buffer size) to
                   8047: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
                   8048: ), which allows its use with @code{require}.  Of course with such
                   8049: parameters to required files, you have to ensure that the first
                   8050: @code{require} fits for all uses (i.e., @code{require} it early in the
                   8051: master load file).
1.44      crook    8052: 
1.26      crook    8053: doc-include-file
                   8054: doc-included
1.28      crook    8055: doc-included?
1.26      crook    8056: doc-include
                   8057: doc-required
                   8058: doc-require
                   8059: doc-needs
1.75      anton    8060: @c doc-init-included-files @c internal
                   8061: @c doc-loadfilename @c internal word
                   8062: doc-sourcefilename
                   8063: doc-sourceline#
1.44      crook    8064: 
1.26      crook    8065: A definition in ANS Forth for @code{required} is provided in
                   8066: @file{compat/required.fs}.
1.21      crook    8067: 
1.26      crook    8068: @c -------------------------------------------------------------
                   8069: @node General files, Search Paths, Forth source files, Files
                   8070: @subsection General files
                   8071: @cindex general files
                   8072: @cindex file-handling
1.21      crook    8073: 
1.75      anton    8074: Files are opened/created by name and type. The following file access
                   8075: methods (FAMs) are recognised:
1.44      crook    8076: 
1.75      anton    8077: @cindex fam (file access method)
1.26      crook    8078: doc-r/o
                   8079: doc-r/w
                   8080: doc-w/o
                   8081: doc-bin
1.1       anton    8082: 
1.44      crook    8083: 
1.26      crook    8084: When a file is opened/created, it returns a file identifier,
1.29      crook    8085: @i{wfileid} that is used for all other file commands. All file
                   8086: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    8087: successful operation and an implementation-defined non-zero value in the
                   8088: case of an error.
1.21      crook    8089: 
1.44      crook    8090: 
1.26      crook    8091: doc-open-file
                   8092: doc-create-file
1.21      crook    8093: 
1.26      crook    8094: doc-close-file
                   8095: doc-delete-file
                   8096: doc-rename-file
                   8097: doc-read-file
                   8098: doc-read-line
                   8099: doc-write-file
                   8100: doc-write-line
                   8101: doc-emit-file
                   8102: doc-flush-file
1.21      crook    8103: 
1.26      crook    8104: doc-file-status
                   8105: doc-file-position
                   8106: doc-reposition-file
                   8107: doc-file-size
                   8108: doc-resize-file
1.21      crook    8109: 
1.44      crook    8110: 
1.26      crook    8111: @c ---------------------------------------------------------
1.48      anton    8112: @node Search Paths,  , General files, Files
1.26      crook    8113: @subsection Search Paths
                   8114: @cindex path for @code{included}
                   8115: @cindex file search path
                   8116: @cindex @code{include} search path
                   8117: @cindex search path for files
1.21      crook    8118: 
1.26      crook    8119: If you specify an absolute filename (i.e., a filename starting with
                   8120: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   8121: @samp{C:...})) for @code{included} and friends, that file is included
                   8122: just as you would expect.
1.21      crook    8123: 
1.75      anton    8124: If the filename starts with @file{./}, this refers to the directory that
                   8125: the present file was @code{included} from.  This allows files to include
                   8126: other files relative to their own position (irrespective of the current
                   8127: working directory or the absolute position).  This feature is essential
                   8128: for libraries consisting of several files, where a file may include
                   8129: other files from the library.  It corresponds to @code{#include "..."}
                   8130: in C. If the current input source is not a file, @file{.} refers to the
                   8131: directory of the innermost file being included, or, if there is no file
                   8132: being included, to the current working directory.
                   8133: 
                   8134: For relative filenames (not starting with @file{./}), Gforth uses a
                   8135: search path similar to Forth's search order (@pxref{Word Lists}). It
                   8136: tries to find the given filename in the directories present in the path,
                   8137: and includes the first one it finds. There are separate search paths for
                   8138: Forth source files and general files.  If the search path contains the
                   8139: directory @file{.}, this refers to the directory of the current file, or
                   8140: the working directory, as if the file had been specified with @file{./}.
1.21      crook    8141: 
1.26      crook    8142: Use @file{~+} to refer to the current working directory (as in the
                   8143: @code{bash}).
1.1       anton    8144: 
1.75      anton    8145: @c anton: fold the following subsubsections into this subsection?
1.1       anton    8146: 
1.48      anton    8147: @menu
1.75      anton    8148: * Source Search Paths::         
1.48      anton    8149: * General Search Paths::        
                   8150: @end menu
                   8151: 
1.26      crook    8152: @c ---------------------------------------------------------
1.75      anton    8153: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
                   8154: @subsubsection Source Search Paths
                   8155: @cindex search path control, source files
1.5       anton    8156: 
1.26      crook    8157: The search path is initialized when you start Gforth (@pxref{Invoking
1.75      anton    8158: Gforth}). You can display it and change it using @code{fpath} in
                   8159: combination with the general path handling words.
1.5       anton    8160: 
1.75      anton    8161: doc-fpath
                   8162: @c the functionality of the following words is easily available through
                   8163: @c   fpath and the general path words.  The may go away.
                   8164: @c doc-.fpath
                   8165: @c doc-fpath+
                   8166: @c doc-fpath=
                   8167: @c doc-open-fpath-file
1.44      crook    8168: 
                   8169: @noindent
1.26      crook    8170: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    8171: 
1.26      crook    8172: @example
1.75      anton    8173: fpath path= /usr/lib/forth/|./
1.26      crook    8174: require timer.fs
                   8175: @end example
1.5       anton    8176: 
1.75      anton    8177: 
1.26      crook    8178: @c ---------------------------------------------------------
1.75      anton    8179: @node General Search Paths,  , Source Search Paths, Search Paths
1.26      crook    8180: @subsubsection General Search Paths
1.75      anton    8181: @cindex search path control, source files
1.5       anton    8182: 
1.26      crook    8183: Your application may need to search files in several directories, like
                   8184: @code{included} does. To facilitate this, Gforth allows you to define
                   8185: and use your own search paths, by providing generic equivalents of the
                   8186: Forth search path words:
1.5       anton    8187: 
1.75      anton    8188: doc-open-path-file
                   8189: doc-path-allot
                   8190: doc-clear-path
                   8191: doc-also-path
1.26      crook    8192: doc-.path
                   8193: doc-path+
                   8194: doc-path=
1.5       anton    8195: 
1.75      anton    8196: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44      crook    8197: 
1.75      anton    8198: Here's an example of creating an empty search path:
                   8199: @c
1.26      crook    8200: @example
1.75      anton    8201: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26      crook    8202: @end example
1.5       anton    8203: 
1.26      crook    8204: @c -------------------------------------------------------------
                   8205: @node Blocks, Other I/O, Files, Words
                   8206: @section Blocks
1.28      crook    8207: @cindex I/O - blocks
                   8208: @cindex blocks
                   8209: 
                   8210: When you run Gforth on a modern desk-top computer, it runs under the
                   8211: control of an operating system which provides certain services.  One of
                   8212: these services is @var{file services}, which allows Forth source code
                   8213: and data to be stored in files and read into Gforth (@pxref{Files}).
                   8214: 
                   8215: Traditionally, Forth has been an important programming language on
                   8216: systems where it has interfaced directly to the underlying hardware with
                   8217: no intervening operating system. Forth provides a mechanism, called
1.29      crook    8218: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    8219: 
                   8220: A block is a 1024-byte data area, which can be used to hold data or
                   8221: Forth source code. No structure is imposed on the contents of the
                   8222: block. A block is identified by its number; blocks are numbered
                   8223: contiguously from 1 to an implementation-defined maximum.
                   8224: 
                   8225: A typical system that used blocks but no operating system might use a
                   8226: single floppy-disk drive for mass storage, with the disks formatted to
                   8227: provide 256-byte sectors. Blocks would be implemented by assigning the
                   8228: first four sectors of the disk to block 1, the second four sectors to
                   8229: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   8230: would not contain any file system information, just the set of blocks.
                   8231: 
1.29      crook    8232: @cindex blocks file
1.28      crook    8233: On systems that do provide file services, blocks are typically
1.29      crook    8234: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    8235: file}.  The size of the blocks file will be an exact multiple of 1024
                   8236: bytes, corresponding to the number of blocks it contains. This is the
                   8237: mechanism that Gforth uses.
                   8238: 
1.29      crook    8239: @cindex @file{blocks.fb}
1.75      anton    8240: Only one blocks file can be open at a time. If you use block words without
1.28      crook    8241: having specified a blocks file, Gforth defaults to the blocks file
                   8242: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75      anton    8243: locate a blocks file (@pxref{Source Search Paths}).
1.28      crook    8244: 
1.29      crook    8245: @cindex block buffers
1.28      crook    8246: When you read and write blocks under program control, Gforth uses a
1.29      crook    8247: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    8248: not used when you use @code{load} to interpret the contents of a block.
                   8249: 
1.75      anton    8250: The behaviour of the block buffers is analagous to that of a cache.
                   8251: Each block buffer has three states:
1.28      crook    8252: 
                   8253: @itemize @bullet
                   8254: @item
                   8255: Unassigned
                   8256: @item
                   8257: Assigned-clean
                   8258: @item
                   8259: Assigned-dirty
                   8260: @end itemize
                   8261: 
1.29      crook    8262: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    8263: block, the block (specified by its block number) must be assigned to a
                   8264: block buffer.
                   8265: 
                   8266: The assignment of a block to a block buffer is performed by @code{block}
                   8267: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   8268: contents of a block. Use @code{buffer} when you don't care about the
                   8269: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    8270: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    8271: with the particular block is already stored in a block buffer due to an
                   8272: earlier @code{block} command, @code{buffer} will return that block
                   8273: buffer and the existing contents of the block will be
                   8274: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    8275: block buffer for the block.}.
1.28      crook    8276: 
1.47      crook    8277: Once a block has been assigned to a block buffer using @code{block} or
1.75      anton    8278: @code{buffer}, that block buffer becomes the @i{current block
                   8279: buffer}. Data may only be manipulated (read or written) within the
                   8280: current block buffer.
1.47      crook    8281: 
                   8282: When the contents of the current block buffer has been modified it is
1.48      anton    8283: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75      anton    8284: either abandon the changes (by doing nothing) or mark the block as
                   8285: changed (assigned-dirty), using @code{update}. Using @code{update} does
                   8286: not change the blocks file; it simply changes a block buffer's state to
                   8287: @i{assigned-dirty}.  The block will be written implicitly when it's
                   8288: buffer is needed for another block, or explicitly by @code{flush} or
                   8289: @code{save-buffers}.
                   8290: 
                   8291: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
                   8292: blocks file on disk. Leaving Gforth with @code{bye} also performs a
                   8293: @code{flush}.
1.28      crook    8294: 
1.29      crook    8295: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    8296: algorithm to assign a block buffer to a block. That means that any
                   8297: particular block can only be assigned to one specific block buffer,
1.29      crook    8298: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    8299: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   8300: the new block immediately. If it is @i{assigned-dirty} its current
                   8301: contents are written back to the blocks file on disk before it is
1.28      crook    8302: allocated to the new block.
                   8303: 
                   8304: Although no structure is imposed on the contents of a block, it is
                   8305: traditional to display the contents as 16 lines each of 64 characters.  A
                   8306: block provides a single, continuous stream of input (for example, it
                   8307: acts as a single parse area) -- there are no end-of-line characters
                   8308: within a block, and no end-of-file character at the end of a
                   8309: block. There are two consequences of this:
1.26      crook    8310: 
1.28      crook    8311: @itemize @bullet
                   8312: @item
                   8313: The last character of one line wraps straight into the first character
                   8314: of the following line
                   8315: @item
                   8316: The word @code{\} -- comment to end of line -- requires special
                   8317: treatment; in the context of a block it causes all characters until the
                   8318: end of the current 64-character ``line'' to be ignored.
                   8319: @end itemize
                   8320: 
                   8321: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    8322: the current blocks file will be extended to the appropriate size and the
1.28      crook    8323: block buffer will be initialised with spaces.
                   8324: 
1.47      crook    8325: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   8326: for details) but doesn't encourage the use of blocks; the mechanism is
                   8327: only provided for backward compatibility -- ANS Forth requires blocks to
                   8328: be available when files are.
1.28      crook    8329: 
                   8330: Common techniques that are used when working with blocks include:
                   8331: 
                   8332: @itemize @bullet
                   8333: @item
                   8334: A screen editor that allows you to edit blocks without leaving the Forth
                   8335: environment.
                   8336: @item
                   8337: Shadow screens; where every code block has an associated block
                   8338: containing comments (for example: code in odd block numbers, comments in
                   8339: even block numbers). Typically, the block editor provides a convenient
                   8340: mechanism to toggle between code and comments.
                   8341: @item
                   8342: Load blocks; a single block (typically block 1) contains a number of
                   8343: @code{thru} commands which @code{load} the whole of the application.
                   8344: @end itemize
1.26      crook    8345: 
1.29      crook    8346: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   8347: integrated into a Forth programming environment.
1.26      crook    8348: 
                   8349: @comment TODO what about errors on open-blocks?
1.44      crook    8350: 
1.26      crook    8351: doc-open-blocks
                   8352: doc-use
1.75      anton    8353: doc-block-offset
1.26      crook    8354: doc-get-block-fid
                   8355: doc-block-position
1.28      crook    8356: 
1.75      anton    8357: doc-list
1.28      crook    8358: doc-scr
                   8359: 
1.45      crook    8360: doc---gforthman-block
1.28      crook    8361: doc-buffer
                   8362: 
1.75      anton    8363: doc-empty-buffers
                   8364: doc-empty-buffer
1.26      crook    8365: doc-update
1.28      crook    8366: doc-updated?
1.26      crook    8367: doc-save-buffers
1.75      anton    8368: doc-save-buffer
1.26      crook    8369: doc-flush
1.28      crook    8370: 
1.26      crook    8371: doc-load
                   8372: doc-thru
                   8373: doc-+load
                   8374: doc-+thru
1.45      crook    8375: doc---gforthman--->
1.26      crook    8376: doc-block-included
                   8377: 
1.44      crook    8378: 
1.26      crook    8379: @c -------------------------------------------------------------
1.78      anton    8380: @node Other I/O, Locals, Blocks, Words
1.26      crook    8381: @section Other I/O
1.28      crook    8382: @cindex I/O - keyboard and display
1.26      crook    8383: 
                   8384: @menu
                   8385: * Simple numeric output::       Predefined formats
                   8386: * Formatted numeric output::    Formatted (pictured) output
                   8387: * String Formats::              How Forth stores strings in memory
1.67      anton    8388: * Displaying characters and strings::  Other stuff
1.26      crook    8389: * Input::                       Input
                   8390: @end menu
                   8391: 
                   8392: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8393: @subsection Simple numeric output
1.28      crook    8394: @cindex numeric output - simple/free-format
1.5       anton    8395: 
1.26      crook    8396: The simplest output functions are those that display numbers from the
                   8397: data or floating-point stacks. Floating-point output is always displayed
                   8398: using base 10. Numbers displayed from the data stack use the value stored
                   8399: in @code{base}.
1.5       anton    8400: 
1.44      crook    8401: 
1.26      crook    8402: doc-.
                   8403: doc-dec.
                   8404: doc-hex.
                   8405: doc-u.
                   8406: doc-.r
                   8407: doc-u.r
                   8408: doc-d.
                   8409: doc-ud.
                   8410: doc-d.r
                   8411: doc-ud.r
                   8412: doc-f.
                   8413: doc-fe.
                   8414: doc-fs.
1.5       anton    8415: 
1.44      crook    8416: 
1.26      crook    8417: Examples of printing the number 1234.5678E23 in the different floating-point output
                   8418: formats are shown below:
1.5       anton    8419: 
                   8420: @example
1.26      crook    8421: f. 123456779999999000000000000.
                   8422: fe. 123.456779999999E24
                   8423: fs. 1.23456779999999E26
1.5       anton    8424: @end example
                   8425: 
                   8426: 
1.26      crook    8427: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   8428: @subsection Formatted numeric output
1.28      crook    8429: @cindex formatted numeric output
1.26      crook    8430: @cindex pictured numeric output
1.28      crook    8431: @cindex numeric output - formatted
1.26      crook    8432: 
1.29      crook    8433: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    8434: output} for formatted printing of integers.  In this technique, digits
                   8435: are extracted from the number (using the current output radix defined by
                   8436: @code{base}), converted to ASCII codes and appended to a string that is
                   8437: built in a scratch-pad area of memory (@pxref{core-idef,
                   8438: Implementation-defined options, Implementation-defined
                   8439: options}). Arbitrary characters can be appended to the string during the
                   8440: extraction process. The completed string is specified by an address
                   8441: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   8442: under program control.
1.5       anton    8443: 
1.75      anton    8444: All of the integer output words described in the previous section
                   8445: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
                   8446: numeric output.
1.5       anton    8447: 
1.47      crook    8448: Three important things to remember about pictured numeric output:
1.5       anton    8449: 
1.26      crook    8450: @itemize @bullet
                   8451: @item
1.28      crook    8452: It always operates on double-precision numbers; to display a
1.49      anton    8453: single-precision number, convert it first (for ways of doing this
                   8454: @pxref{Double precision}).
1.26      crook    8455: @item
1.28      crook    8456: It always treats the double-precision number as though it were
                   8457: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    8458: @item
                   8459: The string is built up from right to left; least significant digit first.
                   8460: @end itemize
1.5       anton    8461: 
1.44      crook    8462: 
1.26      crook    8463: doc-<#
1.47      crook    8464: doc-<<#
1.26      crook    8465: doc-#
                   8466: doc-#s
                   8467: doc-hold
                   8468: doc-sign
                   8469: doc-#>
1.47      crook    8470: doc-#>>
1.5       anton    8471: 
1.26      crook    8472: doc-represent
1.5       anton    8473: 
1.44      crook    8474: 
                   8475: @noindent
1.26      crook    8476: Here are some examples of using pictured numeric output:
1.5       anton    8477: 
                   8478: @example
1.26      crook    8479: : my-u. ( u -- )
                   8480:   \ Simplest use of pns.. behaves like Standard u. 
                   8481:   0              \ convert to unsigned double
1.75      anton    8482:   <<#            \ start conversion
1.26      crook    8483:   #s             \ convert all digits
                   8484:   #>             \ complete conversion
1.75      anton    8485:   TYPE SPACE     \ display, with trailing space
                   8486:   #>> ;          \ release hold area
1.5       anton    8487: 
1.26      crook    8488: : cents-only ( u -- )
                   8489:   0              \ convert to unsigned double
1.75      anton    8490:   <<#            \ start conversion
1.26      crook    8491:   # #            \ convert two least-significant digits
                   8492:   #>             \ complete conversion, discard other digits
1.75      anton    8493:   TYPE SPACE     \ display, with trailing space
                   8494:   #>> ;          \ release hold area
1.5       anton    8495: 
1.26      crook    8496: : dollars-and-cents ( u -- )
                   8497:   0              \ convert to unsigned double
1.75      anton    8498:   <<#            \ start conversion
1.26      crook    8499:   # #            \ convert two least-significant digits
                   8500:   [char] . hold  \ insert decimal point
                   8501:   #s             \ convert remaining digits
                   8502:   [char] $ hold  \ append currency symbol
                   8503:   #>             \ complete conversion
1.75      anton    8504:   TYPE SPACE     \ display, with trailing space
                   8505:   #>> ;          \ release hold area
1.5       anton    8506: 
1.26      crook    8507: : my-. ( n -- )
                   8508:   \ handling negatives.. behaves like Standard .
                   8509:   s>d            \ convert to signed double
                   8510:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8511:   <<#            \ start conversion
1.26      crook    8512:   #s             \ convert all digits
                   8513:   rot sign       \ get at sign byte, append "-" if needed
                   8514:   #>             \ complete conversion
1.75      anton    8515:   TYPE SPACE     \ display, with trailing space
                   8516:   #>> ;          \ release hold area
1.5       anton    8517: 
1.26      crook    8518: : account. ( n -- )
1.75      anton    8519:   \ accountants don't like minus signs, they use parentheses
1.26      crook    8520:   \ for negative numbers
                   8521:   s>d            \ convert to signed double
                   8522:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8523:   <<#            \ start conversion
1.26      crook    8524:   2 pick         \ get copy of sign byte
                   8525:   0< IF [char] ) hold THEN \ right-most character of output
                   8526:   #s             \ convert all digits
                   8527:   rot            \ get at sign byte
                   8528:   0< IF [char] ( hold THEN
                   8529:   #>             \ complete conversion
1.75      anton    8530:   TYPE SPACE     \ display, with trailing space
                   8531:   #>> ;          \ release hold area
                   8532: 
1.5       anton    8533: @end example
                   8534: 
1.26      crook    8535: Here are some examples of using these words:
1.5       anton    8536: 
                   8537: @example
1.26      crook    8538: 1 my-u. 1
                   8539: hex -1 my-u. decimal FFFFFFFF
                   8540: 1 cents-only 01
                   8541: 1234 cents-only 34
                   8542: 2 dollars-and-cents $0.02
                   8543: 1234 dollars-and-cents $12.34
                   8544: 123 my-. 123
                   8545: -123 my. -123
                   8546: 123 account. 123
                   8547: -456 account. (456)
1.5       anton    8548: @end example
                   8549: 
                   8550: 
1.26      crook    8551: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   8552: @subsection String Formats
1.27      crook    8553: @cindex strings - see character strings
                   8554: @cindex character strings - formats
1.28      crook    8555: @cindex I/O - see character strings
1.75      anton    8556: @cindex counted strings
                   8557: 
                   8558: @c anton: this does not really belong here; maybe the memory section,
                   8559: @c  or the principles chapter
1.26      crook    8560: 
1.27      crook    8561: Forth commonly uses two different methods for representing character
                   8562: strings:
1.26      crook    8563: 
                   8564: @itemize @bullet
                   8565: @item
                   8566: @cindex address of counted string
1.45      crook    8567: @cindex counted string
1.29      crook    8568: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   8569: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   8570: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    8571: memory.
                   8572: @item
1.29      crook    8573: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   8574: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    8575: first byte of the string.
                   8576: @end itemize
                   8577: 
                   8578: ANS Forth encourages the use of the second format when representing
1.75      anton    8579: strings.
1.26      crook    8580: 
1.44      crook    8581: 
1.26      crook    8582: doc-count
                   8583: 
1.44      crook    8584: 
1.49      anton    8585: For words that move, copy and search for strings see @ref{Memory
                   8586: Blocks}. For words that display characters and strings see
                   8587: @ref{Displaying characters and strings}.
1.26      crook    8588: 
                   8589: @node Displaying characters and strings, Input, String Formats, Other I/O
                   8590: @subsection Displaying characters and strings
1.27      crook    8591: @cindex characters - compiling and displaying
                   8592: @cindex character strings - compiling and displaying
1.26      crook    8593: 
                   8594: This section starts with a glossary of Forth words and ends with a set
                   8595: of examples.
                   8596: 
1.44      crook    8597: 
1.26      crook    8598: doc-bl
                   8599: doc-space
                   8600: doc-spaces
                   8601: doc-emit
                   8602: doc-toupper
                   8603: doc-."
                   8604: doc-.(
                   8605: doc-type
1.44      crook    8606: doc-typewhite
1.26      crook    8607: doc-cr
1.27      crook    8608: @cindex cursor control
1.26      crook    8609: doc-at-xy
                   8610: doc-page
                   8611: doc-s"
                   8612: doc-c"
                   8613: doc-char
                   8614: doc-[char]
                   8615: doc-sliteral
                   8616: 
1.44      crook    8617: 
                   8618: @noindent
1.26      crook    8619: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    8620: 
                   8621: @example
1.26      crook    8622: .( text-1)
                   8623: : my-word
                   8624:   ." text-2" cr
                   8625:   .( text-3)
                   8626: ;
                   8627: 
                   8628: ." text-4"
                   8629: 
                   8630: : my-char
                   8631:   [char] ALPHABET emit
                   8632:   char emit
                   8633: ;
1.5       anton    8634: @end example
                   8635: 
1.26      crook    8636: When you load this code into Gforth, the following output is generated:
1.5       anton    8637: 
1.26      crook    8638: @example
1.30      anton    8639: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    8640: @end example
1.5       anton    8641: 
1.26      crook    8642: @itemize @bullet
                   8643: @item
                   8644: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   8645: is an immediate word; it behaves in the same way whether it is used inside
                   8646: or outside a colon definition.
                   8647: @item
                   8648: Message @code{text-4} is displayed because of Gforth's added interpretation
                   8649: semantics for @code{."}.
                   8650: @item
1.29      crook    8651: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    8652: performs the compilation semantics for @code{."} within the definition of
                   8653: @code{my-word}.
                   8654: @end itemize
1.5       anton    8655: 
1.26      crook    8656: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    8657: 
1.26      crook    8658: @example
1.30      anton    8659: @kbd{my-word @key{RET}} text-2
1.26      crook    8660:  ok
1.30      anton    8661: @kbd{my-char fred @key{RET}} Af ok
                   8662: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    8663: @end example
1.5       anton    8664: 
                   8665: @itemize @bullet
                   8666: @item
1.26      crook    8667: Message @code{text-2} is displayed because of the run-time behaviour of
                   8668: @code{."}.
                   8669: @item
                   8670: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   8671: on the stack at run-time. @code{emit} always displays the character
                   8672: when @code{my-char} is executed.
                   8673: @item
                   8674: @code{char} parses a string at run-time and the second @code{emit} displays
                   8675: the first character of the string.
1.5       anton    8676: @item
1.26      crook    8677: If you type @code{see my-char} you can see that @code{[char]} discarded
                   8678: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   8679: definition of @code{my-char}.
1.5       anton    8680: @end itemize
                   8681: 
                   8682: 
                   8683: 
1.48      anton    8684: @node Input,  , Displaying characters and strings, Other I/O
1.26      crook    8685: @subsection Input
                   8686: @cindex input
1.28      crook    8687: @cindex I/O - see input
                   8688: @cindex parsing a string
1.5       anton    8689: 
1.49      anton    8690: For ways of storing character strings in memory see @ref{String Formats}.
1.5       anton    8691: 
1.27      crook    8692: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29      crook    8693: @comment then index them
1.27      crook    8694: 
1.44      crook    8695: 
1.27      crook    8696: doc-key
                   8697: doc-key?
1.45      crook    8698: doc-ekey
                   8699: doc-ekey?
                   8700: doc-ekey>char
1.26      crook    8701: doc->number
                   8702: doc->float
                   8703: doc-accept
1.27      crook    8704: doc-pad
1.75      anton    8705: @c anton: these belong in the input stream section
1.27      crook    8706: doc-parse
                   8707: doc-word
                   8708: doc-sword
1.75      anton    8709: doc-name
1.27      crook    8710: doc-refill
                   8711: @comment obsolescent words..
                   8712: doc-convert
1.26      crook    8713: doc-query
                   8714: doc-expect
1.27      crook    8715: doc-span
1.5       anton    8716: 
                   8717: 
1.78      anton    8718: @c -------------------------------------------------------------
                   8719: @node Locals, Structures, Other I/O, Words
                   8720: @section Locals
                   8721: @cindex locals
                   8722: 
                   8723: Local variables can make Forth programming more enjoyable and Forth
                   8724: programs easier to read. Unfortunately, the locals of ANS Forth are
                   8725: laden with restrictions. Therefore, we provide not only the ANS Forth
                   8726: locals wordset, but also our own, more powerful locals wordset (we
                   8727: implemented the ANS Forth locals wordset through our locals wordset).
1.44      crook    8728: 
1.78      anton    8729: The ideas in this section have also been published in M. Anton Ertl,
                   8730: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
                   8731: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12      anton    8732: 
                   8733: @menu
1.78      anton    8734: * Gforth locals::               
                   8735: * ANS Forth locals::            
1.5       anton    8736: @end menu
                   8737: 
1.78      anton    8738: @node Gforth locals, ANS Forth locals, Locals, Locals
                   8739: @subsection Gforth locals
                   8740: @cindex Gforth locals
                   8741: @cindex locals, Gforth style
1.5       anton    8742: 
1.78      anton    8743: Locals can be defined with
1.44      crook    8744: 
1.78      anton    8745: @example
                   8746: @{ local1 local2 ... -- comment @}
                   8747: @end example
                   8748: or
                   8749: @example
                   8750: @{ local1 local2 ... @}
                   8751: @end example
1.5       anton    8752: 
1.78      anton    8753: E.g.,
                   8754: @example
                   8755: : max @{ n1 n2 -- n3 @}
                   8756:  n1 n2 > if
                   8757:    n1
                   8758:  else
                   8759:    n2
                   8760:  endif ;
                   8761: @end example
1.44      crook    8762: 
1.78      anton    8763: The similarity of locals definitions with stack comments is intended. A
                   8764: locals definition often replaces the stack comment of a word. The order
                   8765: of the locals corresponds to the order in a stack comment and everything
                   8766: after the @code{--} is really a comment.
1.77      anton    8767: 
1.78      anton    8768: This similarity has one disadvantage: It is too easy to confuse locals
                   8769: declarations with stack comments, causing bugs and making them hard to
                   8770: find. However, this problem can be avoided by appropriate coding
                   8771: conventions: Do not use both notations in the same program. If you do,
                   8772: they should be distinguished using additional means, e.g. by position.
1.77      anton    8773: 
1.78      anton    8774: @cindex types of locals
                   8775: @cindex locals types
                   8776: The name of the local may be preceded by a type specifier, e.g.,
                   8777: @code{F:} for a floating point value:
1.5       anton    8778: 
1.78      anton    8779: @example
                   8780: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   8781: \ complex multiplication
                   8782:  Ar Br f* Ai Bi f* f-
                   8783:  Ar Bi f* Ai Br f* f+ ;
                   8784: @end example
1.44      crook    8785: 
1.78      anton    8786: @cindex flavours of locals
                   8787: @cindex locals flavours
                   8788: @cindex value-flavoured locals
                   8789: @cindex variable-flavoured locals
                   8790: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   8791: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   8792: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   8793: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   8794: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   8795: produces its address (which becomes invalid when the variable's scope is
                   8796: left). E.g., the standard word @code{emit} can be defined in terms of
                   8797: @code{type} like this:
1.5       anton    8798: 
1.78      anton    8799: @example
                   8800: : emit @{ C^ char* -- @}
                   8801:     char* 1 type ;
                   8802: @end example
1.5       anton    8803: 
1.78      anton    8804: @cindex default type of locals
                   8805: @cindex locals, default type
                   8806: A local without type specifier is a @code{W:} local. Both flavours of
                   8807: locals are initialized with values from the data or FP stack.
1.44      crook    8808: 
1.78      anton    8809: Currently there is no way to define locals with user-defined data
                   8810: structures, but we are working on it.
1.5       anton    8811: 
1.78      anton    8812: Gforth allows defining locals everywhere in a colon definition. This
                   8813: poses the following questions:
1.5       anton    8814: 
1.78      anton    8815: @menu
                   8816: * Where are locals visible by name?::  
                   8817: * How long do locals live?::    
                   8818: * Locals programming style::    
                   8819: * Locals implementation::       
                   8820: @end menu
1.44      crook    8821: 
1.78      anton    8822: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   8823: @subsubsection Where are locals visible by name?
                   8824: @cindex locals visibility
                   8825: @cindex visibility of locals
                   8826: @cindex scope of locals
1.5       anton    8827: 
1.78      anton    8828: Basically, the answer is that locals are visible where you would expect
                   8829: it in block-structured languages, and sometimes a little longer. If you
                   8830: want to restrict the scope of a local, enclose its definition in
                   8831: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    8832: 
                   8833: 
1.78      anton    8834: doc-scope
                   8835: doc-endscope
1.5       anton    8836: 
                   8837: 
1.78      anton    8838: These words behave like control structure words, so you can use them
                   8839: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   8840: arbitrary ways.
1.77      anton    8841: 
1.78      anton    8842: If you want a more exact answer to the visibility question, here's the
                   8843: basic principle: A local is visible in all places that can only be
                   8844: reached through the definition of the local@footnote{In compiler
                   8845: construction terminology, all places dominated by the definition of the
                   8846: local.}. In other words, it is not visible in places that can be reached
                   8847: without going through the definition of the local. E.g., locals defined
                   8848: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   8849: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   8850: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77      anton    8851: 
1.78      anton    8852: The reasoning behind this solution is: We want to have the locals
                   8853: visible as long as it is meaningful. The user can always make the
                   8854: visibility shorter by using explicit scoping. In a place that can
                   8855: only be reached through the definition of a local, the meaning of a
                   8856: local name is clear. In other places it is not: How is the local
                   8857: initialized at the control flow path that does not contain the
                   8858: definition? Which local is meant, if the same name is defined twice in
                   8859: two independent control flow paths?
1.77      anton    8860: 
1.78      anton    8861: This should be enough detail for nearly all users, so you can skip the
                   8862: rest of this section. If you really must know all the gory details and
                   8863: options, read on.
1.77      anton    8864: 
1.78      anton    8865: In order to implement this rule, the compiler has to know which places
                   8866: are unreachable. It knows this automatically after @code{AHEAD},
                   8867: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   8868: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   8869: compiler that the control flow never reaches that place. If
                   8870: @code{UNREACHABLE} is not used where it could, the only consequence is
                   8871: that the visibility of some locals is more limited than the rule above
                   8872: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   8873: lie to the compiler), buggy code will be produced.
1.77      anton    8874: 
1.5       anton    8875: 
1.78      anton    8876: doc-unreachable
1.5       anton    8877: 
1.23      crook    8878: 
1.78      anton    8879: Another problem with this rule is that at @code{BEGIN}, the compiler
                   8880: does not know which locals will be visible on the incoming
                   8881: back-edge. All problems discussed in the following are due to this
                   8882: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   8883: loops as examples; the discussion also applies to @code{?DO} and other
                   8884: loops). Perhaps the most insidious example is:
1.26      crook    8885: @example
1.78      anton    8886: AHEAD
                   8887: BEGIN
                   8888:   x
                   8889: [ 1 CS-ROLL ] THEN
                   8890:   @{ x @}
                   8891:   ...
                   8892: UNTIL
1.26      crook    8893: @end example
1.23      crook    8894: 
1.78      anton    8895: This should be legal according to the visibility rule. The use of
                   8896: @code{x} can only be reached through the definition; but that appears
                   8897: textually below the use.
                   8898: 
                   8899: From this example it is clear that the visibility rules cannot be fully
                   8900: implemented without major headaches. Our implementation treats common
                   8901: cases as advertised and the exceptions are treated in a safe way: The
                   8902: compiler makes a reasonable guess about the locals visible after a
                   8903: @code{BEGIN}; if it is too pessimistic, the
                   8904: user will get a spurious error about the local not being defined; if the
                   8905: compiler is too optimistic, it will notice this later and issue a
                   8906: warning. In the case above the compiler would complain about @code{x}
                   8907: being undefined at its use. You can see from the obscure examples in
                   8908: this section that it takes quite unusual control structures to get the
                   8909: compiler into trouble, and even then it will often do fine.
1.23      crook    8910: 
1.78      anton    8911: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   8912: is that all locals visible before the @code{BEGIN} will also be
                   8913: visible after the @code{BEGIN}. This guess is valid for all loops that
                   8914: are entered only through the @code{BEGIN}, in particular, for normal
                   8915: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   8916: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   8917: compiler. When the branch to the @code{BEGIN} is finally generated by
                   8918: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   8919: warns the user if it was too optimistic:
1.26      crook    8920: @example
1.78      anton    8921: IF
                   8922:   @{ x @}
                   8923: BEGIN
                   8924:   \ x ? 
                   8925: [ 1 cs-roll ] THEN
                   8926:   ...
                   8927: UNTIL
1.26      crook    8928: @end example
1.23      crook    8929: 
1.78      anton    8930: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   8931: optimistically assumes that it lives until the @code{THEN}. It notices
                   8932: this difference when it compiles the @code{UNTIL} and issues a
                   8933: warning. The user can avoid the warning, and make sure that @code{x}
                   8934: is not used in the wrong area by using explicit scoping:
                   8935: @example
                   8936: IF
                   8937:   SCOPE
                   8938:   @{ x @}
                   8939:   ENDSCOPE
                   8940: BEGIN
                   8941: [ 1 cs-roll ] THEN
                   8942:   ...
                   8943: UNTIL
                   8944: @end example
1.23      crook    8945: 
1.78      anton    8946: Since the guess is optimistic, there will be no spurious error messages
                   8947: about undefined locals.
1.44      crook    8948: 
1.78      anton    8949: If the @code{BEGIN} is not reachable from above (e.g., after
                   8950: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   8951: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   8952: defined later. Therefore, the compiler assumes that no locals are
                   8953: visible after the @code{BEGIN}. However, the user can use
                   8954: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   8955: visible at the BEGIN as at the point where the top control-flow stack
                   8956: item was created.
1.23      crook    8957: 
1.44      crook    8958: 
1.78      anton    8959: doc-assume-live
1.26      crook    8960: 
1.23      crook    8961: 
1.78      anton    8962: @noindent
                   8963: E.g.,
                   8964: @example
                   8965: @{ x @}
                   8966: AHEAD
                   8967: ASSUME-LIVE
                   8968: BEGIN
                   8969:   x
                   8970: [ 1 CS-ROLL ] THEN
                   8971:   ...
                   8972: UNTIL
                   8973: @end example
1.44      crook    8974: 
1.78      anton    8975: Other cases where the locals are defined before the @code{BEGIN} can be
                   8976: handled by inserting an appropriate @code{CS-ROLL} before the
                   8977: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   8978: behind the @code{ASSUME-LIVE}).
1.23      crook    8979: 
1.78      anton    8980: Cases where locals are defined after the @code{BEGIN} (but should be
                   8981: visible immediately after the @code{BEGIN}) can only be handled by
                   8982: rearranging the loop. E.g., the ``most insidious'' example above can be
                   8983: arranged into:
                   8984: @example
                   8985: BEGIN
                   8986:   @{ x @}
                   8987:   ... 0=
                   8988: WHILE
                   8989:   x
                   8990: REPEAT
                   8991: @end example
1.44      crook    8992: 
1.78      anton    8993: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
                   8994: @subsubsection How long do locals live?
                   8995: @cindex locals lifetime
                   8996: @cindex lifetime of locals
1.23      crook    8997: 
1.78      anton    8998: The right answer for the lifetime question would be: A local lives at
                   8999: least as long as it can be accessed. For a value-flavoured local this
                   9000: means: until the end of its visibility. However, a variable-flavoured
                   9001: local could be accessed through its address far beyond its visibility
                   9002: scope. Ultimately, this would mean that such locals would have to be
                   9003: garbage collected. Since this entails un-Forth-like implementation
                   9004: complexities, I adopted the same cowardly solution as some other
                   9005: languages (e.g., C): The local lives only as long as it is visible;
                   9006: afterwards its address is invalid (and programs that access it
                   9007: afterwards are erroneous).
1.23      crook    9008: 
1.78      anton    9009: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
                   9010: @subsubsection Locals programming style
                   9011: @cindex locals programming style
                   9012: @cindex programming style, locals
1.23      crook    9013: 
1.78      anton    9014: The freedom to define locals anywhere has the potential to change
                   9015: programming styles dramatically. In particular, the need to use the
                   9016: return stack for intermediate storage vanishes. Moreover, all stack
                   9017: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9018: determined arguments) can be eliminated: If the stack items are in the
                   9019: wrong order, just write a locals definition for all of them; then
                   9020: write the items in the order you want.
1.23      crook    9021: 
1.78      anton    9022: This seems a little far-fetched and eliminating stack manipulations is
                   9023: unlikely to become a conscious programming objective. Still, the number
                   9024: of stack manipulations will be reduced dramatically if local variables
                   9025: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
                   9026: a traditional implementation of @code{max}).
1.23      crook    9027: 
1.78      anton    9028: This shows one potential benefit of locals: making Forth programs more
                   9029: readable. Of course, this benefit will only be realized if the
                   9030: programmers continue to honour the principle of factoring instead of
                   9031: using the added latitude to make the words longer.
1.23      crook    9032: 
1.78      anton    9033: @cindex single-assignment style for locals
                   9034: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9035: every value-flavoured local has only a single assignment and many
                   9036: advantages of functional languages apply to Forth. I.e., programs are
                   9037: easier to analyse, to optimize and to read: It is clear from the
                   9038: definition what the local stands for, it does not turn into something
                   9039: different later.
1.23      crook    9040: 
1.78      anton    9041: E.g., a definition using @code{TO} might look like this:
                   9042: @example
                   9043: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9044:  u1 u2 min 0
                   9045:  ?do
                   9046:    addr1 c@@ addr2 c@@ -
                   9047:    ?dup-if
                   9048:      unloop exit
                   9049:    then
                   9050:    addr1 char+ TO addr1
                   9051:    addr2 char+ TO addr2
                   9052:  loop
                   9053:  u1 u2 - ;
1.26      crook    9054: @end example
1.78      anton    9055: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9056: every loop iteration. @code{strcmp} is a typical example of the
                   9057: readability problems of using @code{TO}. When you start reading
                   9058: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9059: string. Only near the end of the loop you realize that it is something
                   9060: else.
1.23      crook    9061: 
1.78      anton    9062: This can be avoided by defining two locals at the start of the loop that
                   9063: are initialized with the right value for the current iteration.
                   9064: @example
                   9065: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9066:  addr1 addr2
                   9067:  u1 u2 min 0 
                   9068:  ?do @{ s1 s2 @}
                   9069:    s1 c@@ s2 c@@ -
                   9070:    ?dup-if
                   9071:      unloop exit
                   9072:    then
                   9073:    s1 char+ s2 char+
                   9074:  loop
                   9075:  2drop
                   9076:  u1 u2 - ;
                   9077: @end example
                   9078: Here it is clear from the start that @code{s1} has a different value
                   9079: in every loop iteration.
1.23      crook    9080: 
1.78      anton    9081: @node Locals implementation,  , Locals programming style, Gforth locals
                   9082: @subsubsection Locals implementation
                   9083: @cindex locals implementation
                   9084: @cindex implementation of locals
1.23      crook    9085: 
1.78      anton    9086: @cindex locals stack
                   9087: Gforth uses an extra locals stack. The most compelling reason for
                   9088: this is that the return stack is not float-aligned; using an extra stack
                   9089: also eliminates the problems and restrictions of using the return stack
                   9090: as locals stack. Like the other stacks, the locals stack grows toward
                   9091: lower addresses. A few primitives allow an efficient implementation:
                   9092: 
                   9093: 
                   9094: doc-@local#
                   9095: doc-f@local#
                   9096: doc-laddr#
                   9097: doc-lp+!#
                   9098: doc-lp!
                   9099: doc->l
                   9100: doc-f>l
                   9101: 
                   9102: 
                   9103: In addition to these primitives, some specializations of these
                   9104: primitives for commonly occurring inline arguments are provided for
                   9105: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9106: @code{@@local#} for the inline argument 0. The following compiling words
                   9107: compile the right specialized version, or the general version, as
                   9108: appropriate:
1.23      crook    9109: 
1.5       anton    9110: 
1.78      anton    9111: doc-compile-@local
                   9112: doc-compile-f@local
                   9113: doc-compile-lp+!
1.5       anton    9114: 
                   9115: 
1.78      anton    9116: Combinations of conditional branches and @code{lp+!#} like
                   9117: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9118: is taken) are provided for efficiency and correctness in loops.
1.5       anton    9119: 
1.78      anton    9120: A special area in the dictionary space is reserved for keeping the
                   9121: local variable names. @code{@{} switches the dictionary pointer to this
                   9122: area and @code{@}} switches it back and generates the locals
                   9123: initializing code. @code{W:} etc.@ are normal defining words. This
                   9124: special area is cleared at the start of every colon definition.
1.5       anton    9125: 
1.78      anton    9126: @cindex word list for defining locals
                   9127: A special feature of Gforth's dictionary is used to implement the
                   9128: definition of locals without type specifiers: every word list (aka
                   9129: vocabulary) has its own methods for searching
                   9130: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   9131: with a special search method: When it is searched for a word, it
                   9132: actually creates that word using @code{W:}. @code{@{} changes the search
                   9133: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   9134: and then the word list for defining locals without type specifiers.
1.5       anton    9135: 
1.78      anton    9136: The lifetime rules support a stack discipline within a colon
                   9137: definition: The lifetime of a local is either nested with other locals
                   9138: lifetimes or it does not overlap them.
1.23      crook    9139: 
1.78      anton    9140: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   9141: pointer manipulation is generated. Between control structure words
                   9142: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   9143: is the simplest of the other three control flow words. It has to
                   9144: restore the locals stack depth of the corresponding @code{BEGIN}
                   9145: before branching. The code looks like this:
                   9146: @format
                   9147: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   9148: @code{branch} <begin>
                   9149: @end format
1.26      crook    9150: 
1.78      anton    9151: @code{UNTIL} is a little more complicated: If it branches back, it
                   9152: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   9153: the locals stack must not be changed. The compiler generates the
                   9154: following code:
                   9155: @format
                   9156: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   9157: @end format
                   9158: The locals stack pointer is only adjusted if the branch is taken.
1.44      crook    9159: 
1.78      anton    9160: @code{THEN} can produce somewhat inefficient code:
                   9161: @format
                   9162: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   9163: <orig target>:
                   9164: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   9165: @end format
                   9166: The second @code{lp+!#} adjusts the locals stack pointer from the
                   9167: level at the @i{orig} point to the level after the @code{THEN}. The
                   9168: first @code{lp+!#} adjusts the locals stack pointer from the current
                   9169: level to the level at the orig point, so the complete effect is an
                   9170: adjustment from the current level to the right level after the
                   9171: @code{THEN}.
1.26      crook    9172: 
1.78      anton    9173: @cindex locals information on the control-flow stack
                   9174: @cindex control-flow stack items, locals information
                   9175: In a conventional Forth implementation a dest control-flow stack entry
                   9176: is just the target address and an orig entry is just the address to be
                   9177: patched. Our locals implementation adds a word list to every orig or dest
                   9178: item. It is the list of locals visible (or assumed visible) at the point
                   9179: described by the entry. Our implementation also adds a tag to identify
                   9180: the kind of entry, in particular to differentiate between live and dead
                   9181: (reachable and unreachable) orig entries.
1.26      crook    9182: 
1.78      anton    9183: A few unusual operations have to be performed on locals word lists:
1.44      crook    9184: 
1.5       anton    9185: 
1.78      anton    9186: doc-common-list
                   9187: doc-sub-list?
                   9188: doc-list-size
1.52      anton    9189: 
                   9190: 
1.78      anton    9191: Several features of our locals word list implementation make these
                   9192: operations easy to implement: The locals word lists are organised as
                   9193: linked lists; the tails of these lists are shared, if the lists
                   9194: contain some of the same locals; and the address of a name is greater
                   9195: than the address of the names behind it in the list.
1.5       anton    9196: 
1.78      anton    9197: Another important implementation detail is the variable
                   9198: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   9199: determine if they can be reached directly or only through the branch
                   9200: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   9201: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   9202: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5       anton    9203: 
1.78      anton    9204: Counted loops are similar to other loops in most respects, but
                   9205: @code{LEAVE} requires special attention: It performs basically the same
                   9206: service as @code{AHEAD}, but it does not create a control-flow stack
                   9207: entry. Therefore the information has to be stored elsewhere;
                   9208: traditionally, the information was stored in the target fields of the
                   9209: branches created by the @code{LEAVE}s, by organizing these fields into a
                   9210: linked list. Unfortunately, this clever trick does not provide enough
                   9211: space for storing our extended control flow information. Therefore, we
                   9212: introduce another stack, the leave stack. It contains the control-flow
                   9213: stack entries for all unresolved @code{LEAVE}s.
1.44      crook    9214: 
1.78      anton    9215: Local names are kept until the end of the colon definition, even if
                   9216: they are no longer visible in any control-flow path. In a few cases
                   9217: this may lead to increased space needs for the locals name area, but
                   9218: usually less than reclaiming this space would cost in code size.
1.5       anton    9219: 
1.44      crook    9220: 
1.78      anton    9221: @node ANS Forth locals,  , Gforth locals, Locals
                   9222: @subsection ANS Forth locals
                   9223: @cindex locals, ANS Forth style
1.5       anton    9224: 
1.78      anton    9225: The ANS Forth locals wordset does not define a syntax for locals, but
                   9226: words that make it possible to define various syntaxes. One of the
                   9227: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   9228: wordset, i.e.:
1.29      crook    9229: 
                   9230: @example
1.78      anton    9231: @{ local1 local2 ... -- comment @}
                   9232: @end example
                   9233: @noindent
                   9234: or
                   9235: @example
                   9236: @{ local1 local2 ... @}
1.29      crook    9237: @end example
                   9238: 
1.78      anton    9239: The order of the locals corresponds to the order in a stack comment. The
                   9240: restrictions are:
1.5       anton    9241: 
1.78      anton    9242: @itemize @bullet
                   9243: @item
                   9244: Locals can only be cell-sized values (no type specifiers are allowed).
                   9245: @item
                   9246: Locals can be defined only outside control structures.
                   9247: @item
                   9248: Locals can interfere with explicit usage of the return stack. For the
                   9249: exact (and long) rules, see the standard. If you don't use return stack
                   9250: accessing words in a definition using locals, you will be all right. The
                   9251: purpose of this rule is to make locals implementation on the return
                   9252: stack easier.
                   9253: @item
                   9254: The whole definition must be in one line.
                   9255: @end itemize
1.5       anton    9256: 
1.78      anton    9257: Locals defined in ANS Forth behave like @code{VALUE}s
                   9258: (@pxref{Values}). I.e., they are initialized from the stack. Using their
                   9259: name produces their value. Their value can be changed using @code{TO}.
1.77      anton    9260: 
1.78      anton    9261: Since the syntax above is supported by Gforth directly, you need not do
                   9262: anything to use it. If you want to port a program using this syntax to
                   9263: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   9264: syntax on the other system.
1.5       anton    9265: 
1.78      anton    9266: Note that a syntax shown in the standard, section A.13 looks
                   9267: similar, but is quite different in having the order of locals
                   9268: reversed. Beware!
1.5       anton    9269: 
1.78      anton    9270: The ANS Forth locals wordset itself consists of one word:
1.5       anton    9271: 
1.78      anton    9272: doc-(local)
1.5       anton    9273: 
1.78      anton    9274: The ANS Forth locals extension wordset defines a syntax using
                   9275: @code{locals|}, but it is so awful that we strongly recommend not to use
                   9276: it. We have implemented this syntax to make porting to Gforth easy, but
                   9277: do not document it here. The problem with this syntax is that the locals
                   9278: are defined in an order reversed with respect to the standard stack
                   9279: comment notation, making programs harder to read, and easier to misread
                   9280: and miswrite. The only merit of this syntax is that it is easy to
                   9281: implement using the ANS Forth locals wordset.
1.53      anton    9282: 
                   9283: 
1.78      anton    9284: @c ----------------------------------------------------------
                   9285: @node Structures, Object-oriented Forth, Locals, Words
                   9286: @section  Structures
                   9287: @cindex structures
                   9288: @cindex records
1.53      anton    9289: 
1.78      anton    9290: This section presents the structure package that comes with Gforth. A
                   9291: version of the package implemented in ANS Forth is available in
                   9292: @file{compat/struct.fs}. This package was inspired by a posting on
                   9293: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   9294: possibly John Hayes). A version of this section has been published in
                   9295: M. Anton Ertl,
                   9296: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
                   9297: Another Forth Structures Package}, Forth Dimensions 19(3), pages
                   9298: 13--16. Marcel Hendrix provided helpful comments.
1.53      anton    9299: 
1.78      anton    9300: @menu
                   9301: * Why explicit structure support?::  
                   9302: * Structure Usage::             
                   9303: * Structure Naming Convention::  
                   9304: * Structure Implementation::    
                   9305: * Structure Glossary::          
                   9306: @end menu
1.55      anton    9307: 
1.78      anton    9308: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   9309: @subsection Why explicit structure support?
1.53      anton    9310: 
1.78      anton    9311: @cindex address arithmetic for structures
                   9312: @cindex structures using address arithmetic
                   9313: If we want to use a structure containing several fields, we could simply
                   9314: reserve memory for it, and access the fields using address arithmetic
                   9315: (@pxref{Address arithmetic}). As an example, consider a structure with
                   9316: the following fields
1.57      anton    9317: 
1.78      anton    9318: @table @code
                   9319: @item a
                   9320: is a float
                   9321: @item b
                   9322: is a cell
                   9323: @item c
                   9324: is a float
                   9325: @end table
1.57      anton    9326: 
1.78      anton    9327: Given the (float-aligned) base address of the structure we get the
                   9328: address of the field
1.52      anton    9329: 
1.78      anton    9330: @table @code
                   9331: @item a
                   9332: without doing anything further.
                   9333: @item b
                   9334: with @code{float+}
                   9335: @item c
                   9336: with @code{float+ cell+ faligned}
                   9337: @end table
1.52      anton    9338: 
1.78      anton    9339: It is easy to see that this can become quite tiring. 
1.52      anton    9340: 
1.78      anton    9341: Moreover, it is not very readable, because seeing a
                   9342: @code{cell+} tells us neither which kind of structure is
                   9343: accessed nor what field is accessed; we have to somehow infer the kind
                   9344: of structure, and then look up in the documentation, which field of
                   9345: that structure corresponds to that offset.
1.53      anton    9346: 
1.78      anton    9347: Finally, this kind of address arithmetic also causes maintenance
                   9348: troubles: If you add or delete a field somewhere in the middle of the
                   9349: structure, you have to find and change all computations for the fields
                   9350: afterwards.
1.52      anton    9351: 
1.78      anton    9352: So, instead of using @code{cell+} and friends directly, how
                   9353: about storing the offsets in constants:
1.52      anton    9354: 
1.78      anton    9355: @example
                   9356: 0 constant a-offset
                   9357: 0 float+ constant b-offset
                   9358: 0 float+ cell+ faligned c-offset
                   9359: @end example
1.64      pazsan   9360: 
1.78      anton    9361: Now we can get the address of field @code{x} with @code{x-offset
                   9362: +}. This is much better in all respects. Of course, you still
                   9363: have to change all later offset definitions if you add a field. You can
                   9364: fix this by declaring the offsets in the following way:
1.57      anton    9365: 
1.78      anton    9366: @example
                   9367: 0 constant a-offset
                   9368: a-offset float+ constant b-offset
                   9369: b-offset cell+ faligned constant c-offset
                   9370: @end example
1.57      anton    9371: 
1.78      anton    9372: Since we always use the offsets with @code{+}, we could use a defining
                   9373: word @code{cfield} that includes the @code{+} in the action of the
                   9374: defined word:
1.64      pazsan   9375: 
1.78      anton    9376: @example
                   9377: : cfield ( n "name" -- )
                   9378:     create ,
                   9379: does> ( name execution: addr1 -- addr2 )
                   9380:     @@ + ;
1.64      pazsan   9381: 
1.78      anton    9382: 0 cfield a
                   9383: 0 a float+ cfield b
                   9384: 0 b cell+ faligned cfield c
                   9385: @end example
1.64      pazsan   9386: 
1.78      anton    9387: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64      pazsan   9388: 
1.78      anton    9389: The structure field words now can be used quite nicely. However,
                   9390: their definition is still a bit cumbersome: We have to repeat the
                   9391: name, the information about size and alignment is distributed before
                   9392: and after the field definitions etc.  The structure package presented
                   9393: here addresses these problems.
1.64      pazsan   9394: 
1.78      anton    9395: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   9396: @subsection Structure Usage
                   9397: @cindex structure usage
1.57      anton    9398: 
1.78      anton    9399: @cindex @code{field} usage
                   9400: @cindex @code{struct} usage
                   9401: @cindex @code{end-struct} usage
                   9402: You can define a structure for a (data-less) linked list with:
1.57      anton    9403: @example
1.78      anton    9404: struct
                   9405:     cell% field list-next
                   9406: end-struct list%
1.57      anton    9407: @end example
                   9408: 
1.78      anton    9409: With the address of the list node on the stack, you can compute the
                   9410: address of the field that contains the address of the next node with
                   9411: @code{list-next}. E.g., you can determine the length of a list
                   9412: with:
1.57      anton    9413: 
                   9414: @example
1.78      anton    9415: : list-length ( list -- n )
                   9416: \ "list" is a pointer to the first element of a linked list
                   9417: \ "n" is the length of the list
                   9418:     0 BEGIN ( list1 n1 )
                   9419:         over
                   9420:     WHILE ( list1 n1 )
                   9421:         1+ swap list-next @@ swap
                   9422:     REPEAT
                   9423:     nip ;
1.57      anton    9424: @end example
                   9425: 
1.78      anton    9426: You can reserve memory for a list node in the dictionary with
                   9427: @code{list% %allot}, which leaves the address of the list node on the
                   9428: stack. For the equivalent allocation on the heap you can use @code{list%
                   9429: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   9430: use @code{list% %allocate}). You can get the the size of a list
                   9431: node with @code{list% %size} and its alignment with @code{list%
                   9432: %alignment}.
                   9433: 
                   9434: Note that in ANS Forth the body of a @code{create}d word is
                   9435: @code{aligned} but not necessarily @code{faligned};
                   9436: therefore, if you do a:
1.57      anton    9437: 
                   9438: @example
1.78      anton    9439: create @emph{name} foo% %allot drop
1.57      anton    9440: @end example
                   9441: 
1.78      anton    9442: @noindent
                   9443: then the memory alloted for @code{foo%} is guaranteed to start at the
                   9444: body of @code{@emph{name}} only if @code{foo%} contains only character,
                   9445: cell and double fields.  Therefore, if your structure contains floats,
                   9446: better use
1.57      anton    9447: 
                   9448: @example
1.78      anton    9449: foo% %allot constant @emph{name}
1.57      anton    9450: @end example
                   9451: 
1.78      anton    9452: @cindex structures containing structures
                   9453: You can include a structure @code{foo%} as a field of
                   9454: another structure, like this:
1.65      anton    9455: @example
1.78      anton    9456: struct
                   9457: ...
                   9458:     foo% field ...
                   9459: ...
                   9460: end-struct ...
1.65      anton    9461: @end example
1.52      anton    9462: 
1.78      anton    9463: @cindex structure extension
                   9464: @cindex extended records
                   9465: Instead of starting with an empty structure, you can extend an
                   9466: existing structure. E.g., a plain linked list without data, as defined
                   9467: above, is hardly useful; You can extend it to a linked list of integers,
                   9468: like this:@footnote{This feature is also known as @emph{extended
                   9469: records}. It is the main innovation in the Oberon language; in other
                   9470: words, adding this feature to Modula-2 led Wirth to create a new
                   9471: language, write a new compiler etc.  Adding this feature to Forth just
                   9472: required a few lines of code.}
1.52      anton    9473: 
1.78      anton    9474: @example
                   9475: list%
                   9476:     cell% field intlist-int
                   9477: end-struct intlist%
                   9478: @end example
1.55      anton    9479: 
1.78      anton    9480: @code{intlist%} is a structure with two fields:
                   9481: @code{list-next} and @code{intlist-int}.
1.55      anton    9482: 
1.78      anton    9483: @cindex structures containing arrays
                   9484: You can specify an array type containing @emph{n} elements of
                   9485: type @code{foo%} like this:
1.55      anton    9486: 
                   9487: @example
1.78      anton    9488: foo% @emph{n} *
1.56      anton    9489: @end example
1.55      anton    9490: 
1.78      anton    9491: You can use this array type in any place where you can use a normal
                   9492: type, e.g., when defining a @code{field}, or with
                   9493: @code{%allot}.
                   9494: 
                   9495: @cindex first field optimization
                   9496: The first field is at the base address of a structure and the word for
                   9497: this field (e.g., @code{list-next}) actually does not change the address
                   9498: on the stack. You may be tempted to leave it away in the interest of
                   9499: run-time and space efficiency. This is not necessary, because the
                   9500: structure package optimizes this case: If you compile a first-field
                   9501: words, no code is generated. So, in the interest of readability and
                   9502: maintainability you should include the word for the field when accessing
                   9503: the field.
1.52      anton    9504: 
                   9505: 
1.78      anton    9506: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   9507: @subsection Structure Naming Convention
                   9508: @cindex structure naming convention
1.52      anton    9509: 
1.78      anton    9510: The field names that come to (my) mind are often quite generic, and,
                   9511: if used, would cause frequent name clashes. E.g., many structures
                   9512: probably contain a @code{counter} field. The structure names
                   9513: that come to (my) mind are often also the logical choice for the names
                   9514: of words that create such a structure.
1.52      anton    9515: 
1.78      anton    9516: Therefore, I have adopted the following naming conventions: 
1.52      anton    9517: 
1.78      anton    9518: @itemize @bullet
                   9519: @cindex field naming convention
                   9520: @item
                   9521: The names of fields are of the form
                   9522: @code{@emph{struct}-@emph{field}}, where
                   9523: @code{@emph{struct}} is the basic name of the structure, and
                   9524: @code{@emph{field}} is the basic name of the field. You can
                   9525: think of field words as converting the (address of the)
                   9526: structure into the (address of the) field.
1.52      anton    9527: 
1.78      anton    9528: @cindex structure naming convention
                   9529: @item
                   9530: The names of structures are of the form
                   9531: @code{@emph{struct}%}, where
                   9532: @code{@emph{struct}} is the basic name of the structure.
                   9533: @end itemize
1.52      anton    9534: 
1.78      anton    9535: This naming convention does not work that well for fields of extended
                   9536: structures; e.g., the integer list structure has a field
                   9537: @code{intlist-int}, but has @code{list-next}, not
                   9538: @code{intlist-next}.
1.53      anton    9539: 
1.78      anton    9540: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   9541: @subsection Structure Implementation
                   9542: @cindex structure implementation
                   9543: @cindex implementation of structures
1.52      anton    9544: 
1.78      anton    9545: The central idea in the implementation is to pass the data about the
                   9546: structure being built on the stack, not in some global
                   9547: variable. Everything else falls into place naturally once this design
                   9548: decision is made.
1.53      anton    9549: 
1.78      anton    9550: The type description on the stack is of the form @emph{align
                   9551: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   9552: very simple.
1.53      anton    9553: 
1.78      anton    9554: @code{field} is a defining word that uses @code{Create}
                   9555: and @code{DOES>}. The body of the field contains the offset
                   9556: of the field, and the normal @code{DOES>} action is simply:
1.53      anton    9557: 
                   9558: @example
1.78      anton    9559: @@ +
1.53      anton    9560: @end example
                   9561: 
1.78      anton    9562: @noindent
                   9563: i.e., add the offset to the address, giving the stack effect
                   9564: @i{addr1 -- addr2} for a field.
                   9565: 
                   9566: @cindex first field optimization, implementation
                   9567: This simple structure is slightly complicated by the optimization
                   9568: for fields with offset 0, which requires a different
                   9569: @code{DOES>}-part (because we cannot rely on there being
                   9570: something on the stack if such a field is invoked during
                   9571: compilation). Therefore, we put the different @code{DOES>}-parts
                   9572: in separate words, and decide which one to invoke based on the
                   9573: offset. For a zero offset, the field is basically a noop; it is
                   9574: immediate, and therefore no code is generated when it is compiled.
1.53      anton    9575: 
1.78      anton    9576: @node Structure Glossary,  , Structure Implementation, Structures
                   9577: @subsection Structure Glossary
                   9578: @cindex structure glossary
1.53      anton    9579: 
1.5       anton    9580: 
1.78      anton    9581: doc-%align
                   9582: doc-%alignment
                   9583: doc-%alloc
                   9584: doc-%allocate
                   9585: doc-%allot
                   9586: doc-cell%
                   9587: doc-char%
                   9588: doc-dfloat%
                   9589: doc-double%
                   9590: doc-end-struct
                   9591: doc-field
                   9592: doc-float%
                   9593: doc-naligned
                   9594: doc-sfloat%
                   9595: doc-%size
                   9596: doc-struct
1.54      anton    9597: 
                   9598: 
1.26      crook    9599: @c -------------------------------------------------------------
1.78      anton    9600: @node Object-oriented Forth, Programming Tools, Structures, Words
                   9601: @section Object-oriented Forth
                   9602: 
                   9603: Gforth comes with three packages for object-oriented programming:
                   9604: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   9605: is preloaded, so you have to @code{include} them before use. The most
                   9606: important differences between these packages (and others) are discussed
                   9607: in @ref{Comparison with other object models}. All packages are written
                   9608: in ANS Forth and can be used with any other ANS Forth.
1.5       anton    9609: 
1.78      anton    9610: @menu
                   9611: * Why object-oriented programming?::  
                   9612: * Object-Oriented Terminology::  
                   9613: * Objects::                     
                   9614: * OOF::                         
                   9615: * Mini-OOF::                    
                   9616: * Comparison with other object models::  
                   9617: @end menu
1.5       anton    9618: 
1.78      anton    9619: @c ----------------------------------------------------------------
                   9620: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   9621: @subsection Why object-oriented programming?
                   9622: @cindex object-oriented programming motivation
                   9623: @cindex motivation for object-oriented programming
1.44      crook    9624: 
1.78      anton    9625: Often we have to deal with several data structures (@emph{objects}),
                   9626: that have to be treated similarly in some respects, but differently in
                   9627: others. Graphical objects are the textbook example: circles, triangles,
                   9628: dinosaurs, icons, and others, and we may want to add more during program
                   9629: development. We want to apply some operations to any graphical object,
                   9630: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   9631: has to do something different for every kind of object.
                   9632: @comment TODO add some other operations eg perimeter, area
                   9633: @comment and tie in to concrete examples later..
1.5       anton    9634: 
1.78      anton    9635: We could implement @code{draw} as a big @code{CASE}
                   9636: control structure that executes the appropriate code depending on the
                   9637: kind of object to be drawn. This would be not be very elegant, and,
                   9638: moreover, we would have to change @code{draw} every time we add
                   9639: a new kind of graphical object (say, a spaceship).
1.44      crook    9640: 
1.78      anton    9641: What we would rather do is: When defining spaceships, we would tell
                   9642: the system: ``Here's how you @code{draw} a spaceship; you figure
                   9643: out the rest''.
1.5       anton    9644: 
1.78      anton    9645: This is the problem that all systems solve that (rightfully) call
                   9646: themselves object-oriented; the object-oriented packages presented here
                   9647: solve this problem (and not much else).
                   9648: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44      crook    9649: 
1.78      anton    9650: @c ------------------------------------------------------------------------
                   9651: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   9652: @subsection Object-Oriented Terminology
                   9653: @cindex object-oriented terminology
                   9654: @cindex terminology for object-oriented programming
1.5       anton    9655: 
1.78      anton    9656: This section is mainly for reference, so you don't have to understand
                   9657: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   9658: short:
1.44      crook    9659: 
1.78      anton    9660: @table @emph
                   9661: @cindex class
                   9662: @item class
                   9663: a data structure definition with some extras.
1.5       anton    9664: 
1.78      anton    9665: @cindex object
                   9666: @item object
                   9667: an instance of the data structure described by the class definition.
1.5       anton    9668: 
1.78      anton    9669: @cindex instance variables
                   9670: @item instance variables
                   9671: fields of the data structure.
1.5       anton    9672: 
1.78      anton    9673: @cindex selector
                   9674: @cindex method selector
                   9675: @cindex virtual function
                   9676: @item selector
                   9677: (or @emph{method selector}) a word (e.g.,
                   9678: @code{draw}) that performs an operation on a variety of data
                   9679: structures (classes). A selector describes @emph{what} operation to
                   9680: perform. In C++ terminology: a (pure) virtual function.
1.5       anton    9681: 
1.78      anton    9682: @cindex method
                   9683: @item method
                   9684: the concrete definition that performs the operation
                   9685: described by the selector for a specific class. A method specifies
                   9686: @emph{how} the operation is performed for a specific class.
1.5       anton    9687: 
1.78      anton    9688: @cindex selector invocation
                   9689: @cindex message send
                   9690: @cindex invoking a selector
                   9691: @item selector invocation
                   9692: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   9693: is used for determining which method is used. In Smalltalk terminology:
                   9694: a message (consisting of the selector and the other arguments) is sent
                   9695: to the object.
1.5       anton    9696: 
1.78      anton    9697: @cindex receiving object
                   9698: @item receiving object
                   9699: the object used for determining the method executed by a selector
                   9700: invocation. In the @file{objects.fs} model, it is the object that is on
                   9701: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   9702: the Smalltalk @emph{message} terminology.)
1.5       anton    9703: 
1.78      anton    9704: @cindex child class
                   9705: @cindex parent class
                   9706: @cindex inheritance
                   9707: @item child class
                   9708: a class that has (@emph{inherits}) all properties (instance variables,
                   9709: selectors, methods) from a @emph{parent class}. In Smalltalk
                   9710: terminology: The subclass inherits from the superclass. In C++
                   9711: terminology: The derived class inherits from the base class.
1.5       anton    9712: 
1.78      anton    9713: @end table
1.5       anton    9714: 
1.78      anton    9715: @c If you wonder about the message sending terminology, it comes from
                   9716: @c a time when each object had it's own task and objects communicated via
                   9717: @c message passing; eventually the Smalltalk developers realized that
                   9718: @c they can do most things through simple (indirect) calls. They kept the
                   9719: @c terminology.
1.5       anton    9720: 
1.78      anton    9721: @c --------------------------------------------------------------
                   9722: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   9723: @subsection The @file{objects.fs} model
                   9724: @cindex objects
                   9725: @cindex object-oriented programming
1.26      crook    9726: 
1.78      anton    9727: @cindex @file{objects.fs}
                   9728: @cindex @file{oof.fs}
1.26      crook    9729: 
1.78      anton    9730: This section describes the @file{objects.fs} package. This material also
                   9731: has been published in M. Anton Ertl,
                   9732: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
                   9733: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
                   9734: 37--43.
                   9735: @c McKewan's and Zsoter's packages
1.26      crook    9736: 
1.78      anton    9737: This section assumes that you have read @ref{Structures}.
1.5       anton    9738: 
1.78      anton    9739: The techniques on which this model is based have been used to implement
                   9740: the parser generator, Gray, and have also been used in Gforth for
                   9741: implementing the various flavours of word lists (hashed or not,
                   9742: case-sensitive or not, special-purpose word lists for locals etc.).
1.5       anton    9743: 
                   9744: 
1.26      crook    9745: @menu
1.78      anton    9746: * Properties of the Objects model::  
                   9747: * Basic Objects Usage::         
                   9748: * The Objects base class::      
                   9749: * Creating objects::            
                   9750: * Object-Oriented Programming Style::  
                   9751: * Class Binding::               
                   9752: * Method conveniences::         
                   9753: * Classes and Scoping::         
                   9754: * Dividing classes::            
                   9755: * Object Interfaces::           
                   9756: * Objects Implementation::      
                   9757: * Objects Glossary::            
1.26      crook    9758: @end menu
1.5       anton    9759: 
1.78      anton    9760: Marcel Hendrix provided helpful comments on this section.
1.5       anton    9761: 
1.78      anton    9762: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   9763: @subsubsection Properties of the @file{objects.fs} model
                   9764: @cindex @file{objects.fs} properties
1.5       anton    9765: 
1.78      anton    9766: @itemize @bullet
                   9767: @item
                   9768: It is straightforward to pass objects on the stack. Passing
                   9769: selectors on the stack is a little less convenient, but possible.
1.44      crook    9770: 
1.78      anton    9771: @item
                   9772: Objects are just data structures in memory, and are referenced by their
                   9773: address. You can create words for objects with normal defining words
                   9774: like @code{constant}. Likewise, there is no difference between instance
                   9775: variables that contain objects and those that contain other data.
1.5       anton    9776: 
1.78      anton    9777: @item
                   9778: Late binding is efficient and easy to use.
1.44      crook    9779: 
1.78      anton    9780: @item
                   9781: It avoids parsing, and thus avoids problems with state-smartness
                   9782: and reduced extensibility; for convenience there are a few parsing
                   9783: words, but they have non-parsing counterparts. There are also a few
                   9784: defining words that parse. This is hard to avoid, because all standard
                   9785: defining words parse (except @code{:noname}); however, such
                   9786: words are not as bad as many other parsing words, because they are not
                   9787: state-smart.
1.5       anton    9788: 
1.78      anton    9789: @item
                   9790: It does not try to incorporate everything. It does a few things and does
                   9791: them well (IMO). In particular, this model was not designed to support
                   9792: information hiding (although it has features that may help); you can use
                   9793: a separate package for achieving this.
1.5       anton    9794: 
1.78      anton    9795: @item
                   9796: It is layered; you don't have to learn and use all features to use this
                   9797: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   9798: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
                   9799: are optional and independent of each other.
1.5       anton    9800: 
1.78      anton    9801: @item
                   9802: An implementation in ANS Forth is available.
1.5       anton    9803: 
1.78      anton    9804: @end itemize
1.5       anton    9805: 
1.44      crook    9806: 
1.78      anton    9807: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   9808: @subsubsection Basic @file{objects.fs} Usage
                   9809: @cindex basic objects usage
                   9810: @cindex objects, basic usage
1.5       anton    9811: 
1.78      anton    9812: You can define a class for graphical objects like this:
1.44      crook    9813: 
1.78      anton    9814: @cindex @code{class} usage
                   9815: @cindex @code{end-class} usage
                   9816: @cindex @code{selector} usage
1.5       anton    9817: @example
1.78      anton    9818: object class \ "object" is the parent class
                   9819:   selector draw ( x y graphical -- )
                   9820: end-class graphical
                   9821: @end example
                   9822: 
                   9823: This code defines a class @code{graphical} with an
                   9824: operation @code{draw}.  We can perform the operation
                   9825: @code{draw} on any @code{graphical} object, e.g.:
                   9826: 
                   9827: @example
                   9828: 100 100 t-rex draw
1.26      crook    9829: @end example
1.5       anton    9830: 
1.78      anton    9831: @noindent
                   9832: where @code{t-rex} is a word (say, a constant) that produces a
                   9833: graphical object.
                   9834: 
                   9835: @comment TODO add a 2nd operation eg perimeter.. and use for
                   9836: @comment a concrete example
1.5       anton    9837: 
1.78      anton    9838: @cindex abstract class
                   9839: How do we create a graphical object? With the present definitions,
                   9840: we cannot create a useful graphical object. The class
                   9841: @code{graphical} describes graphical objects in general, but not
                   9842: any concrete graphical object type (C++ users would call it an
                   9843: @emph{abstract class}); e.g., there is no method for the selector
                   9844: @code{draw} in the class @code{graphical}.
1.5       anton    9845: 
1.78      anton    9846: For concrete graphical objects, we define child classes of the
                   9847: class @code{graphical}, e.g.:
1.5       anton    9848: 
1.78      anton    9849: @cindex @code{overrides} usage
                   9850: @cindex @code{field} usage in class definition
1.26      crook    9851: @example
1.78      anton    9852: graphical class \ "graphical" is the parent class
                   9853:   cell% field circle-radius
1.5       anton    9854: 
1.78      anton    9855: :noname ( x y circle -- )
                   9856:   circle-radius @@ draw-circle ;
                   9857: overrides draw
1.5       anton    9858: 
1.78      anton    9859: :noname ( n-radius circle -- )
                   9860:   circle-radius ! ;
                   9861: overrides construct
1.5       anton    9862: 
1.78      anton    9863: end-class circle
                   9864: @end example
1.44      crook    9865: 
1.78      anton    9866: Here we define a class @code{circle} as a child of @code{graphical},
                   9867: with field @code{circle-radius} (which behaves just like a field
                   9868: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   9869: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   9870: defined in @code{object}, the parent class of @code{graphical}).
1.5       anton    9871: 
1.78      anton    9872: Now we can create a circle on the heap (i.e.,
                   9873: @code{allocate}d memory) with:
1.44      crook    9874: 
1.78      anton    9875: @cindex @code{heap-new} usage
1.5       anton    9876: @example
1.78      anton    9877: 50 circle heap-new constant my-circle
1.5       anton    9878: @end example
                   9879: 
1.78      anton    9880: @noindent
                   9881: @code{heap-new} invokes @code{construct}, thus
                   9882: initializing the field @code{circle-radius} with 50. We can draw
                   9883: this new circle at (100,100) with:
1.5       anton    9884: 
                   9885: @example
1.78      anton    9886: 100 100 my-circle draw
1.5       anton    9887: @end example
                   9888: 
1.78      anton    9889: @cindex selector invocation, restrictions
                   9890: @cindex class definition, restrictions
                   9891: Note: You can only invoke a selector if the object on the TOS
                   9892: (the receiving object) belongs to the class where the selector was
                   9893: defined or one of its descendents; e.g., you can invoke
                   9894: @code{draw} only for objects belonging to @code{graphical}
                   9895: or its descendents (e.g., @code{circle}).  Immediately before
                   9896: @code{end-class}, the search order has to be the same as
                   9897: immediately after @code{class}.
                   9898: 
                   9899: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   9900: @subsubsection The @file{object.fs} base class
                   9901: @cindex @code{object} class
                   9902: 
                   9903: When you define a class, you have to specify a parent class.  So how do
                   9904: you start defining classes? There is one class available from the start:
                   9905: @code{object}. It is ancestor for all classes and so is the
                   9906: only class that has no parent. It has two selectors: @code{construct}
                   9907: and @code{print}.
                   9908: 
                   9909: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   9910: @subsubsection Creating objects
                   9911: @cindex creating objects
                   9912: @cindex object creation
                   9913: @cindex object allocation options
                   9914: 
                   9915: @cindex @code{heap-new} discussion
                   9916: @cindex @code{dict-new} discussion
                   9917: @cindex @code{construct} discussion
                   9918: You can create and initialize an object of a class on the heap with
                   9919: @code{heap-new} ( ... class -- object ) and in the dictionary
                   9920: (allocation with @code{allot}) with @code{dict-new} (
                   9921: ... class -- object ). Both words invoke @code{construct}, which
                   9922: consumes the stack items indicated by "..." above.
                   9923: 
                   9924: @cindex @code{init-object} discussion
                   9925: @cindex @code{class-inst-size} discussion
                   9926: If you want to allocate memory for an object yourself, you can get its
                   9927: alignment and size with @code{class-inst-size 2@@} ( class --
                   9928: align size ). Once you have memory for an object, you can initialize
                   9929: it with @code{init-object} ( ... class object -- );
                   9930: @code{construct} does only a part of the necessary work.
                   9931: 
                   9932: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   9933: @subsubsection Object-Oriented Programming Style
                   9934: @cindex object-oriented programming style
                   9935: @cindex programming style, object-oriented
1.5       anton    9936: 
1.78      anton    9937: This section is not exhaustive.
1.5       anton    9938: 
1.78      anton    9939: @cindex stack effects of selectors
                   9940: @cindex selectors and stack effects
                   9941: In general, it is a good idea to ensure that all methods for the
                   9942: same selector have the same stack effect: when you invoke a selector,
                   9943: you often have no idea which method will be invoked, so, unless all
                   9944: methods have the same stack effect, you will not know the stack effect
                   9945: of the selector invocation.
1.5       anton    9946: 
1.78      anton    9947: One exception to this rule is methods for the selector
                   9948: @code{construct}. We know which method is invoked, because we
                   9949: specify the class to be constructed at the same place. Actually, I
                   9950: defined @code{construct} as a selector only to give the users a
                   9951: convenient way to specify initialization. The way it is used, a
                   9952: mechanism different from selector invocation would be more natural
                   9953: (but probably would take more code and more space to explain).
1.5       anton    9954: 
1.78      anton    9955: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   9956: @subsubsection Class Binding
                   9957: @cindex class binding
                   9958: @cindex early binding
1.5       anton    9959: 
1.78      anton    9960: @cindex late binding
                   9961: Normal selector invocations determine the method at run-time depending
                   9962: on the class of the receiving object. This run-time selection is called
                   9963: @i{late binding}.
1.5       anton    9964: 
1.78      anton    9965: Sometimes it's preferable to invoke a different method. For example,
                   9966: you might want to use the simple method for @code{print}ing
                   9967: @code{object}s instead of the possibly long-winded @code{print} method
                   9968: of the receiver class. You can achieve this by replacing the invocation
                   9969: of @code{print} with:
1.5       anton    9970: 
1.78      anton    9971: @cindex @code{[bind]} usage
1.5       anton    9972: @example
1.78      anton    9973: [bind] object print
1.5       anton    9974: @end example
                   9975: 
1.78      anton    9976: @noindent
                   9977: in compiled code or:
                   9978: 
                   9979: @cindex @code{bind} usage
1.5       anton    9980: @example
1.78      anton    9981: bind object print
1.5       anton    9982: @end example
                   9983: 
1.78      anton    9984: @cindex class binding, alternative to
                   9985: @noindent
                   9986: in interpreted code. Alternatively, you can define the method with a
                   9987: name (e.g., @code{print-object}), and then invoke it through the
                   9988: name. Class binding is just a (often more convenient) way to achieve
                   9989: the same effect; it avoids name clutter and allows you to invoke
                   9990: methods directly without naming them first.
1.5       anton    9991: 
1.78      anton    9992: @cindex superclass binding
                   9993: @cindex parent class binding
                   9994: A frequent use of class binding is this: When we define a method
                   9995: for a selector, we often want the method to do what the selector does
                   9996: in the parent class, and a little more. There is a special word for
                   9997: this purpose: @code{[parent]}; @code{[parent]
                   9998: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   9999: selector}}, where @code{@emph{parent}} is the parent
                   10000: class of the current class. E.g., a method definition might look like:
1.44      crook    10001: 
1.78      anton    10002: @cindex @code{[parent]} usage
                   10003: @example
                   10004: :noname
                   10005:   dup [parent] foo \ do parent's foo on the receiving object
                   10006:   ... \ do some more
                   10007: ; overrides foo
                   10008: @end example
1.6       pazsan   10009: 
1.78      anton    10010: @cindex class binding as optimization
                   10011: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10012: March 1997), Andrew McKewan presents class binding as an optimization
                   10013: technique. I recommend not using it for this purpose unless you are in
                   10014: an emergency. Late binding is pretty fast with this model anyway, so the
                   10015: benefit of using class binding is small; the cost of using class binding
                   10016: where it is not appropriate is reduced maintainability.
1.44      crook    10017: 
1.78      anton    10018: While we are at programming style questions: You should bind
                   10019: selectors only to ancestor classes of the receiving object. E.g., say,
                   10020: you know that the receiving object is of class @code{foo} or its
                   10021: descendents; then you should bind only to @code{foo} and its
                   10022: ancestors.
1.12      anton    10023: 
1.78      anton    10024: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10025: @subsubsection Method conveniences
                   10026: @cindex method conveniences
1.44      crook    10027: 
1.78      anton    10028: In a method you usually access the receiving object pretty often.  If
                   10029: you define the method as a plain colon definition (e.g., with
                   10030: @code{:noname}), you may have to do a lot of stack
                   10031: gymnastics. To avoid this, you can define the method with @code{m:
                   10032: ... ;m}. E.g., you could define the method for
                   10033: @code{draw}ing a @code{circle} with
1.6       pazsan   10034: 
1.78      anton    10035: @cindex @code{this} usage
                   10036: @cindex @code{m:} usage
                   10037: @cindex @code{;m} usage
                   10038: @example
                   10039: m: ( x y circle -- )
                   10040:   ( x y ) this circle-radius @@ draw-circle ;m
                   10041: @end example
1.6       pazsan   10042: 
1.78      anton    10043: @cindex @code{exit} in @code{m: ... ;m}
                   10044: @cindex @code{exitm} discussion
                   10045: @cindex @code{catch} in @code{m: ... ;m}
                   10046: When this method is executed, the receiver object is removed from the
                   10047: stack; you can access it with @code{this} (admittedly, in this
                   10048: example the use of @code{m: ... ;m} offers no advantage). Note
                   10049: that I specify the stack effect for the whole method (i.e. including
                   10050: the receiver object), not just for the code between @code{m:}
                   10051: and @code{;m}. You cannot use @code{exit} in
                   10052: @code{m:...;m}; instead, use
                   10053: @code{exitm}.@footnote{Moreover, for any word that calls
                   10054: @code{catch} and was defined before loading
                   10055: @code{objects.fs}, you have to redefine it like I redefined
                   10056: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12      anton    10057: 
1.78      anton    10058: @cindex @code{inst-var} usage
                   10059: You will frequently use sequences of the form @code{this
                   10060: @emph{field}} (in the example above: @code{this
                   10061: circle-radius}). If you use the field only in this way, you can
                   10062: define it with @code{inst-var} and eliminate the
                   10063: @code{this} before the field name. E.g., the @code{circle}
                   10064: class above could also be defined with:
1.6       pazsan   10065: 
1.78      anton    10066: @example
                   10067: graphical class
                   10068:   cell% inst-var radius
1.6       pazsan   10069: 
1.78      anton    10070: m: ( x y circle -- )
                   10071:   radius @@ draw-circle ;m
                   10072: overrides draw
1.6       pazsan   10073: 
1.78      anton    10074: m: ( n-radius circle -- )
                   10075:   radius ! ;m
                   10076: overrides construct
1.6       pazsan   10077: 
1.78      anton    10078: end-class circle
                   10079: @end example
1.6       pazsan   10080: 
1.78      anton    10081: @code{radius} can only be used in @code{circle} and its
                   10082: descendent classes and inside @code{m:...;m}.
1.6       pazsan   10083: 
1.78      anton    10084: @cindex @code{inst-value} usage
                   10085: You can also define fields with @code{inst-value}, which is
                   10086: to @code{inst-var} what @code{value} is to
                   10087: @code{variable}.  You can change the value of such a field with
                   10088: @code{[to-inst]}.  E.g., we could also define the class
                   10089: @code{circle} like this:
1.44      crook    10090: 
1.78      anton    10091: @example
                   10092: graphical class
                   10093:   inst-value radius
1.6       pazsan   10094: 
1.78      anton    10095: m: ( x y circle -- )
                   10096:   radius draw-circle ;m
                   10097: overrides draw
1.44      crook    10098: 
1.78      anton    10099: m: ( n-radius circle -- )
                   10100:   [to-inst] radius ;m
                   10101: overrides construct
1.6       pazsan   10102: 
1.78      anton    10103: end-class circle
                   10104: @end example
1.6       pazsan   10105: 
1.78      anton    10106: @c !! :m is easy to confuse with m:.  Another name would be better.
1.6       pazsan   10107: 
1.78      anton    10108: @c Finally, you can define named methods with @code{:m}.  One use of this
                   10109: @c feature is the definition of words that occur only in one class and are
                   10110: @c not intended to be overridden, but which still need method context
                   10111: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   10112: @c would be bound frequently, if defined anonymously.
1.6       pazsan   10113: 
                   10114: 
1.78      anton    10115: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
                   10116: @subsubsection Classes and Scoping
                   10117: @cindex classes and scoping
                   10118: @cindex scoping and classes
1.6       pazsan   10119: 
1.78      anton    10120: Inheritance is frequent, unlike structure extension. This exacerbates
                   10121: the problem with the field name convention (@pxref{Structure Naming
                   10122: Convention}): One always has to remember in which class the field was
                   10123: originally defined; changing a part of the class structure would require
                   10124: changes for renaming in otherwise unaffected code.
1.6       pazsan   10125: 
1.78      anton    10126: @cindex @code{inst-var} visibility
                   10127: @cindex @code{inst-value} visibility
                   10128: To solve this problem, I added a scoping mechanism (which was not in my
                   10129: original charter): A field defined with @code{inst-var} (or
                   10130: @code{inst-value}) is visible only in the class where it is defined and in
                   10131: the descendent classes of this class.  Using such fields only makes
                   10132: sense in @code{m:}-defined methods in these classes anyway.
1.6       pazsan   10133: 
1.78      anton    10134: This scoping mechanism allows us to use the unadorned field name,
                   10135: because name clashes with unrelated words become much less likely.
1.6       pazsan   10136: 
1.78      anton    10137: @cindex @code{protected} discussion
                   10138: @cindex @code{private} discussion
                   10139: Once we have this mechanism, we can also use it for controlling the
                   10140: visibility of other words: All words defined after
                   10141: @code{protected} are visible only in the current class and its
                   10142: descendents. @code{public} restores the compilation
                   10143: (i.e. @code{current}) word list that was in effect before. If you
                   10144: have several @code{protected}s without an intervening
                   10145: @code{public} or @code{set-current}, @code{public}
                   10146: will restore the compilation word list in effect before the first of
                   10147: these @code{protected}s.
1.6       pazsan   10148: 
1.78      anton    10149: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   10150: @subsubsection Dividing classes
                   10151: @cindex Dividing classes
                   10152: @cindex @code{methods}...@code{end-methods}
1.6       pazsan   10153: 
1.78      anton    10154: You may want to do the definition of methods separate from the
                   10155: definition of the class, its selectors, fields, and instance variables,
                   10156: i.e., separate the implementation from the definition.  You can do this
                   10157: in the following way:
1.6       pazsan   10158: 
1.78      anton    10159: @example
                   10160: graphical class
                   10161:   inst-value radius
                   10162: end-class circle
1.6       pazsan   10163: 
1.78      anton    10164: ... \ do some other stuff
1.6       pazsan   10165: 
1.78      anton    10166: circle methods \ now we are ready
1.44      crook    10167: 
1.78      anton    10168: m: ( x y circle -- )
                   10169:   radius draw-circle ;m
                   10170: overrides draw
1.6       pazsan   10171: 
1.78      anton    10172: m: ( n-radius circle -- )
                   10173:   [to-inst] radius ;m
                   10174: overrides construct
1.44      crook    10175: 
1.78      anton    10176: end-methods
                   10177: @end example
1.7       pazsan   10178: 
1.78      anton    10179: You can use several @code{methods}...@code{end-methods} sections.  The
                   10180: only things you can do to the class in these sections are: defining
                   10181: methods, and overriding the class's selectors.  You must not define new
                   10182: selectors or fields.
1.7       pazsan   10183: 
1.78      anton    10184: Note that you often have to override a selector before using it.  In
                   10185: particular, you usually have to override @code{construct} with a new
                   10186: method before you can invoke @code{heap-new} and friends.  E.g., you
                   10187: must not create a circle before the @code{overrides construct} sequence
                   10188: in the example above.
1.7       pazsan   10189: 
1.78      anton    10190: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
                   10191: @subsubsection Object Interfaces
                   10192: @cindex object interfaces
                   10193: @cindex interfaces for objects
1.7       pazsan   10194: 
1.78      anton    10195: In this model you can only call selectors defined in the class of the
                   10196: receiving objects or in one of its ancestors. If you call a selector
                   10197: with a receiving object that is not in one of these classes, the
                   10198: result is undefined; if you are lucky, the program crashes
                   10199: immediately.
1.7       pazsan   10200: 
1.78      anton    10201: @cindex selectors common to hardly-related classes
                   10202: Now consider the case when you want to have a selector (or several)
                   10203: available in two classes: You would have to add the selector to a
                   10204: common ancestor class, in the worst case to @code{object}. You
                   10205: may not want to do this, e.g., because someone else is responsible for
                   10206: this ancestor class.
1.7       pazsan   10207: 
1.78      anton    10208: The solution for this problem is interfaces. An interface is a
                   10209: collection of selectors. If a class implements an interface, the
                   10210: selectors become available to the class and its descendents. A class
                   10211: can implement an unlimited number of interfaces. For the problem
                   10212: discussed above, we would define an interface for the selector(s), and
                   10213: both classes would implement the interface.
1.7       pazsan   10214: 
1.78      anton    10215: As an example, consider an interface @code{storage} for
                   10216: writing objects to disk and getting them back, and a class
                   10217: @code{foo} that implements it. The code would look like this:
1.7       pazsan   10218: 
1.78      anton    10219: @cindex @code{interface} usage
                   10220: @cindex @code{end-interface} usage
                   10221: @cindex @code{implementation} usage
                   10222: @example
                   10223: interface
                   10224:   selector write ( file object -- )
                   10225:   selector read1 ( file object -- )
                   10226: end-interface storage
1.13      pazsan   10227: 
1.78      anton    10228: bar class
                   10229:   storage implementation
1.13      pazsan   10230: 
1.78      anton    10231: ... overrides write
                   10232: ... overrides read1
                   10233: ...
                   10234: end-class foo
                   10235: @end example
1.13      pazsan   10236: 
1.78      anton    10237: @noindent
                   10238: (I would add a word @code{read} @i{( file -- object )} that uses
                   10239: @code{read1} internally, but that's beyond the point illustrated
                   10240: here.)
1.13      pazsan   10241: 
1.78      anton    10242: Note that you cannot use @code{protected} in an interface; and
                   10243: of course you cannot define fields.
1.13      pazsan   10244: 
1.78      anton    10245: In the Neon model, all selectors are available for all classes;
                   10246: therefore it does not need interfaces. The price you pay in this model
                   10247: is slower late binding, and therefore, added complexity to avoid late
                   10248: binding.
1.13      pazsan   10249: 
1.78      anton    10250: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   10251: @subsubsection @file{objects.fs} Implementation
                   10252: @cindex @file{objects.fs} implementation
1.13      pazsan   10253: 
1.78      anton    10254: @cindex @code{object-map} discussion
                   10255: An object is a piece of memory, like one of the data structures
                   10256: described with @code{struct...end-struct}. It has a field
                   10257: @code{object-map} that points to the method map for the object's
                   10258: class.
1.13      pazsan   10259: 
1.78      anton    10260: @cindex method map
                   10261: @cindex virtual function table
                   10262: The @emph{method map}@footnote{This is Self terminology; in C++
                   10263: terminology: virtual function table.} is an array that contains the
                   10264: execution tokens (@i{xt}s) of the methods for the object's class. Each
                   10265: selector contains an offset into a method map.
1.13      pazsan   10266: 
1.78      anton    10267: @cindex @code{selector} implementation, class
                   10268: @code{selector} is a defining word that uses
                   10269: @code{CREATE} and @code{DOES>}. The body of the
                   10270: selector contains the offset; the @code{DOES>} action for a
                   10271: class selector is, basically:
1.8       pazsan   10272: 
                   10273: @example
1.78      anton    10274: ( object addr ) @@ over object-map @@ + @@ execute
1.13      pazsan   10275: @end example
                   10276: 
1.78      anton    10277: Since @code{object-map} is the first field of the object, it
                   10278: does not generate any code. As you can see, calling a selector has a
                   10279: small, constant cost.
1.26      crook    10280: 
1.78      anton    10281: @cindex @code{current-interface} discussion
                   10282: @cindex class implementation and representation
                   10283: A class is basically a @code{struct} combined with a method
                   10284: map. During the class definition the alignment and size of the class
                   10285: are passed on the stack, just as with @code{struct}s, so
                   10286: @code{field} can also be used for defining class
                   10287: fields. However, passing more items on the stack would be
                   10288: inconvenient, so @code{class} builds a data structure in memory,
                   10289: which is accessed through the variable
                   10290: @code{current-interface}. After its definition is complete, the
                   10291: class is represented on the stack by a pointer (e.g., as parameter for
                   10292: a child class definition).
1.26      crook    10293: 
1.78      anton    10294: A new class starts off with the alignment and size of its parent,
                   10295: and a copy of the parent's method map. Defining new fields extends the
                   10296: size and alignment; likewise, defining new selectors extends the
                   10297: method map. @code{overrides} just stores a new @i{xt} in the method
                   10298: map at the offset given by the selector.
1.13      pazsan   10299: 
1.78      anton    10300: @cindex class binding, implementation
                   10301: Class binding just gets the @i{xt} at the offset given by the selector
                   10302: from the class's method map and @code{compile,}s (in the case of
                   10303: @code{[bind]}) it.
1.13      pazsan   10304: 
1.78      anton    10305: @cindex @code{this} implementation
                   10306: @cindex @code{catch} and @code{this}
                   10307: @cindex @code{this} and @code{catch}
                   10308: I implemented @code{this} as a @code{value}. At the
                   10309: start of an @code{m:...;m} method the old @code{this} is
                   10310: stored to the return stack and restored at the end; and the object on
                   10311: the TOS is stored @code{TO this}. This technique has one
                   10312: disadvantage: If the user does not leave the method via
                   10313: @code{;m}, but via @code{throw} or @code{exit},
                   10314: @code{this} is not restored (and @code{exit} may
                   10315: crash). To deal with the @code{throw} problem, I have redefined
                   10316: @code{catch} to save and restore @code{this}; the same
                   10317: should be done with any word that can catch an exception. As for
                   10318: @code{exit}, I simply forbid it (as a replacement, there is
                   10319: @code{exitm}).
1.13      pazsan   10320: 
1.78      anton    10321: @cindex @code{inst-var} implementation
                   10322: @code{inst-var} is just the same as @code{field}, with
                   10323: a different @code{DOES>} action:
1.13      pazsan   10324: @example
1.78      anton    10325: @@ this +
1.8       pazsan   10326: @end example
1.78      anton    10327: Similar for @code{inst-value}.
1.8       pazsan   10328: 
1.78      anton    10329: @cindex class scoping implementation
                   10330: Each class also has a word list that contains the words defined with
                   10331: @code{inst-var} and @code{inst-value}, and its protected
                   10332: words. It also has a pointer to its parent. @code{class} pushes
                   10333: the word lists of the class and all its ancestors onto the search order stack,
                   10334: and @code{end-class} drops them.
1.20      pazsan   10335: 
1.78      anton    10336: @cindex interface implementation
                   10337: An interface is like a class without fields, parent and protected
                   10338: words; i.e., it just has a method map. If a class implements an
                   10339: interface, its method map contains a pointer to the method map of the
                   10340: interface. The positive offsets in the map are reserved for class
                   10341: methods, therefore interface map pointers have negative
                   10342: offsets. Interfaces have offsets that are unique throughout the
                   10343: system, unlike class selectors, whose offsets are only unique for the
                   10344: classes where the selector is available (invokable).
1.20      pazsan   10345: 
1.78      anton    10346: This structure means that interface selectors have to perform one
                   10347: indirection more than class selectors to find their method. Their body
                   10348: contains the interface map pointer offset in the class method map, and
                   10349: the method offset in the interface method map. The
                   10350: @code{does>} action for an interface selector is, basically:
1.20      pazsan   10351: 
                   10352: @example
1.78      anton    10353: ( object selector-body )
                   10354: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   10355: swap object-map @@ + @@ ( object selector-body map )
                   10356: swap selector-offset @@ + @@ execute
1.20      pazsan   10357: @end example
                   10358: 
1.78      anton    10359: where @code{object-map} and @code{selector-offset} are
                   10360: first fields and generate no code.
1.20      pazsan   10361: 
1.78      anton    10362: As a concrete example, consider the following code:
1.20      pazsan   10363: 
                   10364: @example
1.78      anton    10365: interface
                   10366:   selector if1sel1
                   10367:   selector if1sel2
                   10368: end-interface if1
1.20      pazsan   10369: 
1.78      anton    10370: object class
                   10371:   if1 implementation
                   10372:   selector cl1sel1
                   10373:   cell% inst-var cl1iv1
1.20      pazsan   10374: 
1.78      anton    10375: ' m1 overrides construct
                   10376: ' m2 overrides if1sel1
                   10377: ' m3 overrides if1sel2
                   10378: ' m4 overrides cl1sel2
                   10379: end-class cl1
1.20      pazsan   10380: 
1.78      anton    10381: create obj1 object dict-new drop
                   10382: create obj2 cl1    dict-new drop
                   10383: @end example
1.20      pazsan   10384: 
1.78      anton    10385: The data structure created by this code (including the data structure
                   10386: for @code{object}) is shown in the
                   10387: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
                   10388: @comment TODO add this diagram..
1.20      pazsan   10389: 
1.78      anton    10390: @node Objects Glossary,  , Objects Implementation, Objects
                   10391: @subsubsection @file{objects.fs} Glossary
                   10392: @cindex @file{objects.fs} Glossary
1.20      pazsan   10393: 
                   10394: 
1.78      anton    10395: doc---objects-bind
                   10396: doc---objects-<bind>
                   10397: doc---objects-bind'
                   10398: doc---objects-[bind]
                   10399: doc---objects-class
                   10400: doc---objects-class->map
                   10401: doc---objects-class-inst-size
                   10402: doc---objects-class-override!
1.79      anton    10403: doc---objects-class-previous
                   10404: doc---objects-class>order
1.78      anton    10405: doc---objects-construct
                   10406: doc---objects-current'
                   10407: doc---objects-[current]
                   10408: doc---objects-current-interface
                   10409: doc---objects-dict-new
                   10410: doc---objects-end-class
                   10411: doc---objects-end-class-noname
                   10412: doc---objects-end-interface
                   10413: doc---objects-end-interface-noname
                   10414: doc---objects-end-methods
                   10415: doc---objects-exitm
                   10416: doc---objects-heap-new
                   10417: doc---objects-implementation
                   10418: doc---objects-init-object
                   10419: doc---objects-inst-value
                   10420: doc---objects-inst-var
                   10421: doc---objects-interface
                   10422: doc---objects-m:
                   10423: doc---objects-:m
                   10424: doc---objects-;m
                   10425: doc---objects-method
                   10426: doc---objects-methods
                   10427: doc---objects-object
                   10428: doc---objects-overrides
                   10429: doc---objects-[parent]
                   10430: doc---objects-print
                   10431: doc---objects-protected
                   10432: doc---objects-public
                   10433: doc---objects-selector
                   10434: doc---objects-this
                   10435: doc---objects-<to-inst>
                   10436: doc---objects-[to-inst]
                   10437: doc---objects-to-this
                   10438: doc---objects-xt-new
1.20      pazsan   10439: 
                   10440: 
1.78      anton    10441: @c -------------------------------------------------------------
                   10442: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   10443: @subsection The @file{oof.fs} model
                   10444: @cindex oof
                   10445: @cindex object-oriented programming
1.20      pazsan   10446: 
1.78      anton    10447: @cindex @file{objects.fs}
                   10448: @cindex @file{oof.fs}
1.20      pazsan   10449: 
1.78      anton    10450: This section describes the @file{oof.fs} package.
1.20      pazsan   10451: 
1.78      anton    10452: The package described in this section has been used in bigFORTH since 1991, and
                   10453: used for two large applications: a chromatographic system used to
                   10454: create new medicaments, and a graphic user interface library (MINOS).
1.20      pazsan   10455: 
1.78      anton    10456: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   10457: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   10458: 10(2), 1994.
1.20      pazsan   10459: 
1.78      anton    10460: @menu
                   10461: * Properties of the OOF model::  
                   10462: * Basic OOF Usage::             
                   10463: * The OOF base class::          
                   10464: * Class Declaration::           
                   10465: * Class Implementation::        
                   10466: @end menu
1.20      pazsan   10467: 
1.78      anton    10468: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   10469: @subsubsection Properties of the @file{oof.fs} model
                   10470: @cindex @file{oof.fs} properties
1.20      pazsan   10471: 
1.78      anton    10472: @itemize @bullet
                   10473: @item
                   10474: This model combines object oriented programming with information
                   10475: hiding. It helps you writing large application, where scoping is
                   10476: necessary, because it provides class-oriented scoping.
1.20      pazsan   10477: 
1.78      anton    10478: @item
                   10479: Named objects, object pointers, and object arrays can be created,
                   10480: selector invocation uses the ``object selector'' syntax. Selector invocation
                   10481: to objects and/or selectors on the stack is a bit less convenient, but
                   10482: possible.
1.44      crook    10483: 
1.78      anton    10484: @item
                   10485: Selector invocation and instance variable usage of the active object is
                   10486: straightforward, since both make use of the active object.
1.44      crook    10487: 
1.78      anton    10488: @item
                   10489: Late binding is efficient and easy to use.
1.20      pazsan   10490: 
1.78      anton    10491: @item
                   10492: State-smart objects parse selectors. However, extensibility is provided
                   10493: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20      pazsan   10494: 
1.78      anton    10495: @item
                   10496: An implementation in ANS Forth is available.
1.20      pazsan   10497: 
1.78      anton    10498: @end itemize
1.23      crook    10499: 
                   10500: 
1.78      anton    10501: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   10502: @subsubsection Basic @file{oof.fs} Usage
                   10503: @cindex @file{oof.fs} usage
1.23      crook    10504: 
1.78      anton    10505: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23      crook    10506: 
1.78      anton    10507: You can define a class for graphical objects like this:
1.23      crook    10508: 
1.78      anton    10509: @cindex @code{class} usage
                   10510: @cindex @code{class;} usage
                   10511: @cindex @code{method} usage
                   10512: @example
                   10513: object class graphical \ "object" is the parent class
                   10514:   method draw ( x y graphical -- )
                   10515: class;
                   10516: @end example
1.23      crook    10517: 
1.78      anton    10518: This code defines a class @code{graphical} with an
                   10519: operation @code{draw}.  We can perform the operation
                   10520: @code{draw} on any @code{graphical} object, e.g.:
1.23      crook    10521: 
1.78      anton    10522: @example
                   10523: 100 100 t-rex draw
                   10524: @end example
1.23      crook    10525: 
1.78      anton    10526: @noindent
                   10527: where @code{t-rex} is an object or object pointer, created with e.g.
                   10528: @code{graphical : t-rex}.
1.23      crook    10529: 
1.78      anton    10530: @cindex abstract class
                   10531: How do we create a graphical object? With the present definitions,
                   10532: we cannot create a useful graphical object. The class
                   10533: @code{graphical} describes graphical objects in general, but not
                   10534: any concrete graphical object type (C++ users would call it an
                   10535: @emph{abstract class}); e.g., there is no method for the selector
                   10536: @code{draw} in the class @code{graphical}.
1.23      crook    10537: 
1.78      anton    10538: For concrete graphical objects, we define child classes of the
                   10539: class @code{graphical}, e.g.:
1.23      crook    10540: 
1.78      anton    10541: @example
                   10542: graphical class circle \ "graphical" is the parent class
                   10543:   cell var circle-radius
                   10544: how:
                   10545:   : draw ( x y -- )
                   10546:     circle-radius @@ draw-circle ;
1.23      crook    10547: 
1.78      anton    10548:   : init ( n-radius -- (
                   10549:     circle-radius ! ;
                   10550: class;
                   10551: @end example
1.1       anton    10552: 
1.78      anton    10553: Here we define a class @code{circle} as a child of @code{graphical},
                   10554: with a field @code{circle-radius}; it defines new methods for the
                   10555: selectors @code{draw} and @code{init} (@code{init} is defined in
                   10556: @code{object}, the parent class of @code{graphical}).
1.1       anton    10557: 
1.78      anton    10558: Now we can create a circle in the dictionary with:
1.1       anton    10559: 
1.78      anton    10560: @example
                   10561: 50 circle : my-circle
                   10562: @end example
1.21      crook    10563: 
1.78      anton    10564: @noindent
                   10565: @code{:} invokes @code{init}, thus initializing the field
                   10566: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   10567: with:
1.1       anton    10568: 
1.78      anton    10569: @example
                   10570: 100 100 my-circle draw
                   10571: @end example
1.1       anton    10572: 
1.78      anton    10573: @cindex selector invocation, restrictions
                   10574: @cindex class definition, restrictions
                   10575: Note: You can only invoke a selector if the receiving object belongs to
                   10576: the class where the selector was defined or one of its descendents;
                   10577: e.g., you can invoke @code{draw} only for objects belonging to
                   10578: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   10579: mechanism will check if you try to invoke a selector that is not
                   10580: defined in this class hierarchy, so you'll get an error at compilation
                   10581: time.
1.1       anton    10582: 
                   10583: 
1.78      anton    10584: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   10585: @subsubsection The @file{oof.fs} base class
                   10586: @cindex @file{oof.fs} base class
1.1       anton    10587: 
1.78      anton    10588: When you define a class, you have to specify a parent class.  So how do
                   10589: you start defining classes? There is one class available from the start:
                   10590: @code{object}. You have to use it as ancestor for all classes. It is the
                   10591: only class that has no parent. Classes are also objects, except that
                   10592: they don't have instance variables; class manipulation such as
                   10593: inheritance or changing definitions of a class is handled through
                   10594: selectors of the class @code{object}.
1.1       anton    10595: 
1.78      anton    10596: @code{object} provides a number of selectors:
1.1       anton    10597: 
1.78      anton    10598: @itemize @bullet
                   10599: @item
                   10600: @code{class} for subclassing, @code{definitions} to add definitions
                   10601: later on, and @code{class?} to get type informations (is the class a
                   10602: subclass of the class passed on the stack?).
1.1       anton    10603: 
1.78      anton    10604: doc---object-class
                   10605: doc---object-definitions
                   10606: doc---object-class?
1.1       anton    10607: 
                   10608: 
1.26      crook    10609: @item
1.78      anton    10610: @code{init} and @code{dispose} as constructor and destructor of the
                   10611: object. @code{init} is invocated after the object's memory is allocated,
                   10612: while @code{dispose} also handles deallocation. Thus if you redefine
                   10613: @code{dispose}, you have to call the parent's dispose with @code{super
                   10614: dispose}, too.
                   10615: 
                   10616: doc---object-init
                   10617: doc---object-dispose
                   10618: 
1.1       anton    10619: 
1.26      crook    10620: @item
1.78      anton    10621: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   10622: @code{[]} to create named and unnamed objects and object arrays or
                   10623: object pointers.
                   10624: 
                   10625: doc---object-new
                   10626: doc---object-new[]
                   10627: doc---object-:
                   10628: doc---object-ptr
                   10629: doc---object-asptr
                   10630: doc---object-[]
                   10631: 
1.1       anton    10632: 
1.26      crook    10633: @item
1.78      anton    10634: @code{::} and @code{super} for explicit scoping. You should use explicit
                   10635: scoping only for super classes or classes with the same set of instance
                   10636: variables. Explicitly-scoped selectors use early binding.
1.21      crook    10637: 
1.78      anton    10638: doc---object-::
                   10639: doc---object-super
1.21      crook    10640: 
                   10641: 
1.26      crook    10642: @item
1.78      anton    10643: @code{self} to get the address of the object
1.21      crook    10644: 
1.78      anton    10645: doc---object-self
1.21      crook    10646: 
                   10647: 
1.78      anton    10648: @item
                   10649: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   10650: pointers and instance defers.
1.21      crook    10651: 
1.78      anton    10652: doc---object-bind
                   10653: doc---object-bound
                   10654: doc---object-link
                   10655: doc---object-is
1.21      crook    10656: 
                   10657: 
1.78      anton    10658: @item
                   10659: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   10660: form the stack, and @code{postpone} to generate selector invocation code.
1.21      crook    10661: 
1.78      anton    10662: doc---object-'
                   10663: doc---object-postpone
1.21      crook    10664: 
                   10665: 
1.78      anton    10666: @item
                   10667: @code{with} and @code{endwith} to select the active object from the
                   10668: stack, and enable its scope. Using @code{with} and @code{endwith}
                   10669: also allows you to create code using selector @code{postpone} without being
                   10670: trapped by the state-smart objects.
1.21      crook    10671: 
1.78      anton    10672: doc---object-with
                   10673: doc---object-endwith
1.21      crook    10674: 
                   10675: 
1.78      anton    10676: @end itemize
1.21      crook    10677: 
1.78      anton    10678: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   10679: @subsubsection Class Declaration
                   10680: @cindex class declaration
1.21      crook    10681: 
1.78      anton    10682: @itemize @bullet
                   10683: @item
                   10684: Instance variables
1.21      crook    10685: 
1.78      anton    10686: doc---oof-var
1.21      crook    10687: 
                   10688: 
1.78      anton    10689: @item
                   10690: Object pointers
1.21      crook    10691: 
1.78      anton    10692: doc---oof-ptr
                   10693: doc---oof-asptr
1.21      crook    10694: 
                   10695: 
1.78      anton    10696: @item
                   10697: Instance defers
1.21      crook    10698: 
1.78      anton    10699: doc---oof-defer
1.21      crook    10700: 
                   10701: 
1.78      anton    10702: @item
                   10703: Method selectors
1.21      crook    10704: 
1.78      anton    10705: doc---oof-early
                   10706: doc---oof-method
1.21      crook    10707: 
                   10708: 
1.78      anton    10709: @item
                   10710: Class-wide variables
1.21      crook    10711: 
1.78      anton    10712: doc---oof-static
1.21      crook    10713: 
                   10714: 
1.78      anton    10715: @item
                   10716: End declaration
1.1       anton    10717: 
1.78      anton    10718: doc---oof-how:
                   10719: doc---oof-class;
1.21      crook    10720: 
                   10721: 
1.78      anton    10722: @end itemize
1.21      crook    10723: 
1.78      anton    10724: @c -------------------------------------------------------------
                   10725: @node Class Implementation,  , Class Declaration, OOF
                   10726: @subsubsection Class Implementation
                   10727: @cindex class implementation
1.21      crook    10728: 
1.78      anton    10729: @c -------------------------------------------------------------
                   10730: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   10731: @subsection The @file{mini-oof.fs} model
                   10732: @cindex mini-oof
1.21      crook    10733: 
1.78      anton    10734: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79      anton    10735: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78      anton    10736: and reduces to the bare minimum of features. This is based on a posting
                   10737: of Bernd Paysan in comp.lang.forth.
1.21      crook    10738: 
1.78      anton    10739: @menu
                   10740: * Basic Mini-OOF Usage::        
                   10741: * Mini-OOF Example::            
                   10742: * Mini-OOF Implementation::     
                   10743: @end menu
1.21      crook    10744: 
1.78      anton    10745: @c -------------------------------------------------------------
                   10746: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
                   10747: @subsubsection Basic @file{mini-oof.fs} Usage
                   10748: @cindex mini-oof usage
1.21      crook    10749: 
1.78      anton    10750: There is a base class (@code{class}, which allocates one cell for the
                   10751: object pointer) plus seven other words: to define a method, a variable,
                   10752: a class; to end a class, to resolve binding, to allocate an object and
                   10753: to compile a class method.
                   10754: @comment TODO better description of the last one
1.26      crook    10755: 
1.21      crook    10756: 
1.78      anton    10757: doc-object
                   10758: doc-method
                   10759: doc-var
                   10760: doc-class
                   10761: doc-end-class
                   10762: doc-defines
                   10763: doc-new
                   10764: doc-::
1.21      crook    10765: 
                   10766: 
                   10767: 
1.78      anton    10768: @c -------------------------------------------------------------
                   10769: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   10770: @subsubsection Mini-OOF Example
                   10771: @cindex mini-oof example
1.1       anton    10772: 
1.78      anton    10773: A short example shows how to use this package. This example, in slightly
                   10774: extended form, is supplied as @file{moof-exm.fs}
                   10775: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20      pazsan   10776: 
1.26      crook    10777: @example
1.78      anton    10778: object class
                   10779:   method init
                   10780:   method draw
                   10781: end-class graphical
1.26      crook    10782: @end example
1.20      pazsan   10783: 
1.78      anton    10784: This code defines a class @code{graphical} with an
                   10785: operation @code{draw}.  We can perform the operation
                   10786: @code{draw} on any @code{graphical} object, e.g.:
1.20      pazsan   10787: 
1.26      crook    10788: @example
1.78      anton    10789: 100 100 t-rex draw
1.26      crook    10790: @end example
1.12      anton    10791: 
1.78      anton    10792: where @code{t-rex} is an object or object pointer, created with e.g.
                   10793: @code{graphical new Constant t-rex}.
1.12      anton    10794: 
1.78      anton    10795: For concrete graphical objects, we define child classes of the
                   10796: class @code{graphical}, e.g.:
1.12      anton    10797: 
1.26      crook    10798: @example
                   10799: graphical class
1.78      anton    10800:   cell var circle-radius
                   10801: end-class circle \ "graphical" is the parent class
1.12      anton    10802: 
1.78      anton    10803: :noname ( x y -- )
                   10804:   circle-radius @@ draw-circle ; circle defines draw
                   10805: :noname ( r -- )
                   10806:   circle-radius ! ; circle defines init
                   10807: @end example
1.12      anton    10808: 
1.78      anton    10809: There is no implicit init method, so we have to define one. The creation
                   10810: code of the object now has to call init explicitely.
1.21      crook    10811: 
1.78      anton    10812: @example
                   10813: circle new Constant my-circle
                   10814: 50 my-circle init
1.12      anton    10815: @end example
                   10816: 
1.78      anton    10817: It is also possible to add a function to create named objects with
                   10818: automatic call of @code{init}, given that all objects have @code{init}
                   10819: on the same place:
1.38      anton    10820: 
1.78      anton    10821: @example
                   10822: : new: ( .. o "name" -- )
                   10823:     new dup Constant init ;
                   10824: 80 circle new: large-circle
                   10825: @end example
1.12      anton    10826: 
1.78      anton    10827: We can draw this new circle at (100,100) with:
1.12      anton    10828: 
1.78      anton    10829: @example
                   10830: 100 100 my-circle draw
                   10831: @end example
1.12      anton    10832: 
1.78      anton    10833: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
                   10834: @subsubsection @file{mini-oof.fs} Implementation
1.12      anton    10835: 
1.78      anton    10836: Object-oriented systems with late binding typically use a
                   10837: ``vtable''-approach: the first variable in each object is a pointer to a
                   10838: table, which contains the methods as function pointers. The vtable
                   10839: may also contain other information.
1.12      anton    10840: 
1.79      anton    10841: So first, let's declare selectors:
1.37      anton    10842: 
                   10843: @example
1.79      anton    10844: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
1.78      anton    10845:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
                   10846: @end example
1.37      anton    10847: 
1.79      anton    10848: During selector declaration, the number of selectors and instance
                   10849: variables is on the stack (in address units). @code{method} creates one
                   10850: selector and increments the selector number. To execute a selector, it
1.78      anton    10851: takes the object, fetches the vtable pointer, adds the offset, and
1.79      anton    10852: executes the method @i{xt} stored there. Each selector takes the object
                   10853: it is invoked with as top of stack parameter; it passes the parameters
                   10854: (including the object) unchanged to the appropriate method which should
1.78      anton    10855: consume that object.
1.37      anton    10856: 
1.78      anton    10857: Now, we also have to declare instance variables
1.37      anton    10858: 
1.78      anton    10859: @example
1.79      anton    10860: : var ( m v size "name" -- m v' ) Create  over , +
1.78      anton    10861:   DOES> ( o -- addr ) @@ + ;
1.37      anton    10862: @end example
                   10863: 
1.78      anton    10864: As before, a word is created with the current offset. Instance
                   10865: variables can have different sizes (cells, floats, doubles, chars), so
                   10866: all we do is take the size and add it to the offset. If your machine
                   10867: has alignment restrictions, put the proper @code{aligned} or
                   10868: @code{faligned} before the variable, to adjust the variable
                   10869: offset. That's why it is on the top of stack.
1.37      anton    10870: 
1.78      anton    10871: We need a starting point (the base object) and some syntactic sugar:
1.37      anton    10872: 
1.78      anton    10873: @example
                   10874: Create object  1 cells , 2 cells ,
1.79      anton    10875: : class ( class -- class selectors vars ) dup 2@@ ;
1.78      anton    10876: @end example
1.12      anton    10877: 
1.78      anton    10878: For inheritance, the vtable of the parent object has to be
                   10879: copied when a new, derived class is declared. This gives all the
                   10880: methods of the parent class, which can be overridden, though.
1.12      anton    10881: 
1.78      anton    10882: @example
1.79      anton    10883: : end-class  ( class selectors vars "name" -- )
1.78      anton    10884:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   10885:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
                   10886: @end example
1.12      anton    10887: 
1.78      anton    10888: The first line creates the vtable, initialized with
                   10889: @code{noop}s. The second line is the inheritance mechanism, it
                   10890: copies the xts from the parent vtable.
1.12      anton    10891: 
1.78      anton    10892: We still have no way to define new methods, let's do that now:
1.12      anton    10893: 
1.26      crook    10894: @example
1.79      anton    10895: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78      anton    10896: @end example
1.12      anton    10897: 
1.78      anton    10898: To allocate a new object, we need a word, too:
1.12      anton    10899: 
1.78      anton    10900: @example
                   10901: : new ( class -- o )  here over @@ allot swap over ! ;
1.12      anton    10902: @end example
                   10903: 
1.78      anton    10904: Sometimes derived classes want to access the method of the
                   10905: parent object. There are two ways to achieve this with Mini-OOF:
                   10906: first, you could use named words, and second, you could look up the
                   10907: vtable of the parent object.
1.12      anton    10908: 
1.78      anton    10909: @example
                   10910: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
                   10911: @end example
1.12      anton    10912: 
                   10913: 
1.78      anton    10914: Nothing can be more confusing than a good example, so here is
                   10915: one. First let's declare a text object (called
                   10916: @code{button}), that stores text and position:
1.12      anton    10917: 
1.78      anton    10918: @example
                   10919: object class
                   10920:   cell var text
                   10921:   cell var len
                   10922:   cell var x
                   10923:   cell var y
                   10924:   method init
                   10925:   method draw
                   10926: end-class button
                   10927: @end example
1.12      anton    10928: 
1.78      anton    10929: @noindent
                   10930: Now, implement the two methods, @code{draw} and @code{init}:
1.21      crook    10931: 
1.26      crook    10932: @example
1.78      anton    10933: :noname ( o -- )
                   10934:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
                   10935:  button defines draw
                   10936: :noname ( addr u o -- )
                   10937:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
                   10938:  button defines init
1.26      crook    10939: @end example
1.12      anton    10940: 
1.78      anton    10941: @noindent
                   10942: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79      anton    10943: new data and no new selectors:
1.78      anton    10944: 
                   10945: @example
                   10946: button class
                   10947: end-class bold-button
1.12      anton    10948: 
1.78      anton    10949: : bold   27 emit ." [1m" ;
                   10950: : normal 27 emit ." [0m" ;
                   10951: @end example
1.1       anton    10952: 
1.78      anton    10953: @noindent
                   10954: The class @code{bold-button} has a different draw method to
                   10955: @code{button}, but the new method is defined in terms of the draw method
                   10956: for @code{button}:
1.20      pazsan   10957: 
1.78      anton    10958: @example
                   10959: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   10960: @end example
1.21      crook    10961: 
1.78      anton    10962: @noindent
1.79      anton    10963: Finally, create two objects and apply selectors:
1.21      crook    10964: 
1.26      crook    10965: @example
1.78      anton    10966: button new Constant foo
                   10967: s" thin foo" foo init
                   10968: page
                   10969: foo draw
                   10970: bold-button new Constant bar
                   10971: s" fat bar" bar init
                   10972: 1 bar y !
                   10973: bar draw
1.26      crook    10974: @end example
1.21      crook    10975: 
                   10976: 
1.78      anton    10977: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   10978: @subsection Comparison with other object models
                   10979: @cindex comparison of object models
                   10980: @cindex object models, comparison
                   10981: 
                   10982: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   10983: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   10984: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   10985: relation of the object models described here to two well-known and two
                   10986: closely-related (by the use of method maps) models.  Andras Zsoter
                   10987: helped us with this section.
                   10988: 
                   10989: @cindex Neon model
                   10990: The most popular model currently seems to be the Neon model (see
                   10991: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   10992: 1997) by Andrew McKewan) but this model has a number of limitations
                   10993: @footnote{A longer version of this critique can be
                   10994: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   10995: Dimensions, May 1997) by Anton Ertl.}:
                   10996: 
                   10997: @itemize @bullet
                   10998: @item
                   10999: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11000: to pass objects on the stack.
1.21      crook    11001: 
1.78      anton    11002: @item
                   11003: It requires that the selector parses the input stream (at
1.79      anton    11004: compile time); this leads to reduced extensibility and to bugs that are
1.78      anton    11005: hard to find.
1.21      crook    11006: 
1.78      anton    11007: @item
1.79      anton    11008: It allows using every selector on every object; this eliminates the
                   11009: need for interfaces, but makes it harder to create efficient
                   11010: implementations.
1.78      anton    11011: @end itemize
1.21      crook    11012: 
1.78      anton    11013: @cindex Pountain's object-oriented model
                   11014: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11015: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11016: object-oriented programming, because it hardly deals with late
                   11017: binding. Instead, it focuses on features like information hiding and
                   11018: overloading that are characteristic of modular languages like Ada (83).
1.26      crook    11019: 
1.78      anton    11020: @cindex Zsoter's object-oriented model
1.79      anton    11021: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
                   11022: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
                   11023: describes a model that makes heavy use of an active object (like
                   11024: @code{this} in @file{objects.fs}): The active object is not only used
                   11025: for accessing all fields, but also specifies the receiving object of
                   11026: every selector invocation; you have to change the active object
                   11027: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   11028: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   11029: the method entry point is unnecessary with Zsoter's model, because the
                   11030: receiving object is the active object already. On the other hand, the
                   11031: explicit change is absolutely necessary in that model, because otherwise
                   11032: no one could ever change the active object. An ANS Forth implementation
                   11033: of this model is available through
                   11034: @uref{http://www.forth.org/oopf.html}.
1.21      crook    11035: 
1.78      anton    11036: @cindex @file{oof.fs}, differences to other models
                   11037: The @file{oof.fs} model combines information hiding and overloading
                   11038: resolution (by keeping names in various word lists) with object-oriented
                   11039: programming. It sets the active object implicitly on method entry, but
                   11040: also allows explicit changing (with @code{>o...o>} or with
                   11041: @code{with...endwith}). It uses parsing and state-smart objects and
                   11042: classes for resolving overloading and for early binding: the object or
                   11043: class parses the selector and determines the method from this. If the
                   11044: selector is not parsed by an object or class, it performs a call to the
                   11045: selector for the active object (late binding), like Zsoter's model.
                   11046: Fields are always accessed through the active object. The big
                   11047: disadvantage of this model is the parsing and the state-smartness, which
                   11048: reduces extensibility and increases the opportunities for subtle bugs;
                   11049: essentially, you are only safe if you never tick or @code{postpone} an
                   11050: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21      crook    11051: 
1.78      anton    11052: @cindex @file{mini-oof.fs}, differences to other models
                   11053: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11054: version of the @file{objects.fs} model, but syntactically it is a
                   11055: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21      crook    11056: 
                   11057: 
1.78      anton    11058: @c -------------------------------------------------------------
                   11059: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
                   11060: @section Programming Tools
                   11061: @cindex programming tools
1.21      crook    11062: 
1.78      anton    11063: @c !! move this and assembler down below OO stuff.
1.21      crook    11064: 
1.78      anton    11065: @menu
                   11066: * Examining::                   
                   11067: * Forgetting words::            
                   11068: * Debugging::                   Simple and quick.
                   11069: * Assertions::                  Making your programs self-checking.
                   11070: * Singlestep Debugger::         Executing your program word by word.
                   11071: @end menu
1.21      crook    11072: 
1.78      anton    11073: @node Examining, Forgetting words, Programming Tools, Programming Tools
                   11074: @subsection Examining data and code
                   11075: @cindex examining data and code
                   11076: @cindex data examination
                   11077: @cindex code examination
1.44      crook    11078: 
1.78      anton    11079: The following words inspect the stack non-destructively:
1.21      crook    11080: 
1.78      anton    11081: doc-.s
                   11082: doc-f.s
1.44      crook    11083: 
1.78      anton    11084: There is a word @code{.r} but it does @i{not} display the return stack!
                   11085: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21      crook    11086: 
1.78      anton    11087: doc-depth
                   11088: doc-fdepth
                   11089: doc-clearstack
1.21      crook    11090: 
1.78      anton    11091: The following words inspect memory.
1.21      crook    11092: 
1.78      anton    11093: doc-?
                   11094: doc-dump
1.21      crook    11095: 
1.78      anton    11096: And finally, @code{see} allows to inspect code:
1.21      crook    11097: 
1.78      anton    11098: doc-see
                   11099: doc-xt-see
1.21      crook    11100: 
1.78      anton    11101: @node Forgetting words, Debugging, Examining, Programming Tools
                   11102: @subsection Forgetting words
                   11103: @cindex words, forgetting
                   11104: @cindex forgeting words
1.21      crook    11105: 
1.78      anton    11106: @c  anton: other, maybe better places for this subsection: Defining Words;
                   11107: @c  Dictionary allocation.  At least a reference should be there.
1.21      crook    11108: 
1.78      anton    11109: Forth allows you to forget words (and everything that was alloted in the
                   11110: dictonary after them) in a LIFO manner.
1.21      crook    11111: 
1.78      anton    11112: doc-marker
1.21      crook    11113: 
1.78      anton    11114: The most common use of this feature is during progam development: when
                   11115: you change a source file, forget all the words it defined and load it
                   11116: again (since you also forget everything defined after the source file
                   11117: was loaded, you have to reload that, too).  Note that effects like
                   11118: storing to variables and destroyed system words are not undone when you
                   11119: forget words.  With a system like Gforth, that is fast enough at
                   11120: starting up and compiling, I find it more convenient to exit and restart
                   11121: Gforth, as this gives me a clean slate.
1.21      crook    11122: 
1.78      anton    11123: Here's an example of using @code{marker} at the start of a source file
                   11124: that you are debugging; it ensures that you only ever have one copy of
                   11125: the file's definitions compiled at any time:
1.21      crook    11126: 
1.78      anton    11127: @example
                   11128: [IFDEF] my-code
                   11129:     my-code
                   11130: [ENDIF]
1.26      crook    11131: 
1.78      anton    11132: marker my-code
                   11133: init-included-files
1.21      crook    11134: 
1.78      anton    11135: \ .. definitions start here
                   11136: \ .
                   11137: \ .
                   11138: \ end
                   11139: @end example
1.21      crook    11140: 
1.26      crook    11141: 
1.78      anton    11142: @node Debugging, Assertions, Forgetting words, Programming Tools
                   11143: @subsection Debugging
                   11144: @cindex debugging
1.21      crook    11145: 
1.78      anton    11146: Languages with a slow edit/compile/link/test development loop tend to
                   11147: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21      crook    11148: 
1.78      anton    11149: A much better (faster) way in fast-compiling languages is to add
                   11150: printing code at well-selected places, let the program run, look at
                   11151: the output, see where things went wrong, add more printing code, etc.,
                   11152: until the bug is found.
1.21      crook    11153: 
1.78      anton    11154: The simple debugging aids provided in @file{debugs.fs}
                   11155: are meant to support this style of debugging.
1.21      crook    11156: 
1.78      anton    11157: The word @code{~~} prints debugging information (by default the source
                   11158: location and the stack contents). It is easy to insert. If you use Emacs
                   11159: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   11160: query-replace them with nothing). The deferred words
                   11161: @code{printdebugdata} and @code{printdebugline} control the output of
                   11162: @code{~~}. The default source location output format works well with
                   11163: Emacs' compilation mode, so you can step through the program at the
                   11164: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   11165: is that you can step in any direction and you know where the crash has
                   11166: happened or where the strange data has occurred).
1.21      crook    11167: 
1.78      anton    11168: doc-~~
                   11169: doc-printdebugdata
                   11170: doc-printdebugline
1.21      crook    11171: 
1.78      anton    11172: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   11173: @subsection Assertions
                   11174: @cindex assertions
1.21      crook    11175: 
1.78      anton    11176: It is a good idea to make your programs self-checking, especially if you
                   11177: make an assumption that may become invalid during maintenance (for
                   11178: example, that a certain field of a data structure is never zero). Gforth
                   11179: supports @dfn{assertions} for this purpose. They are used like this:
1.21      crook    11180: 
                   11181: @example
1.78      anton    11182: assert( @i{flag} )
1.26      crook    11183: @end example
                   11184: 
1.78      anton    11185: The code between @code{assert(} and @code{)} should compute a flag, that
                   11186: should be true if everything is alright and false otherwise. It should
                   11187: not change anything else on the stack. The overall stack effect of the
                   11188: assertion is @code{( -- )}. E.g.
1.21      crook    11189: 
1.26      crook    11190: @example
1.78      anton    11191: assert( 1 1 + 2 = ) \ what we learn in school
                   11192: assert( dup 0<> ) \ assert that the top of stack is not zero
                   11193: assert( false ) \ this code should not be reached
1.21      crook    11194: @end example
                   11195: 
1.78      anton    11196: The need for assertions is different at different times. During
                   11197: debugging, we want more checking, in production we sometimes care more
                   11198: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   11199: becomes a comment. Depending on the importance of an assertion and the
                   11200: time it takes to check it, you may want to turn off some assertions and
                   11201: keep others turned on. Gforth provides several levels of assertions for
                   11202: this purpose:
                   11203: 
                   11204: 
                   11205: doc-assert0(
                   11206: doc-assert1(
                   11207: doc-assert2(
                   11208: doc-assert3(
                   11209: doc-assert(
                   11210: doc-)
1.21      crook    11211: 
                   11212: 
1.78      anton    11213: The variable @code{assert-level} specifies the highest assertions that
                   11214: are turned on. I.e., at the default @code{assert-level} of one,
                   11215: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   11216: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26      crook    11217: 
1.78      anton    11218: The value of @code{assert-level} is evaluated at compile-time, not at
                   11219: run-time. Therefore you cannot turn assertions on or off at run-time;
                   11220: you have to set the @code{assert-level} appropriately before compiling a
                   11221: piece of code. You can compile different pieces of code at different
                   11222: @code{assert-level}s (e.g., a trusted library at level 1 and
                   11223: newly-written code at level 3).
1.26      crook    11224: 
                   11225: 
1.78      anton    11226: doc-assert-level
1.26      crook    11227: 
                   11228: 
1.78      anton    11229: If an assertion fails, a message compatible with Emacs' compilation mode
                   11230: is produced and the execution is aborted (currently with @code{ABORT"}.
                   11231: If there is interest, we will introduce a special throw code. But if you
                   11232: intend to @code{catch} a specific condition, using @code{throw} is
                   11233: probably more appropriate than an assertion).
1.44      crook    11234: 
1.78      anton    11235: Definitions in ANS Forth for these assertion words are provided
                   11236: in @file{compat/assert.fs}.
1.26      crook    11237: 
1.44      crook    11238: 
1.78      anton    11239: @node Singlestep Debugger,  , Assertions, Programming Tools
                   11240: @subsection Singlestep Debugger
                   11241: @cindex singlestep Debugger
                   11242: @cindex debugging Singlestep
1.44      crook    11243: 
1.78      anton    11244: When you create a new word there's often the need to check whether it
                   11245: behaves correctly or not. You can do this by typing @code{dbg
                   11246: badword}. A debug session might look like this:
1.26      crook    11247: 
1.78      anton    11248: @example
                   11249: : badword 0 DO i . LOOP ;  ok
                   11250: 2 dbg badword 
                   11251: : badword  
                   11252: Scanning code...
1.44      crook    11253: 
1.78      anton    11254: Nesting debugger ready!
1.44      crook    11255: 
1.78      anton    11256: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   11257: 400D4740  8049F68 DO             -> [ 0 ] 
                   11258: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   11259: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   11260: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   11261: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   11262: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   11263: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   11264: 400D4758  804B384 ;              ->  ok
                   11265: @end example
1.21      crook    11266: 
1.78      anton    11267: Each line displayed is one step. You always have to hit return to
                   11268: execute the next word that is displayed. If you don't want to execute
                   11269: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   11270: an overview what keys are available:
1.44      crook    11271: 
1.78      anton    11272: @table @i
1.44      crook    11273: 
1.78      anton    11274: @item @key{RET}
                   11275: Next; Execute the next word.
1.21      crook    11276: 
1.78      anton    11277: @item n
                   11278: Nest; Single step through next word.
1.44      crook    11279: 
1.78      anton    11280: @item u
                   11281: Unnest; Stop debugging and execute rest of word. If we got to this word
                   11282: with nest, continue debugging with the calling word.
1.44      crook    11283: 
1.78      anton    11284: @item d
                   11285: Done; Stop debugging and execute rest.
1.21      crook    11286: 
1.78      anton    11287: @item s
                   11288: Stop; Abort immediately.
1.44      crook    11289: 
1.78      anton    11290: @end table
1.44      crook    11291: 
1.78      anton    11292: Debugging large application with this mechanism is very difficult, because
                   11293: you have to nest very deeply into the program before the interesting part
                   11294: begins. This takes a lot of time. 
1.26      crook    11295: 
1.78      anton    11296: To do it more directly put a @code{BREAK:} command into your source code.
                   11297: When program execution reaches @code{BREAK:} the single step debugger is
                   11298: invoked and you have all the features described above.
1.44      crook    11299: 
1.78      anton    11300: If you have more than one part to debug it is useful to know where the
                   11301: program has stopped at the moment. You can do this by the 
                   11302: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   11303: string is typed out when the ``breakpoint'' is reached.
1.44      crook    11304: 
1.26      crook    11305: 
1.78      anton    11306: doc-dbg
                   11307: doc-break:
                   11308: doc-break"
1.44      crook    11309: 
                   11310: 
1.26      crook    11311: 
1.78      anton    11312: @c -------------------------------------------------------------
                   11313: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   11314: @section Assembler and Code Words
                   11315: @cindex assembler
                   11316: @cindex code words
1.44      crook    11317: 
1.78      anton    11318: @menu
                   11319: * Code and ;code::              
                   11320: * Common Assembler::            Assembler Syntax
                   11321: * Common Disassembler::         
                   11322: * 386 Assembler::               Deviations and special cases
                   11323: * Alpha Assembler::             Deviations and special cases
                   11324: * MIPS assembler::              Deviations and special cases
                   11325: * Other assemblers::            How to write them
                   11326: @end menu
1.21      crook    11327: 
1.78      anton    11328: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
                   11329: @subsection @code{Code} and @code{;code}
1.26      crook    11330: 
1.78      anton    11331: Gforth provides some words for defining primitives (words written in
                   11332: machine code), and for defining the machine-code equivalent of
                   11333: @code{DOES>}-based defining words. However, the machine-independent
                   11334: nature of Gforth poses a few problems: First of all, Gforth runs on
                   11335: several architectures, so it can provide no standard assembler. What's
                   11336: worse is that the register allocation not only depends on the processor,
                   11337: but also on the @code{gcc} version and options used.
1.44      crook    11338: 
1.78      anton    11339: The words that Gforth offers encapsulate some system dependences (e.g.,
                   11340: the header structure), so a system-independent assembler may be used in
                   11341: Gforth. If you do not have an assembler, you can compile machine code
                   11342: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   11343: because these words emit stuff in @i{data} space; it works because
                   11344: Gforth has unified code/data spaces. Assembler isn't likely to be
                   11345: portable anyway.}.
1.21      crook    11346: 
1.44      crook    11347: 
1.78      anton    11348: doc-assembler
                   11349: doc-init-asm
                   11350: doc-code
                   11351: doc-end-code
                   11352: doc-;code
                   11353: doc-flush-icache
1.44      crook    11354: 
1.21      crook    11355: 
1.78      anton    11356: If @code{flush-icache} does not work correctly, @code{code} words
                   11357: etc. will not work (reliably), either.
1.44      crook    11358: 
1.78      anton    11359: The typical usage of these @code{code} words can be shown most easily by
                   11360: analogy to the equivalent high-level defining words:
1.44      crook    11361: 
1.78      anton    11362: @example
                   11363: : foo                              code foo
                   11364:    <high-level Forth words>              <assembler>
                   11365: ;                                  end-code
                   11366:                                 
                   11367: : bar                              : bar
                   11368:    <high-level Forth words>           <high-level Forth words>
                   11369:    CREATE                             CREATE
                   11370:       <high-level Forth words>           <high-level Forth words>
                   11371:    DOES>                              ;code
                   11372:       <high-level Forth words>           <assembler>
                   11373: ;                                  end-code
                   11374: @end example
1.21      crook    11375: 
1.78      anton    11376: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44      crook    11377: 
1.78      anton    11378: @cindex registers of the inner interpreter
                   11379: In the assembly code you will want to refer to the inner interpreter's
                   11380: registers (e.g., the data stack pointer) and you may want to use other
                   11381: registers for temporary storage. Unfortunately, the register allocation
                   11382: is installation-dependent.
1.44      crook    11383: 
1.78      anton    11384: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
                   11385: (return stack pointer) are in different places in @code{gforth} and
                   11386: @code{gforth-fast}.  This means that you cannot write a @code{NEXT}
                   11387: routine that works on both versions; so for doing @code{NEXT}, I
                   11388: recomment jumping to @code{' noop >code-address}, which contains nothing
                   11389: but a @code{NEXT}.
1.21      crook    11390: 
1.78      anton    11391: For general accesses to the inner interpreter's registers, the easiest
                   11392: solution is to use explicit register declarations (@pxref{Explicit Reg
                   11393: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
                   11394: all of the inner interpreter's registers: You have to compile Gforth
                   11395: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
                   11396: the appropriate declarations must be present in the @code{machine.h}
                   11397: file (see @code{mips.h} for an example; you can find a full list of all
                   11398: declarable register symbols with @code{grep register engine.c}). If you
                   11399: give explicit registers to all variables that are declared at the
                   11400: beginning of @code{engine()}, you should be able to use the other
                   11401: caller-saved registers for temporary storage. Alternatively, you can use
                   11402: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
                   11403: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
                   11404: reserve a register (however, this restriction on register allocation may
                   11405: slow Gforth significantly).
1.44      crook    11406: 
1.78      anton    11407: If this solution is not viable (e.g., because @code{gcc} does not allow
                   11408: you to explicitly declare all the registers you need), you have to find
                   11409: out by looking at the code where the inner interpreter's registers
                   11410: reside and which registers can be used for temporary storage. You can
                   11411: get an assembly listing of the engine's code with @code{make engine.s}.
1.44      crook    11412: 
1.78      anton    11413: In any case, it is good practice to abstract your assembly code from the
                   11414: actual register allocation. E.g., if the data stack pointer resides in
                   11415: register @code{$17}, create an alias for this register called @code{sp},
                   11416: and use that in your assembly code.
1.21      crook    11417: 
1.78      anton    11418: @cindex code words, portable
                   11419: Another option for implementing normal and defining words efficiently
                   11420: is to add the desired functionality to the source of Gforth. For normal
                   11421: words you just have to edit @file{primitives} (@pxref{Automatic
                   11422: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   11423: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   11424: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44      crook    11425: 
1.78      anton    11426: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
                   11427: @subsection Common Assembler
1.44      crook    11428: 
1.78      anton    11429: The assemblers in Gforth generally use a postfix syntax, i.e., the
                   11430: instruction name follows the operands.
1.21      crook    11431: 
1.78      anton    11432: The operands are passed in the usual order (the same that is used in the
                   11433: manual of the architecture).  Since they all are Forth words, they have
                   11434: to be separated by spaces; you can also use Forth words to compute the
                   11435: operands.
1.44      crook    11436: 
1.78      anton    11437: The instruction names usually end with a @code{,}.  This makes it easier
                   11438: to visually separate instructions if you put several of them on one
                   11439: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21      crook    11440: 
1.78      anton    11441: Registers are usually specified by number; e.g., (decimal) @code{11}
                   11442: specifies registers R11 and F11 on the Alpha architecture (which one,
                   11443: depends on the instruction).  The usual names are also available, e.g.,
                   11444: @code{s2} for R11 on Alpha.
1.21      crook    11445: 
1.78      anton    11446: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
                   11447: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
                   11448: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
                   11449: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
                   11450: conditions are specified in a way specific to each assembler.
1.1       anton    11451: 
1.78      anton    11452: Note that the register assignments of the Gforth engine can change
                   11453: between Gforth versions, or even between different compilations of the
                   11454: same Gforth version (e.g., if you use a different GCC version).  So if
                   11455: you want to refer to Gforth's registers (e.g., the stack pointer or
                   11456: TOS), I recommend defining your own words for refering to these
                   11457: registers, and using them later on; then you can easily adapt to a
                   11458: changed register assignment.  The stability of the register assignment
                   11459: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1       anton    11460: 
1.78      anton    11461: In particular, the return stack pointer and the instruction pointer are
                   11462: in memory in @code{gforth}, and usually in registers in
                   11463: @code{gforth-fast}.  The most common use of these registers is to
                   11464: dispatch to the next word (the @code{next} routine).  A portable way to
                   11465: do this is to jump to @code{' noop >code-address} (of course, this is
                   11466: less efficient than integrating the @code{next} code and scheduling it
                   11467: well).
1.1       anton    11468: 
1.78      anton    11469: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
                   11470: @subsection Common Disassembler
1.1       anton    11471: 
1.78      anton    11472: You can disassemble a @code{code} word with @code{see}
                   11473: (@pxref{Debugging}).  You can disassemble a section of memory with
1.1       anton    11474: 
1.78      anton    11475: doc-disasm
1.44      crook    11476: 
1.78      anton    11477: The disassembler generally produces output that can be fed into the
                   11478: assembler (i.e., same syntax, etc.).  It also includes additional
                   11479: information in comments.  In particular, the address of the instruction
                   11480: is given in a comment before the instruction.
1.1       anton    11481: 
1.78      anton    11482: @code{See} may display more or less than the actual code of the word,
                   11483: because the recognition of the end of the code is unreliable.  You can
                   11484: use @code{disasm} if it did not display enough.  It may display more, if
                   11485: the code word is not immediately followed by a named word.  If you have
                   11486: something else there, you can follow the word with @code{align last @ ,}
                   11487: to ensure that the end is recognized.
1.21      crook    11488: 
1.78      anton    11489: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
                   11490: @subsection 386 Assembler
1.44      crook    11491: 
1.78      anton    11492: The 386 assembler included in Gforth was written by Bernd Paysan, it's
                   11493: available under GPL, and originally part of bigFORTH.
1.21      crook    11494: 
1.78      anton    11495: The 386 disassembler included in Gforth was written by Andrew McKewan
                   11496: and is in the public domain.
1.21      crook    11497: 
1.78      anton    11498: The disassembler displays code in prefix Intel syntax.
1.21      crook    11499: 
1.78      anton    11500: The assembler uses a postfix syntax with reversed parameters.
1.1       anton    11501: 
1.78      anton    11502: The assembler includes all instruction of the Athlon, i.e. 486 core
                   11503: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
                   11504: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
                   11505: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1       anton    11506: 
1.78      anton    11507: There are several prefixes to switch between different operation sizes,
                   11508: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
                   11509: double-word accesses. Addressing modes can be switched with @code{.wa}
                   11510: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
                   11511: need a prefix for byte register names (@code{AL} et al).
1.1       anton    11512: 
1.78      anton    11513: For floating point operations, the prefixes are @code{.fs} (IEEE
                   11514: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
                   11515: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21      crook    11516: 
1.78      anton    11517: The MMX opcodes don't have size prefixes, they are spelled out like in
                   11518: the Intel assembler. Instead of move from and to memory, there are
                   11519: PLDQ/PLDD and PSTQ/PSTD.
1.21      crook    11520: 
1.78      anton    11521: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
                   11522: ax.  Immediate values are indicated by postfixing them with @code{#},
                   11523: e.g., @code{3 #}.  Here are some examples of addressing modes:
1.21      crook    11524: 
1.26      crook    11525: @example
1.78      anton    11526: 3 #          \ immediate
                   11527: ax           \ register
                   11528: 100 di d)    \ 100[edi]
                   11529: 4 bx cx di)  \ 4[ebx][ecx]
                   11530: di ax *4 i)  \ [edi][eax*4]
                   11531: 20 ax *4 i#) \ 20[eax*4]
1.26      crook    11532: @end example
1.21      crook    11533: 
1.78      anton    11534: Some example of instructions are:
1.1       anton    11535: 
                   11536: @example
1.78      anton    11537: ax bx mov             \ move ebx,eax
                   11538: 3 # ax mov            \ mov eax,3
                   11539: 100 di ) ax mov       \ mov eax,100[edi]
                   11540: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
                   11541: .w ax bx mov          \ mov bx,ax
1.1       anton    11542: @end example
                   11543: 
1.78      anton    11544: The following forms are supported for binary instructions:
1.1       anton    11545: 
                   11546: @example
1.78      anton    11547: <reg> <reg> <inst>
                   11548: <n> # <reg> <inst>
                   11549: <mem> <reg> <inst>
                   11550: <reg> <mem> <inst>
1.1       anton    11551: @end example
                   11552: 
1.78      anton    11553: Immediate to memory is not supported.  The shift/rotate syntax is:
1.1       anton    11554: 
1.26      crook    11555: @example
1.78      anton    11556: <reg/mem> 1 # shl \ shortens to shift without immediate
                   11557: <reg/mem> 4 # shl
                   11558: <reg/mem> cl shl
1.26      crook    11559: @end example
1.1       anton    11560: 
1.78      anton    11561: Precede string instructions (@code{movs} etc.) with @code{.b} to get
                   11562: the byte version.
1.1       anton    11563: 
1.78      anton    11564: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
                   11565: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
                   11566: pc < >= <= >}. (Note that most of these words shadow some Forth words
                   11567: when @code{assembler} is in front of @code{forth} in the search path,
                   11568: e.g., in @code{code} words).  Currently the control structure words use
                   11569: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
                   11570: to shuffle them (you can also use @code{swap} etc.).
1.21      crook    11571: 
1.78      anton    11572: Here is an example of a @code{code} word (assumes that the stack pointer
                   11573: is in esi and the TOS is in ebx):
1.21      crook    11574: 
1.26      crook    11575: @example
1.78      anton    11576: code my+ ( n1 n2 -- n )
                   11577:     4 si D) bx add
                   11578:     4 # si add
                   11579:     Next
                   11580: end-code
1.26      crook    11581: @end example
1.21      crook    11582: 
1.78      anton    11583: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
                   11584: @subsection Alpha Assembler
1.21      crook    11585: 
1.78      anton    11586: The Alpha assembler and disassembler were originally written by Bernd
                   11587: Thallner.
1.26      crook    11588: 
1.78      anton    11589: The register names @code{a0}--@code{a5} are not available to avoid
                   11590: shadowing hex numbers.
1.2       jwilke   11591: 
1.78      anton    11592: Immediate forms of arithmetic instructions are distinguished by a
                   11593: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
                   11594: does not count as arithmetic instruction).
1.2       jwilke   11595: 
1.78      anton    11596: You have to specify all operands to an instruction, even those that
                   11597: other assemblers consider optional, e.g., the destination register for
                   11598: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2       jwilke   11599: 
1.78      anton    11600: You can specify conditions for @code{if,} by removing the first @code{b}
                   11601: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2       jwilke   11602: 
1.26      crook    11603: @example
1.78      anton    11604: 11 fgt if, \ if F11>0e
                   11605:   ...
                   11606: endif,
1.26      crook    11607: @end example
1.2       jwilke   11608: 
1.78      anton    11609: @code{fbgt,} gives @code{fgt}.  
                   11610: 
                   11611: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
                   11612: @subsection MIPS assembler
1.2       jwilke   11613: 
1.78      anton    11614: The MIPS assembler was originally written by Christian Pirker.
1.2       jwilke   11615: 
1.78      anton    11616: Currently the assembler and disassembler only cover the MIPS-I
                   11617: architecture (R3000), and don't support FP instructions.
1.2       jwilke   11618: 
1.78      anton    11619: The register names @code{$a0}--@code{$a3} are not available to avoid
                   11620: shadowing hex numbers.
1.2       jwilke   11621: 
1.78      anton    11622: Because there is no way to distinguish registers from immediate values,
                   11623: you have to explicitly use the immediate forms of instructions, i.e.,
                   11624: @code{addiu,}, not just @code{addu,} (@command{as} does this
                   11625: implicitly).
1.2       jwilke   11626: 
1.78      anton    11627: If the architecture manual specifies several formats for the instruction
                   11628: (e.g., for @code{jalr,}), you usually have to use the one with more
                   11629: arguments (i.e., two for @code{jalr,}).  When in doubt, see
                   11630: @code{arch/mips/testasm.fs} for an example of correct use.
1.2       jwilke   11631: 
1.78      anton    11632: Branches and jumps in the MIPS architecture have a delay slot.  You have
                   11633: to fill it yourself (the simplest way is to use @code{nop,}), the
                   11634: assembler does not do it for you (unlike @command{as}).  Even
                   11635: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
                   11636: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
                   11637: and @code{then,} just specify branch targets, they are not affected.
1.2       jwilke   11638: 
1.78      anton    11639: Note that you must not put branches, jumps, or @code{li,} into the delay
                   11640: slot: @code{li,} may expand to several instructions, and control flow
                   11641: instructions may not be put into the branch delay slot in any case.
1.2       jwilke   11642: 
1.78      anton    11643: For branches the argument specifying the target is a relative address;
                   11644: You have to add the address of the delay slot to get the absolute
                   11645: address.
1.1       anton    11646: 
1.78      anton    11647: The MIPS architecture also has load delay slots and restrictions on
                   11648: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
                   11649: yourself to satisfy these restrictions, the assembler does not do it for
                   11650: you.
1.1       anton    11651: 
1.78      anton    11652: You can specify the conditions for @code{if,} etc. by taking a
                   11653: conditional branch and leaving away the @code{b} at the start and the
                   11654: @code{,} at the end.  E.g.,
1.1       anton    11655: 
1.26      crook    11656: @example
1.78      anton    11657: 4 5 eq if,
                   11658:   ... \ do something if $4 equals $5
                   11659: then,
1.26      crook    11660: @end example
1.1       anton    11661: 
1.78      anton    11662: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
                   11663: @subsection Other assemblers
                   11664: 
                   11665: If you want to contribute another assembler/disassembler, please contact
                   11666: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
                   11667: already.  If you are writing them from scratch, please use a similar
                   11668: syntax style as the one we use (i.e., postfix, commas at the end of the
                   11669: instruction names, @pxref{Common Assembler}); make the output of the
                   11670: disassembler be valid input for the assembler, and keep the style
                   11671: similar to the style we used.
                   11672: 
                   11673: Hints on implementation: The most important part is to have a good test
                   11674: suite that contains all instructions.  Once you have that, the rest is
                   11675: easy.  For actual coding you can take a look at
                   11676: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
                   11677: the assembler and disassembler, avoiding redundancy and some potential
                   11678: bugs.  You can also look at that file (and @pxref{Advanced does> usage
                   11679: example}) to get ideas how to factor a disassembler.
                   11680: 
                   11681: Start with the disassembler, because it's easier to reuse data from the
                   11682: disassembler for the assembler than the other way round.
1.1       anton    11683: 
1.78      anton    11684: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
                   11685: how simple it can be.
1.1       anton    11686: 
1.78      anton    11687: @c -------------------------------------------------------------
                   11688: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
                   11689: @section Threading Words
                   11690: @cindex threading words
1.1       anton    11691: 
1.78      anton    11692: @cindex code address
                   11693: These words provide access to code addresses and other threading stuff
                   11694: in Gforth (and, possibly, other interpretive Forths). It more or less
                   11695: abstracts away the differences between direct and indirect threading
                   11696: (and, for direct threading, the machine dependences). However, at
                   11697: present this wordset is still incomplete. It is also pretty low-level;
                   11698: some day it will hopefully be made unnecessary by an internals wordset
                   11699: that abstracts implementation details away completely.
1.1       anton    11700: 
1.78      anton    11701: The terminology used here stems from indirect threaded Forth systems; in
                   11702: such a system, the XT of a word is represented by the CFA (code field
                   11703: address) of a word; the CFA points to a cell that contains the code
                   11704: address.  The code address is the address of some machine code that
                   11705: performs the run-time action of invoking the word (e.g., the
                   11706: @code{dovar:} routine pushes the address of the body of the word (a
                   11707: variable) on the stack
                   11708: ).
1.1       anton    11709: 
1.78      anton    11710: @cindex code address
                   11711: @cindex code field address
                   11712: In an indirect threaded Forth, you can get the code address of @i{name}
                   11713: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
                   11714: >code-address}, independent of the threading method.
1.1       anton    11715: 
1.78      anton    11716: doc-threading-method
                   11717: doc->code-address
                   11718: doc-code-address!
1.1       anton    11719: 
1.78      anton    11720: @cindex @code{does>}-handler
                   11721: @cindex @code{does>}-code
                   11722: For a word defined with @code{DOES>}, the code address usually points to
                   11723: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
                   11724: routine (in Gforth on some platforms, it can also point to the dodoes
                   11725: routine itself).  What you are typically interested in, though, is
                   11726: whether a word is a @code{DOES>}-defined word, and what Forth code it
                   11727: executes; @code{>does-code} tells you that.
1.1       anton    11728: 
1.78      anton    11729: doc->does-code
1.1       anton    11730: 
1.78      anton    11731: To create a @code{DOES>}-defined word with the following basic words,
                   11732: you have to set up a @code{DOES>}-handler with @code{does-handler!};
                   11733: @code{/does-handler} aus behind you have to place your executable Forth
                   11734: code.  Finally you have to create a word and modify its behaviour with
                   11735: @code{does-handler!}.
1.1       anton    11736: 
1.78      anton    11737: doc-does-code!
                   11738: doc-does-handler!
                   11739: doc-/does-handler
1.1       anton    11740: 
1.78      anton    11741: The code addresses produced by various defining words are produced by
                   11742: the following words:
1.1       anton    11743: 
1.78      anton    11744: doc-docol:
                   11745: doc-docon:
                   11746: doc-dovar:
                   11747: doc-douser:
                   11748: doc-dodefer:
                   11749: doc-dofield:
1.1       anton    11750: 
1.26      crook    11751: @c -------------------------------------------------------------
1.78      anton    11752: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21      crook    11753: @section Passing Commands to the Operating System
                   11754: @cindex operating system - passing commands
                   11755: @cindex shell commands
                   11756: 
                   11757: Gforth allows you to pass an arbitrary string to the host operating
                   11758: system shell (if such a thing exists) for execution.
                   11759: 
1.44      crook    11760: 
1.21      crook    11761: doc-sh
                   11762: doc-system
                   11763: doc-$?
1.23      crook    11764: doc-getenv
1.21      crook    11765: 
1.44      crook    11766: 
1.26      crook    11767: @c -------------------------------------------------------------
1.47      crook    11768: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
                   11769: @section Keeping track of Time
                   11770: @cindex time-related words
                   11771: 
                   11772: doc-ms
                   11773: doc-time&date
1.79      anton    11774: doc-utime
                   11775: doc-cputime
1.47      crook    11776: 
                   11777: 
                   11778: @c -------------------------------------------------------------
                   11779: @node Miscellaneous Words,  , Keeping track of Time, Words
1.21      crook    11780: @section Miscellaneous Words
                   11781: @cindex miscellaneous words
                   11782: 
1.29      crook    11783: @comment TODO find homes for these
                   11784: 
1.26      crook    11785: These section lists the ANS Forth words that are not documented
1.21      crook    11786: elsewhere in this manual. Ultimately, they all need proper homes.
                   11787: 
                   11788: doc-[compile]
1.68      anton    11789: doc-quit
1.44      crook    11790: 
1.26      crook    11791: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    11792: (@pxref{ANS conformance}):
1.21      crook    11793: 
                   11794: @code{EDITOR} 
                   11795: @code{EMIT?} 
                   11796: @code{FORGET} 
                   11797: 
1.24      anton    11798: @c ******************************************************************
                   11799: @node Error messages, Tools, Words, Top
                   11800: @chapter Error messages
                   11801: @cindex error messages
                   11802: @cindex backtrace
                   11803: 
                   11804: A typical Gforth error message looks like this:
                   11805: 
                   11806: @example
                   11807: in file included from :-1
                   11808: in file included from ./yyy.fs:1
                   11809: ./xxx.fs:4: Invalid memory address
                   11810: bar
                   11811: ^^^
1.79      anton    11812: Backtrace:
1.25      anton    11813: $400E664C @@
                   11814: $400E6664 foo
1.24      anton    11815: @end example
                   11816: 
                   11817: The message identifying the error is @code{Invalid memory address}.  The
                   11818: error happened when text-interpreting line 4 of the file
                   11819: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   11820: word on the line where the error happened, is pointed out (with
                   11821: @code{^^^}).
                   11822: 
                   11823: The file containing the error was included in line 1 of @file{./yyy.fs},
                   11824: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   11825: @file{yyy.fs} as command-line parameter to Gforth).
                   11826: 
                   11827: At the end of the error message you find a return stack dump that can be
                   11828: interpreted as a backtrace (possibly empty). On top you find the top of
                   11829: the return stack when the @code{throw} happened, and at the bottom you
                   11830: find the return stack entry just above the return stack of the topmost
                   11831: text interpreter.
                   11832: 
                   11833: To the right of most return stack entries you see a guess for the word
                   11834: that pushed that return stack entry as its return address. This gives a
                   11835: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   11836: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   11837: address} exception).
                   11838: 
                   11839: Note that the backtrace is not perfect: We don't know which return stack
                   11840: entries are return addresses (so we may get false positives); and in
                   11841: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   11842: address the word that pushed the return address, so for some return
                   11843: addresses you see no names in the return stack dump.
1.25      anton    11844: 
                   11845: @cindex @code{catch} and backtraces
                   11846: The return stack dump represents the return stack at the time when a
                   11847: specific @code{throw} was executed.  In programs that make use of
                   11848: @code{catch}, it is not necessarily clear which @code{throw} should be
                   11849: used for the return stack dump (e.g., consider one @code{throw} that
                   11850: indicates an error, which is caught, and during recovery another error
1.42      anton    11851: happens; which @code{throw} should be used for the stack dump?).  Gforth
1.25      anton    11852: presents the return stack dump for the first @code{throw} after the last
                   11853: executed (not returned-to) @code{catch}; this works well in the usual
                   11854: case.
                   11855: 
                   11856: @cindex @code{gforth-fast} and backtraces
                   11857: @cindex @code{gforth-fast}, difference from @code{gforth}
                   11858: @cindex backtraces with @code{gforth-fast}
                   11859: @cindex return stack dump with @code{gforth-fast}
1.79      anton    11860: @code{Gforth} is able to do a return stack dump for throws generated
1.25      anton    11861: from primitives (e.g., invalid memory address, stack empty etc.);
                   11862: @code{gforth-fast} is only able to do a return stack dump from a
                   11863: directly called @code{throw} (including @code{abort} etc.).  This is the
1.30      anton    11864: only difference (apart from a speed factor of between 1.15 (K6-2) and
1.78      anton    11865: 2 (21264)) between @code{gforth} and @code{gforth-fast}.  Given an
1.30      anton    11866: exception caused by a primitive in @code{gforth-fast}, you will
                   11867: typically see no return stack dump at all; however, if the exception is
                   11868: caught by @code{catch} (e.g., for restoring some state), and then
                   11869: @code{throw}n again, the return stack dump will be for the first such
                   11870: @code{throw}.
1.2       jwilke   11871: 
1.5       anton    11872: @c ******************************************************************
1.24      anton    11873: @node Tools, ANS conformance, Error messages, Top
1.1       anton    11874: @chapter Tools
                   11875: 
                   11876: @menu
                   11877: * ANS Report::                  Report the words used, sorted by wordset.
                   11878: @end menu
                   11879: 
                   11880: See also @ref{Emacs and Gforth}.
                   11881: 
                   11882: @node ANS Report,  , Tools, Tools
                   11883: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   11884: @cindex @file{ans-report.fs}
                   11885: @cindex report the words used in your program
                   11886: @cindex words used in your program
                   11887: 
                   11888: If you want to label a Forth program as ANS Forth Program, you must
                   11889: document which wordsets the program uses; for extension wordsets, it is
                   11890: helpful to list the words the program requires from these wordsets
                   11891: (because Forth systems are allowed to provide only some words of them).
                   11892: 
                   11893: The @file{ans-report.fs} tool makes it easy for you to determine which
                   11894: words from which wordset and which non-ANS words your application
                   11895: uses. You simply have to include @file{ans-report.fs} before loading the
                   11896: program you want to check. After loading your program, you can get the
                   11897: report with @code{print-ans-report}. A typical use is to run this as
                   11898: batch job like this:
                   11899: @example
                   11900: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   11901: @end example
                   11902: 
                   11903: The output looks like this (for @file{compat/control.fs}):
                   11904: @example
                   11905: The program uses the following words
                   11906: from CORE :
                   11907: : POSTPONE THEN ; immediate ?dup IF 0= 
                   11908: from BLOCK-EXT :
                   11909: \ 
                   11910: from FILE :
                   11911: ( 
                   11912: @end example
                   11913: 
                   11914: @subsection Caveats
                   11915: 
                   11916: Note that @file{ans-report.fs} just checks which words are used, not whether
                   11917: they are used in an ANS Forth conforming way!
                   11918: 
                   11919: Some words are defined in several wordsets in the
                   11920: standard. @file{ans-report.fs} reports them for only one of the
                   11921: wordsets, and not necessarily the one you expect. It depends on usage
                   11922: which wordset is the right one to specify. E.g., if you only use the
                   11923: compilation semantics of @code{S"}, it is a Core word; if you also use
                   11924: its interpretation semantics, it is a File word.
                   11925: 
                   11926: @c ******************************************************************
1.65      anton    11927: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1       anton    11928: @chapter ANS conformance
                   11929: @cindex ANS conformance of Gforth
                   11930: 
                   11931: To the best of our knowledge, Gforth is an
                   11932: 
                   11933: ANS Forth System
                   11934: @itemize @bullet
                   11935: @item providing the Core Extensions word set
                   11936: @item providing the Block word set
                   11937: @item providing the Block Extensions word set
                   11938: @item providing the Double-Number word set
                   11939: @item providing the Double-Number Extensions word set
                   11940: @item providing the Exception word set
                   11941: @item providing the Exception Extensions word set
                   11942: @item providing the Facility word set
1.40      anton    11943: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1       anton    11944: @item providing the File Access word set
                   11945: @item providing the File Access Extensions word set
                   11946: @item providing the Floating-Point word set
                   11947: @item providing the Floating-Point Extensions word set
                   11948: @item providing the Locals word set
                   11949: @item providing the Locals Extensions word set
                   11950: @item providing the Memory-Allocation word set
                   11951: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   11952: @item providing the Programming-Tools word set
                   11953: @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
                   11954: @item providing the Search-Order word set
                   11955: @item providing the Search-Order Extensions word set
                   11956: @item providing the String word set
                   11957: @item providing the String Extensions word set (another easy one)
                   11958: @end itemize
                   11959: 
                   11960: @cindex system documentation
                   11961: In addition, ANS Forth systems are required to document certain
                   11962: implementation choices. This chapter tries to meet these
                   11963: requirements. In many cases it gives a way to ask the system for the
                   11964: information instead of providing the information directly, in
                   11965: particular, if the information depends on the processor, the operating
                   11966: system or the installation options chosen, or if they are likely to
                   11967: change during the maintenance of Gforth.
                   11968: 
                   11969: @comment The framework for the rest has been taken from pfe.
                   11970: 
                   11971: @menu
                   11972: * The Core Words::              
                   11973: * The optional Block word set::  
                   11974: * The optional Double Number word set::  
                   11975: * The optional Exception word set::  
                   11976: * The optional Facility word set::  
                   11977: * The optional File-Access word set::  
                   11978: * The optional Floating-Point word set::  
                   11979: * The optional Locals word set::  
                   11980: * The optional Memory-Allocation word set::  
                   11981: * The optional Programming-Tools word set::  
                   11982: * The optional Search-Order word set::  
                   11983: @end menu
                   11984: 
                   11985: 
                   11986: @c =====================================================================
                   11987: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   11988: @comment  node-name,  next,  previous,  up
                   11989: @section The Core Words
                   11990: @c =====================================================================
                   11991: @cindex core words, system documentation
                   11992: @cindex system documentation, core words
                   11993: 
                   11994: @menu
                   11995: * core-idef::                   Implementation Defined Options                   
                   11996: * core-ambcond::                Ambiguous Conditions                
                   11997: * core-other::                  Other System Documentation                  
                   11998: @end menu
                   11999: 
                   12000: @c ---------------------------------------------------------------------
                   12001: @node core-idef, core-ambcond, The Core Words, The Core Words
                   12002: @subsection Implementation Defined Options
                   12003: @c ---------------------------------------------------------------------
                   12004: @cindex core words, implementation-defined options
                   12005: @cindex implementation-defined options, core words
                   12006: 
                   12007: 
                   12008: @table @i
                   12009: @item (Cell) aligned addresses:
                   12010: @cindex cell-aligned addresses
                   12011: @cindex aligned addresses
                   12012: processor-dependent. Gforth's alignment words perform natural alignment
                   12013: (e.g., an address aligned for a datum of size 8 is divisible by
                   12014: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   12015: 
                   12016: @item @code{EMIT} and non-graphic characters:
                   12017: @cindex @code{EMIT} and non-graphic characters
                   12018: @cindex non-graphic characters and @code{EMIT}
                   12019: The character is output using the C library function (actually, macro)
                   12020: @code{putc}.
                   12021: 
                   12022: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   12023: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   12024: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   12025: @cindex @code{ACCEPT}, editing
                   12026: @cindex @code{EXPECT}, editing
                   12027: This is modeled on the GNU readline library (@pxref{Readline
                   12028: Interaction, , Command Line Editing, readline, The GNU Readline
                   12029: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   12030: producing a full word completion every time you type it (instead of
1.28      crook    12031: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    12032: 
                   12033: @item character set:
                   12034: @cindex character set
                   12035: The character set of your computer and display device. Gforth is
                   12036: 8-bit-clean (but some other component in your system may make trouble).
                   12037: 
                   12038: @item Character-aligned address requirements:
                   12039: @cindex character-aligned address requirements
                   12040: installation-dependent. Currently a character is represented by a C
                   12041: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   12042: (Comments on that requested).
                   12043: 
                   12044: @item character-set extensions and matching of names:
                   12045: @cindex character-set extensions and matching of names
1.26      crook    12046: @cindex case-sensitivity for name lookup
                   12047: @cindex name lookup, case-sensitivity
                   12048: @cindex locale and case-sensitivity
1.21      crook    12049: Any character except the ASCII NUL character can be used in a
1.1       anton    12050: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47      crook    12051: matching is performed using the C library function @code{strncasecmp}, whose
1.1       anton    12052: function is probably influenced by the locale. E.g., the @code{C} locale
                   12053: does not know about accents and umlauts, so they are matched
                   12054: case-sensitively in that locale. For portability reasons it is best to
                   12055: write programs such that they work in the @code{C} locale. Then one can
                   12056: use libraries written by a Polish programmer (who might use words
                   12057: containing ISO Latin-2 encoded characters) and by a French programmer
                   12058: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   12059: funny results for some of the words (which ones, depends on the font you
                   12060: are using)). Also, the locale you prefer may not be available in other
                   12061: operating systems. Hopefully, Unicode will solve these problems one day.
                   12062: 
                   12063: @item conditions under which control characters match a space delimiter:
                   12064: @cindex space delimiters
                   12065: @cindex control characters as delimiters
                   12066: If @code{WORD} is called with the space character as a delimiter, all
                   12067: white-space characters (as identified by the C macro @code{isspace()})
                   12068: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44      crook    12069: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.79      anton    12070: like @code{PARSE} otherwise. @code{Name}, which is used by the outer
1.1       anton    12071: interpreter (aka text interpreter) by default, treats all white-space
                   12072: characters as delimiters.
                   12073: 
1.26      crook    12074: @item format of the control-flow stack:
                   12075: @cindex control-flow stack, format
                   12076: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    12077: stack item in cells is given by the constant @code{cs-item-size}. At the
                   12078: time of this writing, an item consists of a (pointer to a) locals list
                   12079: (third), an address in the code (second), and a tag for identifying the
                   12080: item (TOS). The following tags are used: @code{defstart},
                   12081: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   12082: @code{scopestart}.
                   12083: 
                   12084: @item conversion of digits > 35
                   12085: @cindex digits > 35
                   12086: The characters @code{[\]^_'} are the digits with the decimal value
                   12087: 36@minus{}41. There is no way to input many of the larger digits.
                   12088: 
                   12089: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   12090: @cindex @code{EXPECT}, display after end of input
                   12091: @cindex @code{ACCEPT}, display after end of input
                   12092: The cursor is moved to the end of the entered string. If the input is
                   12093: terminated using the @kbd{Return} key, a space is typed.
                   12094: 
                   12095: @item exception abort sequence of @code{ABORT"}:
                   12096: @cindex exception abort sequence of @code{ABORT"}
                   12097: @cindex @code{ABORT"}, exception abort sequence
                   12098: The error string is stored into the variable @code{"error} and a
                   12099: @code{-2 throw} is performed.
                   12100: 
                   12101: @item input line terminator:
                   12102: @cindex input line terminator
                   12103: @cindex line terminator on input
1.26      crook    12104: @cindex newline character on input
1.1       anton    12105: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   12106: lines. One of these characters is typically produced when you type the
                   12107: @kbd{Enter} or @kbd{Return} key.
                   12108: 
                   12109: @item maximum size of a counted string:
                   12110: @cindex maximum size of a counted string
                   12111: @cindex counted string, maximum size
                   12112: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79      anton    12113: on all platforms, but this may change.
1.1       anton    12114: 
                   12115: @item maximum size of a parsed string:
                   12116: @cindex maximum size of a parsed string
                   12117: @cindex parsed string, maximum size
                   12118: Given by the constant @code{/line}. Currently 255 characters.
                   12119: 
                   12120: @item maximum size of a definition name, in characters:
                   12121: @cindex maximum size of a definition name, in characters
                   12122: @cindex name, maximum length
                   12123: 31
                   12124: 
                   12125: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   12126: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   12127: @cindex @code{ENVIRONMENT?} string length, maximum
                   12128: 31
                   12129: 
                   12130: @item method of selecting the user input device:
                   12131: @cindex user input device, method of selecting
                   12132: The user input device is the standard input. There is currently no way to
                   12133: change it from within Gforth. However, the input can typically be
                   12134: redirected in the command line that starts Gforth.
                   12135: 
                   12136: @item method of selecting the user output device:
                   12137: @cindex user output device, method of selecting
                   12138: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    12139: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   12140: output when the user output device is a terminal, otherwise the output
                   12141: is buffered.
1.1       anton    12142: 
                   12143: @item methods of dictionary compilation:
                   12144: What are we expected to document here?
                   12145: 
                   12146: @item number of bits in one address unit:
                   12147: @cindex number of bits in one address unit
                   12148: @cindex address unit, size in bits
                   12149: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79      anton    12150: platforms.
1.1       anton    12151: 
                   12152: @item number representation and arithmetic:
                   12153: @cindex number representation and arithmetic
1.79      anton    12154: Processor-dependent. Binary two's complement on all current platforms.
1.1       anton    12155: 
                   12156: @item ranges for integer types:
                   12157: @cindex ranges for integer types
                   12158: @cindex integer types, ranges
                   12159: Installation-dependent. Make environmental queries for @code{MAX-N},
                   12160: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   12161: unsigned (and positive) types is 0. The lower bound for signed types on
                   12162: two's complement and one's complement machines machines can be computed
                   12163: by adding 1 to the upper bound.
                   12164: 
                   12165: @item read-only data space regions:
                   12166: @cindex read-only data space regions
                   12167: @cindex data-space, read-only regions
                   12168: The whole Forth data space is writable.
                   12169: 
                   12170: @item size of buffer at @code{WORD}:
                   12171: @cindex size of buffer at @code{WORD}
                   12172: @cindex @code{WORD} buffer size
                   12173: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   12174: shared with the pictured numeric output string. If overwriting
                   12175: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   12176: space, although only as much can be sensibly used as fits in a counted
                   12177: string.
                   12178: 
                   12179: @item size of one cell in address units:
                   12180: @cindex cell size
                   12181: @code{1 cells .}.
                   12182: 
                   12183: @item size of one character in address units:
                   12184: @cindex char size
1.79      anton    12185: @code{1 chars .}. 1 on all current platforms.
1.1       anton    12186: 
                   12187: @item size of the keyboard terminal buffer:
                   12188: @cindex size of the keyboard terminal buffer
                   12189: @cindex terminal buffer, size
                   12190: Varies. You can determine the size at a specific time using @code{lp@@
                   12191: tib - .}. It is shared with the locals stack and TIBs of files that
                   12192: include the current file. You can change the amount of space for TIBs
                   12193: and locals stack at Gforth startup with the command line option
                   12194: @code{-l}.
                   12195: 
                   12196: @item size of the pictured numeric output buffer:
                   12197: @cindex size of the pictured numeric output buffer
                   12198: @cindex pictured numeric output buffer, size
                   12199: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   12200: shared with @code{WORD}.
                   12201: 
                   12202: @item size of the scratch area returned by @code{PAD}:
                   12203: @cindex size of the scratch area returned by @code{PAD}
                   12204: @cindex @code{PAD} size
                   12205: The remainder of dictionary space. @code{unused pad here - - .}.
                   12206: 
                   12207: @item system case-sensitivity characteristics:
                   12208: @cindex case-sensitivity characteristics
1.26      crook    12209: Dictionary searches are case-insensitive (except in
1.1       anton    12210: @code{TABLE}s). However, as explained above under @i{character-set
                   12211: extensions}, the matching for non-ASCII characters is determined by the
                   12212: locale you are using. In the default @code{C} locale all non-ASCII
                   12213: characters are matched case-sensitively.
                   12214: 
                   12215: @item system prompt:
                   12216: @cindex system prompt
                   12217: @cindex prompt
                   12218: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   12219: 
                   12220: @item division rounding:
                   12221: @cindex division rounding
                   12222: installation dependent. @code{s" floored" environment? drop .}. We leave
                   12223: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
                   12224: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
                   12225: 
                   12226: @item values of @code{STATE} when true:
                   12227: @cindex @code{STATE} values
                   12228: -1.
                   12229: 
                   12230: @item values returned after arithmetic overflow:
                   12231: On two's complement machines, arithmetic is performed modulo
                   12232: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   12233: arithmetic (with appropriate mapping for signed types). Division by zero
                   12234: typically results in a @code{-55 throw} (Floating-point unidentified
1.80    ! anton    12235: fault) or @code{-10 throw} (divide by zero).
1.1       anton    12236: 
                   12237: @item whether the current definition can be found after @t{DOES>}:
                   12238: @cindex @t{DOES>}, visibility of current definition
                   12239: No.
                   12240: 
                   12241: @end table
                   12242: 
                   12243: @c ---------------------------------------------------------------------
                   12244: @node core-ambcond, core-other, core-idef, The Core Words
                   12245: @subsection Ambiguous conditions
                   12246: @c ---------------------------------------------------------------------
                   12247: @cindex core words, ambiguous conditions
                   12248: @cindex ambiguous conditions, core words
                   12249: 
                   12250: @table @i
                   12251: 
                   12252: @item a name is neither a word nor a number:
                   12253: @cindex name not found
1.26      crook    12254: @cindex undefined word
1.80    ! anton    12255: @code{-13 throw} (Undefined word).
1.1       anton    12256: 
                   12257: @item a definition name exceeds the maximum length allowed:
1.26      crook    12258: @cindex word name too long
1.1       anton    12259: @code{-19 throw} (Word name too long)
                   12260: 
                   12261: @item addressing a region not inside the various data spaces of the forth system:
                   12262: @cindex Invalid memory address
1.32      anton    12263: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    12264: typically readable. Accessing other addresses gives results dependent on
                   12265: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   12266: address).
                   12267: 
                   12268: @item argument type incompatible with parameter:
1.26      crook    12269: @cindex argument type mismatch
1.1       anton    12270: This is usually not caught. Some words perform checks, e.g., the control
                   12271: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   12272: mismatch).
                   12273: 
                   12274: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   12275: @cindex Interpreting a compile-only word, for @code{'} etc.
                   12276: @cindex execution token of words with undefined execution semantics
                   12277: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   12278: get an execution token for @code{compile-only-error} (which performs a
                   12279: @code{-14 throw} when executed).
                   12280: 
                   12281: @item dividing by zero:
                   12282: @cindex dividing by zero
                   12283: @cindex floating point unidentified fault, integer division
1.80    ! anton    12284: On some platforms, this produces a @code{-10 throw} (Division by
1.24      anton    12285: zero); on other systems, this typically results in a @code{-55 throw}
                   12286: (Floating-point unidentified fault).
1.1       anton    12287: 
                   12288: @item insufficient data stack or return stack space:
                   12289: @cindex insufficient data stack or return stack space
                   12290: @cindex stack overflow
1.26      crook    12291: @cindex address alignment exception, stack overflow
1.1       anton    12292: @cindex Invalid memory address, stack overflow
                   12293: Depending on the operating system, the installation, and the invocation
                   12294: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    12295: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   12296: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   12297: throw} (Invalid memory address) (depending on the platform and how you
                   12298: achieved the overflow) as soon as the overflow happens. If it is not
                   12299: checked, overflows typically result in mysterious illegal memory
                   12300: accesses, producing @code{-9 throw} (Invalid memory address) or
                   12301: @code{-23 throw} (Address alignment exception); they might also destroy
                   12302: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   12303: various errors in these words.
1.1       anton    12304: 
                   12305: @item insufficient space for loop control parameters:
                   12306: @cindex insufficient space for loop control parameters
1.80    ! anton    12307: Like other return stack overflows.
1.1       anton    12308: 
                   12309: @item insufficient space in the dictionary:
                   12310: @cindex insufficient space in the dictionary
                   12311: @cindex dictionary overflow
1.12      anton    12312: If you try to allot (either directly with @code{allot}, or indirectly
                   12313: with @code{,}, @code{create} etc.) more memory than available in the
                   12314: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   12315: to access memory beyond the end of the dictionary, the results are
                   12316: similar to stack overflows.
1.1       anton    12317: 
                   12318: @item interpreting a word with undefined interpretation semantics:
                   12319: @cindex interpreting a word with undefined interpretation semantics
                   12320: @cindex Interpreting a compile-only word
                   12321: For some words, we have defined interpretation semantics. For the
                   12322: others: @code{-14 throw} (Interpreting a compile-only word).
                   12323: 
                   12324: @item modifying the contents of the input buffer or a string literal:
                   12325: @cindex modifying the contents of the input buffer or a string literal
                   12326: These are located in writable memory and can be modified.
                   12327: 
                   12328: @item overflow of the pictured numeric output string:
                   12329: @cindex overflow of the pictured numeric output string
                   12330: @cindex pictured numeric output string, overflow
1.24      anton    12331: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    12332: 
                   12333: @item parsed string overflow:
                   12334: @cindex parsed string overflow
                   12335: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   12336: 
                   12337: @item producing a result out of range:
                   12338: @cindex result out of range
                   12339: On two's complement machines, arithmetic is performed modulo
                   12340: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   12341: arithmetic (with appropriate mapping for signed types). Division by zero
1.24      anton    12342: typically results in a @code{-10 throw} (divide by zero) or @code{-55
                   12343: throw} (floating point unidentified fault). @code{convert} and
                   12344: @code{>number} currently overflow silently.
1.1       anton    12345: 
                   12346: @item reading from an empty data or return stack:
                   12347: @cindex stack empty
                   12348: @cindex stack underflow
1.24      anton    12349: @cindex return stack underflow
1.1       anton    12350: The data stack is checked by the outer (aka text) interpreter after
                   12351: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   12352: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    12353: depending on operating system, installation, and invocation. If they are
                   12354: caught by a check, they typically result in @code{-4 throw} (Stack
                   12355: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   12356: (Invalid memory address), depending on the platform and which stack
                   12357: underflows and by how much. Note that even if the system uses checking
                   12358: (through the MMU), your program may have to underflow by a significant
                   12359: number of stack items to trigger the reaction (the reason for this is
                   12360: that the MMU, and therefore the checking, works with a page-size
                   12361: granularity).  If there is no checking, the symptoms resulting from an
                   12362: underflow are similar to those from an overflow.  Unbalanced return
1.80    ! anton    12363: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24      anton    12364: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   12365: throw}).
1.1       anton    12366: 
                   12367: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   12368: @cindex unexpected end of the input buffer
                   12369: @cindex zero-length string as a name
                   12370: @cindex Attempt to use zero-length string as a name
                   12371: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   12372: use zero-length string as a name). Words like @code{'} probably will not
                   12373: find what they search. Note that it is possible to create zero-length
                   12374: names with @code{nextname} (should it not?).
                   12375: 
                   12376: @item @code{>IN} greater than input buffer:
                   12377: @cindex @code{>IN} greater than input buffer
                   12378: The next invocation of a parsing word returns a string with length 0.
                   12379: 
                   12380: @item @code{RECURSE} appears after @code{DOES>}:
                   12381: @cindex @code{RECURSE} appears after @code{DOES>}
                   12382: Compiles a recursive call to the defining word, not to the defined word.
                   12383: 
                   12384: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   12385: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    12386: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    12387: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   12388: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   12389: the end of the file was reached), its source-id may be
                   12390: reused. Therefore, restoring an input source specification referencing a
                   12391: closed file may lead to unpredictable results instead of a @code{-12
                   12392: THROW}.
                   12393: 
                   12394: In the future, Gforth may be able to restore input source specifications
                   12395: from other than the current input source.
                   12396: 
                   12397: @item data space containing definitions gets de-allocated:
                   12398: @cindex data space containing definitions gets de-allocated
                   12399: Deallocation with @code{allot} is not checked. This typically results in
                   12400: memory access faults or execution of illegal instructions.
                   12401: 
                   12402: @item data space read/write with incorrect alignment:
                   12403: @cindex data space read/write with incorrect alignment
                   12404: @cindex alignment faults
1.26      crook    12405: @cindex address alignment exception
1.1       anton    12406: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    12407: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    12408: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   12409: (Invalid memory address). There are reportedly some processors with
1.12      anton    12410: alignment restrictions that do not report violations.
1.1       anton    12411: 
                   12412: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   12413: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   12414: Like other alignment errors.
                   12415: 
                   12416: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   12417: Like other stack underflows.
                   12418: 
                   12419: @item loop control parameters not available:
                   12420: @cindex loop control parameters not available
                   12421: Not checked. The counted loop words simply assume that the top of return
                   12422: stack items are loop control parameters and behave accordingly.
                   12423: 
                   12424: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   12425: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   12426: @cindex last word was headerless
                   12427: @code{abort" last word was headerless"}.
                   12428: 
                   12429: @item name not defined by @code{VALUE} used by @code{TO}:
                   12430: @cindex name not defined by @code{VALUE} used by @code{TO}
                   12431: @cindex @code{TO} on non-@code{VALUE}s
                   12432: @cindex Invalid name argument, @code{TO}
                   12433: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   12434: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   12435: 
                   12436: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   12437: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    12438: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    12439: @code{-13 throw} (Undefined word)
                   12440: 
                   12441: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   12442: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   12443: Gforth behaves as if they were of the same type. I.e., you can predict
                   12444: the behaviour by interpreting all parameters as, e.g., signed.
                   12445: 
                   12446: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   12447: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   12448: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   12449: compilation semantics of @code{TO}.
                   12450: 
                   12451: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    12452: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    12453: @cindex @code{WORD}, string overflow
                   12454: Not checked. The string will be ok, but the count will, of course,
                   12455: contain only the least significant bits of the length.
                   12456: 
                   12457: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   12458: @cindex @code{LSHIFT}, large shift counts
                   12459: @cindex @code{RSHIFT}, large shift counts
                   12460: Processor-dependent. Typical behaviours are returning 0 and using only
                   12461: the low bits of the shift count.
                   12462: 
                   12463: @item word not defined via @code{CREATE}:
                   12464: @cindex @code{>BODY} of non-@code{CREATE}d words
                   12465: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   12466: 
                   12467: @cindex @code{DOES>} of non-@code{CREATE}d words
                   12468: @code{DOES>} changes the execution semantics of the last defined word no
                   12469: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   12470: @code{CREATE , DOES>}.
                   12471: 
                   12472: @item words improperly used outside @code{<#} and @code{#>}:
                   12473: Not checked. As usual, you can expect memory faults.
                   12474: 
                   12475: @end table
                   12476: 
                   12477: 
                   12478: @c ---------------------------------------------------------------------
                   12479: @node core-other,  , core-ambcond, The Core Words
                   12480: @subsection Other system documentation
                   12481: @c ---------------------------------------------------------------------
                   12482: @cindex other system documentation, core words
                   12483: @cindex core words, other system documentation
                   12484: 
                   12485: @table @i
                   12486: @item nonstandard words using @code{PAD}:
                   12487: @cindex @code{PAD} use by nonstandard words
                   12488: None.
                   12489: 
                   12490: @item operator's terminal facilities available:
                   12491: @cindex operator's terminal facilities available
1.80    ! anton    12492: After processing the OS's command line, Gforth goes into interactive mode,
1.1       anton    12493: and you can give commands to Gforth interactively. The actual facilities
                   12494: available depend on how you invoke Gforth.
                   12495: 
                   12496: @item program data space available:
                   12497: @cindex program data space available
                   12498: @cindex data space available
                   12499: @code{UNUSED .} gives the remaining dictionary space. The total
                   12500: dictionary space can be specified with the @code{-m} switch
                   12501: (@pxref{Invoking Gforth}) when Gforth starts up.
                   12502: 
                   12503: @item return stack space available:
                   12504: @cindex return stack space available
                   12505: You can compute the total return stack space in cells with
                   12506: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   12507: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   12508: 
                   12509: @item stack space available:
                   12510: @cindex stack space available
                   12511: You can compute the total data stack space in cells with
                   12512: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   12513: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   12514: 
                   12515: @item system dictionary space required, in address units:
                   12516: @cindex system dictionary space required, in address units
                   12517: Type @code{here forthstart - .} after startup. At the time of this
                   12518: writing, this gives 80080 (bytes) on a 32-bit system.
                   12519: @end table
                   12520: 
                   12521: 
                   12522: @c =====================================================================
                   12523: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   12524: @section The optional Block word set
                   12525: @c =====================================================================
                   12526: @cindex system documentation, block words
                   12527: @cindex block words, system documentation
                   12528: 
                   12529: @menu
                   12530: * block-idef::                  Implementation Defined Options
                   12531: * block-ambcond::               Ambiguous Conditions               
                   12532: * block-other::                 Other System Documentation                 
                   12533: @end menu
                   12534: 
                   12535: 
                   12536: @c ---------------------------------------------------------------------
                   12537: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   12538: @subsection Implementation Defined Options
                   12539: @c ---------------------------------------------------------------------
                   12540: @cindex implementation-defined options, block words
                   12541: @cindex block words, implementation-defined options
                   12542: 
                   12543: @table @i
                   12544: @item the format for display by @code{LIST}:
                   12545: @cindex @code{LIST} display format
                   12546: First the screen number is displayed, then 16 lines of 64 characters,
                   12547: each line preceded by the line number.
                   12548: 
                   12549: @item the length of a line affected by @code{\}:
                   12550: @cindex length of a line affected by @code{\}
                   12551: @cindex @code{\}, line length in blocks
                   12552: 64 characters.
                   12553: @end table
                   12554: 
                   12555: 
                   12556: @c ---------------------------------------------------------------------
                   12557: @node block-ambcond, block-other, block-idef, The optional Block word set
                   12558: @subsection Ambiguous conditions
                   12559: @c ---------------------------------------------------------------------
                   12560: @cindex block words, ambiguous conditions
                   12561: @cindex ambiguous conditions, block words
                   12562: 
                   12563: @table @i
                   12564: @item correct block read was not possible:
                   12565: @cindex block read not possible
                   12566: Typically results in a @code{throw} of some OS-derived value (between
                   12567: -512 and -2048). If the blocks file was just not long enough, blanks are
                   12568: supplied for the missing portion.
                   12569: 
                   12570: @item I/O exception in block transfer:
                   12571: @cindex I/O exception in block transfer
                   12572: @cindex block transfer, I/O exception
                   12573: Typically results in a @code{throw} of some OS-derived value (between
                   12574: -512 and -2048).
                   12575: 
                   12576: @item invalid block number:
                   12577: @cindex invalid block number
                   12578: @cindex block number invalid
                   12579: @code{-35 throw} (Invalid block number)
                   12580: 
                   12581: @item a program directly alters the contents of @code{BLK}:
                   12582: @cindex @code{BLK}, altering @code{BLK}
                   12583: The input stream is switched to that other block, at the same
                   12584: position. If the storing to @code{BLK} happens when interpreting
                   12585: non-block input, the system will get quite confused when the block ends.
                   12586: 
                   12587: @item no current block buffer for @code{UPDATE}:
                   12588: @cindex @code{UPDATE}, no current block buffer
                   12589: @code{UPDATE} has no effect.
                   12590: 
                   12591: @end table
                   12592: 
                   12593: @c ---------------------------------------------------------------------
                   12594: @node block-other,  , block-ambcond, The optional Block word set
                   12595: @subsection Other system documentation
                   12596: @c ---------------------------------------------------------------------
                   12597: @cindex other system documentation, block words
                   12598: @cindex block words, other system documentation
                   12599: 
                   12600: @table @i
                   12601: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   12602: No restrictions (yet).
                   12603: 
                   12604: @item the number of blocks available for source and data:
                   12605: depends on your disk space.
                   12606: 
                   12607: @end table
                   12608: 
                   12609: 
                   12610: @c =====================================================================
                   12611: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   12612: @section The optional Double Number word set
                   12613: @c =====================================================================
                   12614: @cindex system documentation, double words
                   12615: @cindex double words, system documentation
                   12616: 
                   12617: @menu
                   12618: * double-ambcond::              Ambiguous Conditions              
                   12619: @end menu
                   12620: 
                   12621: 
                   12622: @c ---------------------------------------------------------------------
                   12623: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   12624: @subsection Ambiguous conditions
                   12625: @c ---------------------------------------------------------------------
                   12626: @cindex double words, ambiguous conditions
                   12627: @cindex ambiguous conditions, double words
                   12628: 
                   12629: @table @i
1.29      crook    12630: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   12631: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   12632: The least significant cell of @i{d} is produced.
1.1       anton    12633: 
                   12634: @end table
                   12635: 
                   12636: 
                   12637: @c =====================================================================
                   12638: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   12639: @section The optional Exception word set
                   12640: @c =====================================================================
                   12641: @cindex system documentation, exception words
                   12642: @cindex exception words, system documentation
                   12643: 
                   12644: @menu
                   12645: * exception-idef::              Implementation Defined Options              
                   12646: @end menu
                   12647: 
                   12648: 
                   12649: @c ---------------------------------------------------------------------
                   12650: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   12651: @subsection Implementation Defined Options
                   12652: @c ---------------------------------------------------------------------
                   12653: @cindex implementation-defined options, exception words
                   12654: @cindex exception words, implementation-defined options
                   12655: 
                   12656: @table @i
                   12657: @item @code{THROW}-codes used in the system:
                   12658: @cindex @code{THROW}-codes used in the system
                   12659: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    12660: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    12661: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   12662: allocation operations). The mapping from OS error numbers to throw codes
                   12663: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   12664: undefined OS errors produce a message with a strange number; e.g.,
                   12665: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   12666: @end table
                   12667: 
                   12668: @c =====================================================================
                   12669: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   12670: @section The optional Facility word set
                   12671: @c =====================================================================
                   12672: @cindex system documentation, facility words
                   12673: @cindex facility words, system documentation
                   12674: 
                   12675: @menu
                   12676: * facility-idef::               Implementation Defined Options               
                   12677: * facility-ambcond::            Ambiguous Conditions            
                   12678: @end menu
                   12679: 
                   12680: 
                   12681: @c ---------------------------------------------------------------------
                   12682: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   12683: @subsection Implementation Defined Options
                   12684: @c ---------------------------------------------------------------------
                   12685: @cindex implementation-defined options, facility words
                   12686: @cindex facility words, implementation-defined options
                   12687: 
                   12688: @table @i
                   12689: @item encoding of keyboard events (@code{EKEY}):
                   12690: @cindex keyboard events, encoding in @code{EKEY}
                   12691: @cindex @code{EKEY}, encoding of keyboard events
1.40      anton    12692: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41      anton    12693: Other keys are encoded with the constants @code{k-left}, @code{k-right},
                   12694: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
                   12695: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
                   12696: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40      anton    12697: 
1.1       anton    12698: 
                   12699: @item duration of a system clock tick:
                   12700: @cindex duration of a system clock tick
                   12701: @cindex clock tick duration
                   12702: System dependent. With respect to @code{MS}, the time is specified in
                   12703: microseconds. How well the OS and the hardware implement this, is
                   12704: another question.
                   12705: 
                   12706: @item repeatability to be expected from the execution of @code{MS}:
                   12707: @cindex repeatability to be expected from the execution of @code{MS}
                   12708: @cindex @code{MS}, repeatability to be expected
                   12709: System dependent. On Unix, a lot depends on load. If the system is
                   12710: lightly loaded, and the delay is short enough that Gforth does not get
                   12711: swapped out, the performance should be acceptable. Under MS-DOS and
                   12712: other single-tasking systems, it should be good.
                   12713: 
                   12714: @end table
                   12715: 
                   12716: 
                   12717: @c ---------------------------------------------------------------------
                   12718: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   12719: @subsection Ambiguous conditions
                   12720: @c ---------------------------------------------------------------------
                   12721: @cindex facility words, ambiguous conditions
                   12722: @cindex ambiguous conditions, facility words
                   12723: 
                   12724: @table @i
                   12725: @item @code{AT-XY} can't be performed on user output device:
                   12726: @cindex @code{AT-XY} can't be performed on user output device
                   12727: Largely terminal dependent. No range checks are done on the arguments.
                   12728: No errors are reported. You may see some garbage appearing, you may see
                   12729: simply nothing happen.
                   12730: 
                   12731: @end table
                   12732: 
                   12733: 
                   12734: @c =====================================================================
                   12735: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   12736: @section The optional File-Access word set
                   12737: @c =====================================================================
                   12738: @cindex system documentation, file words
                   12739: @cindex file words, system documentation
                   12740: 
                   12741: @menu
                   12742: * file-idef::                   Implementation Defined Options
                   12743: * file-ambcond::                Ambiguous Conditions                
                   12744: @end menu
                   12745: 
                   12746: @c ---------------------------------------------------------------------
                   12747: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   12748: @subsection Implementation Defined Options
                   12749: @c ---------------------------------------------------------------------
                   12750: @cindex implementation-defined options, file words
                   12751: @cindex file words, implementation-defined options
                   12752: 
                   12753: @table @i
                   12754: @item file access methods used:
                   12755: @cindex file access methods used
                   12756: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   12757: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   12758: @code{wb}): The file is cleared, if it exists, and created, if it does
                   12759: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   12760: @code{create-file} creates a file with 666 permissions modified by your
                   12761: umask.
                   12762: 
                   12763: @item file exceptions:
                   12764: @cindex file exceptions
                   12765: The file words do not raise exceptions (except, perhaps, memory access
                   12766: faults when you pass illegal addresses or file-ids).
                   12767: 
                   12768: @item file line terminator:
                   12769: @cindex file line terminator
                   12770: System-dependent. Gforth uses C's newline character as line
                   12771: terminator. What the actual character code(s) of this are is
                   12772: system-dependent.
                   12773: 
                   12774: @item file name format:
                   12775: @cindex file name format
                   12776: System dependent. Gforth just uses the file name format of your OS.
                   12777: 
                   12778: @item information returned by @code{FILE-STATUS}:
                   12779: @cindex @code{FILE-STATUS}, returned information
                   12780: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   12781: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   12782: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   12783: along with the returned mode.
                   12784: 
                   12785: @item input file state after an exception when including source:
                   12786: @cindex exception when including source
                   12787: All files that are left via the exception are closed.
                   12788: 
1.29      crook    12789: @item @i{ior} values and meaning:
                   12790: @cindex @i{ior} values and meaning
1.68      anton    12791: @cindex @i{wior} values and meaning
1.29      crook    12792: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    12793: intended as throw codes. They typically are in the range
                   12794: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    12795: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    12796: 
                   12797: @item maximum depth of file input nesting:
                   12798: @cindex maximum depth of file input nesting
                   12799: @cindex file input nesting, maximum depth
                   12800: limited by the amount of return stack, locals/TIB stack, and the number
                   12801: of open files available. This should not give you troubles.
                   12802: 
                   12803: @item maximum size of input line:
                   12804: @cindex maximum size of input line
                   12805: @cindex input line size, maximum
                   12806: @code{/line}. Currently 255.
                   12807: 
                   12808: @item methods of mapping block ranges to files:
                   12809: @cindex mapping block ranges to files
                   12810: @cindex files containing blocks
                   12811: @cindex blocks in files
                   12812: By default, blocks are accessed in the file @file{blocks.fb} in the
                   12813: current working directory. The file can be switched with @code{USE}.
                   12814: 
                   12815: @item number of string buffers provided by @code{S"}:
                   12816: @cindex @code{S"}, number of string buffers
                   12817: 1
                   12818: 
                   12819: @item size of string buffer used by @code{S"}:
                   12820: @cindex @code{S"}, size of string buffer
                   12821: @code{/line}. currently 255.
                   12822: 
                   12823: @end table
                   12824: 
                   12825: @c ---------------------------------------------------------------------
                   12826: @node file-ambcond,  , file-idef, The optional File-Access word set
                   12827: @subsection Ambiguous conditions
                   12828: @c ---------------------------------------------------------------------
                   12829: @cindex file words, ambiguous conditions
                   12830: @cindex ambiguous conditions, file words
                   12831: 
                   12832: @table @i
                   12833: @item attempting to position a file outside its boundaries:
                   12834: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   12835: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   12836: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   12837: 
                   12838: @item attempting to read from file positions not yet written:
                   12839: @cindex reading from file positions not yet written
                   12840: End-of-file, i.e., zero characters are read and no error is reported.
                   12841: 
1.29      crook    12842: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   12843: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    12844: An appropriate exception may be thrown, but a memory fault or other
                   12845: problem is more probable.
                   12846: 
1.29      crook    12847: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   12848: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   12849: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   12850: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    12851: thrown.
                   12852: 
                   12853: @item named file cannot be opened (@code{INCLUDED}):
                   12854: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    12855: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    12856: 
                   12857: @item requesting an unmapped block number:
                   12858: @cindex unmapped block numbers
                   12859: There are no unmapped legal block numbers. On some operating systems,
                   12860: writing a block with a large number may overflow the file system and
                   12861: have an error message as consequence.
                   12862: 
                   12863: @item using @code{source-id} when @code{blk} is non-zero:
                   12864: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   12865: @code{source-id} performs its function. Typically it will give the id of
                   12866: the source which loaded the block. (Better ideas?)
                   12867: 
                   12868: @end table
                   12869: 
                   12870: 
                   12871: @c =====================================================================
                   12872: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   12873: @section The optional Floating-Point word set
                   12874: @c =====================================================================
                   12875: @cindex system documentation, floating-point words
                   12876: @cindex floating-point words, system documentation
                   12877: 
                   12878: @menu
                   12879: * floating-idef::               Implementation Defined Options
                   12880: * floating-ambcond::            Ambiguous Conditions            
                   12881: @end menu
                   12882: 
                   12883: 
                   12884: @c ---------------------------------------------------------------------
                   12885: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   12886: @subsection Implementation Defined Options
                   12887: @c ---------------------------------------------------------------------
                   12888: @cindex implementation-defined options, floating-point words
                   12889: @cindex floating-point words, implementation-defined options
                   12890: 
                   12891: @table @i
                   12892: @item format and range of floating point numbers:
                   12893: @cindex format and range of floating point numbers
                   12894: @cindex floating point numbers, format and range
                   12895: System-dependent; the @code{double} type of C.
                   12896: 
1.29      crook    12897: @item results of @code{REPRESENT} when @i{float} is out of range:
                   12898: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    12899: System dependent; @code{REPRESENT} is implemented using the C library
                   12900: function @code{ecvt()} and inherits its behaviour in this respect.
                   12901: 
                   12902: @item rounding or truncation of floating-point numbers:
                   12903: @cindex rounding of floating-point numbers
                   12904: @cindex truncation of floating-point numbers
                   12905: @cindex floating-point numbers, rounding or truncation
                   12906: System dependent; the rounding behaviour is inherited from the hosting C
                   12907: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   12908: nearest, and break ties by rounding to even (i.e., such that the last
                   12909: bit of the mantissa is 0).
                   12910: 
                   12911: @item size of floating-point stack:
                   12912: @cindex floating-point stack size
                   12913: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   12914: the floating-point stack (in floats). You can specify this on startup
                   12915: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   12916: 
                   12917: @item width of floating-point stack:
                   12918: @cindex floating-point stack width 
                   12919: @code{1 floats}.
                   12920: 
                   12921: @end table
                   12922: 
                   12923: 
                   12924: @c ---------------------------------------------------------------------
                   12925: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   12926: @subsection Ambiguous conditions
                   12927: @c ---------------------------------------------------------------------
                   12928: @cindex floating-point words, ambiguous conditions
                   12929: @cindex ambiguous conditions, floating-point words
                   12930: 
                   12931: @table @i
                   12932: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   12933: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   12934: System-dependent. Typically results in a @code{-23 THROW} like other
                   12935: alignment violations.
                   12936: 
                   12937: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   12938: @cindex @code{f@@} used with an address that is not float aligned
                   12939: @cindex @code{f!} used with an address that is not float aligned
                   12940: System-dependent. Typically results in a @code{-23 THROW} like other
                   12941: alignment violations.
                   12942: 
                   12943: @item floating-point result out of range:
                   12944: @cindex floating-point result out of range
1.80    ! anton    12945: System-dependent. Can result in a @code{-43 throw} (floating point
        !          12946: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
        !          12947: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1       anton    12948: unidentified fault), or can produce a special value representing, e.g.,
                   12949: Infinity.
                   12950: 
                   12951: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   12952: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   12953: System-dependent. Typically results in an alignment fault like other
                   12954: alignment violations.
                   12955: 
1.35      anton    12956: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   12957: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    12958: The floating-point number is converted into decimal nonetheless.
                   12959: 
                   12960: @item Both arguments are equal to zero (@code{FATAN2}):
                   12961: @cindex @code{FATAN2}, both arguments are equal to zero
                   12962: System-dependent. @code{FATAN2} is implemented using the C library
                   12963: function @code{atan2()}.
                   12964: 
1.29      crook    12965: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   12966: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   12967: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    12968: because of small errors and the tan will be a very large (or very small)
                   12969: but finite number.
                   12970: 
1.29      crook    12971: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   12972: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    12973: The result is rounded to the nearest float.
                   12974: 
                   12975: @item dividing by zero:
                   12976: @cindex dividing by zero, floating-point
                   12977: @cindex floating-point dividing by zero
                   12978: @cindex floating-point unidentified fault, FP divide-by-zero
1.80    ! anton    12979: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
        !          12980: (floating point divide by zero) or @code{-55 throw} (Floating-point
        !          12981: unidentified fault).
1.1       anton    12982: 
                   12983: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   12984: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   12985: System dependent. On IEEE-FP based systems the number is converted into
                   12986: an infinity.
                   12987: 
1.29      crook    12988: @item @i{float}<1 (@code{FACOSH}):
                   12989: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    12990: @cindex floating-point unidentified fault, @code{FACOSH}
1.80    ! anton    12991: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1       anton    12992: 
1.29      crook    12993: @item @i{float}=<-1 (@code{FLNP1}):
                   12994: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    12995: @cindex floating-point unidentified fault, @code{FLNP1}
1.80    ! anton    12996: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
        !          12997: negative infinity for @i{float}=-1).
1.1       anton    12998: 
1.29      crook    12999: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   13000: @cindex @code{FLN}, @i{float}=<0
                   13001: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    13002: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80    ! anton    13003: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
        !          13004: negative infinity for @i{float}=0).
1.1       anton    13005: 
1.29      crook    13006: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   13007: @cindex @code{FASINH}, @i{float}<0
                   13008: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    13009: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80    ! anton    13010: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
        !          13011: @code{fasinh} some platforms produce a NaN, others a number (bug in the
        !          13012: C library?).
1.1       anton    13013: 
1.29      crook    13014: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   13015: @cindex @code{FACOS}, |@i{float}|>1
                   13016: @cindex @code{FASIN}, |@i{float}|>1
                   13017: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    13018: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80    ! anton    13019: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1       anton    13020: 
1.29      crook    13021: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   13022: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    13023: @cindex floating-point unidentified fault, @code{F>D}
1.80    ! anton    13024: Platform-dependent; typically, some double number is produced and no
        !          13025: error is reported.
1.1       anton    13026: 
                   13027: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   13028: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80    ! anton    13029: @code{Precision} characters of the numeric output area are used.  If
        !          13030: @code{precision} is too high, these words will smash the data or code
        !          13031: close to @code{here}.
1.1       anton    13032: @end table
                   13033: 
                   13034: @c =====================================================================
                   13035: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   13036: @section The optional Locals word set
                   13037: @c =====================================================================
                   13038: @cindex system documentation, locals words
                   13039: @cindex locals words, system documentation
                   13040: 
                   13041: @menu
                   13042: * locals-idef::                 Implementation Defined Options                 
                   13043: * locals-ambcond::              Ambiguous Conditions              
                   13044: @end menu
                   13045: 
                   13046: 
                   13047: @c ---------------------------------------------------------------------
                   13048: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   13049: @subsection Implementation Defined Options
                   13050: @c ---------------------------------------------------------------------
                   13051: @cindex implementation-defined options, locals words
                   13052: @cindex locals words, implementation-defined options
                   13053: 
                   13054: @table @i
                   13055: @item maximum number of locals in a definition:
                   13056: @cindex maximum number of locals in a definition
                   13057: @cindex locals, maximum number in a definition
                   13058: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   13059: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   13060: characters. The number of locals in a definition is bounded by the size
                   13061: of locals-buffer, which contains the names of the locals.
                   13062: 
                   13063: @end table
                   13064: 
                   13065: 
                   13066: @c ---------------------------------------------------------------------
                   13067: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   13068: @subsection Ambiguous conditions
                   13069: @c ---------------------------------------------------------------------
                   13070: @cindex locals words, ambiguous conditions
                   13071: @cindex ambiguous conditions, locals words
                   13072: 
                   13073: @table @i
                   13074: @item executing a named local in interpretation state:
                   13075: @cindex local in interpretation state
                   13076: @cindex Interpreting a compile-only word, for a local
                   13077: Locals have no interpretation semantics. If you try to perform the
                   13078: interpretation semantics, you will get a @code{-14 throw} somewhere
                   13079: (Interpreting a compile-only word). If you perform the compilation
                   13080: semantics, the locals access will be compiled (irrespective of state).
                   13081: 
1.29      crook    13082: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    13083: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   13084: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   13085: @cindex Invalid name argument, @code{TO}
                   13086: @code{-32 throw} (Invalid name argument)
                   13087: 
                   13088: @end table
                   13089: 
                   13090: 
                   13091: @c =====================================================================
                   13092: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   13093: @section The optional Memory-Allocation word set
                   13094: @c =====================================================================
                   13095: @cindex system documentation, memory-allocation words
                   13096: @cindex memory-allocation words, system documentation
                   13097: 
                   13098: @menu
                   13099: * memory-idef::                 Implementation Defined Options                 
                   13100: @end menu
                   13101: 
                   13102: 
                   13103: @c ---------------------------------------------------------------------
                   13104: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   13105: @subsection Implementation Defined Options
                   13106: @c ---------------------------------------------------------------------
                   13107: @cindex implementation-defined options, memory-allocation words
                   13108: @cindex memory-allocation words, implementation-defined options
                   13109: 
                   13110: @table @i
1.29      crook    13111: @item values and meaning of @i{ior}:
                   13112: @cindex  @i{ior} values and meaning
                   13113: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    13114: intended as throw codes. They typically are in the range
                   13115: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    13116: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    13117: 
                   13118: @end table
                   13119: 
                   13120: @c =====================================================================
                   13121: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   13122: @section The optional Programming-Tools word set
                   13123: @c =====================================================================
                   13124: @cindex system documentation, programming-tools words
                   13125: @cindex programming-tools words, system documentation
                   13126: 
                   13127: @menu
                   13128: * programming-idef::            Implementation Defined Options            
                   13129: * programming-ambcond::         Ambiguous Conditions         
                   13130: @end menu
                   13131: 
                   13132: 
                   13133: @c ---------------------------------------------------------------------
                   13134: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   13135: @subsection Implementation Defined Options
                   13136: @c ---------------------------------------------------------------------
                   13137: @cindex implementation-defined options, programming-tools words
                   13138: @cindex programming-tools words, implementation-defined options
                   13139: 
                   13140: @table @i
                   13141: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   13142: @cindex @code{;CODE} ending sequence
                   13143: @cindex @code{CODE} ending sequence
                   13144: @code{END-CODE}
                   13145: 
                   13146: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   13147: @cindex @code{;CODE}, processing input
                   13148: @cindex @code{CODE}, processing input
                   13149: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   13150: the input is processed by the text interpreter, (starting) in interpret
                   13151: state.
                   13152: 
                   13153: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   13154: @cindex @code{ASSEMBLER}, search order capability
                   13155: The ANS Forth search order word set.
                   13156: 
                   13157: @item source and format of display by @code{SEE}:
                   13158: @cindex @code{SEE}, source and format of output
1.80    ! anton    13159: The source for @code{see} is the executable code used by the inner
1.1       anton    13160: interpreter.  The current @code{see} tries to output Forth source code
1.80    ! anton    13161: (and on some platforms, assembly code for primitives) as well as
        !          13162: possible.
1.1       anton    13163: 
                   13164: @end table
                   13165: 
                   13166: @c ---------------------------------------------------------------------
                   13167: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   13168: @subsection Ambiguous conditions
                   13169: @c ---------------------------------------------------------------------
                   13170: @cindex programming-tools words, ambiguous conditions
                   13171: @cindex ambiguous conditions, programming-tools words
                   13172: 
                   13173: @table @i
                   13174: 
1.21      crook    13175: @item deleting the compilation word list (@code{FORGET}):
                   13176: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    13177: Not implemented (yet).
                   13178: 
1.29      crook    13179: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   13180: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   13181: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    13182: @cindex control-flow stack underflow
                   13183: This typically results in an @code{abort"} with a descriptive error
                   13184: message (may change into a @code{-22 throw} (Control structure mismatch)
                   13185: in the future). You may also get a memory access error. If you are
                   13186: unlucky, this ambiguous condition is not caught.
                   13187: 
1.29      crook    13188: @item @i{name} can't be found (@code{FORGET}):
                   13189: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    13190: Not implemented (yet).
                   13191: 
1.29      crook    13192: @item @i{name} not defined via @code{CREATE}:
                   13193: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    13194: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   13195: the execution semantics of the last defined word no matter how it was
                   13196: defined.
                   13197: 
                   13198: @item @code{POSTPONE} applied to @code{[IF]}:
                   13199: @cindex @code{POSTPONE} applied to @code{[IF]}
                   13200: @cindex @code{[IF]} and @code{POSTPONE}
                   13201: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   13202: equivalent to @code{[IF]}.
                   13203: 
                   13204: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   13205: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   13206: Continue in the same state of conditional compilation in the next outer
                   13207: input source. Currently there is no warning to the user about this.
                   13208: 
                   13209: @item removing a needed definition (@code{FORGET}):
                   13210: @cindex @code{FORGET}, removing a needed definition
                   13211: Not implemented (yet).
                   13212: 
                   13213: @end table
                   13214: 
                   13215: 
                   13216: @c =====================================================================
                   13217: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   13218: @section The optional Search-Order word set
                   13219: @c =====================================================================
                   13220: @cindex system documentation, search-order words
                   13221: @cindex search-order words, system documentation
                   13222: 
                   13223: @menu
                   13224: * search-idef::                 Implementation Defined Options                 
                   13225: * search-ambcond::              Ambiguous Conditions              
                   13226: @end menu
                   13227: 
                   13228: 
                   13229: @c ---------------------------------------------------------------------
                   13230: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   13231: @subsection Implementation Defined Options
                   13232: @c ---------------------------------------------------------------------
                   13233: @cindex implementation-defined options, search-order words
                   13234: @cindex search-order words, implementation-defined options
                   13235: 
                   13236: @table @i
                   13237: @item maximum number of word lists in search order:
                   13238: @cindex maximum number of word lists in search order
                   13239: @cindex search order, maximum depth
                   13240: @code{s" wordlists" environment? drop .}. Currently 16.
                   13241: 
                   13242: @item minimum search order:
                   13243: @cindex minimum search order
                   13244: @cindex search order, minimum
                   13245: @code{root root}.
                   13246: 
                   13247: @end table
                   13248: 
                   13249: @c ---------------------------------------------------------------------
                   13250: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   13251: @subsection Ambiguous conditions
                   13252: @c ---------------------------------------------------------------------
                   13253: @cindex search-order words, ambiguous conditions
                   13254: @cindex ambiguous conditions, search-order words
                   13255: 
                   13256: @table @i
1.21      crook    13257: @item changing the compilation word list (during compilation):
                   13258: @cindex changing the compilation word list (during compilation)
                   13259: @cindex compilation word list, change before definition ends
                   13260: The word is entered into the word list that was the compilation word list
1.1       anton    13261: at the start of the definition. Any changes to the name field (e.g.,
                   13262: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
                   13263: are applied to the latest defined word (as reported by @code{last} or
1.21      crook    13264: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1       anton    13265: 
                   13266: @item search order empty (@code{previous}):
                   13267: @cindex @code{previous}, search order empty
1.26      crook    13268: @cindex vocstack empty, @code{previous}
1.1       anton    13269: @code{abort" Vocstack empty"}.
                   13270: 
                   13271: @item too many word lists in search order (@code{also}):
                   13272: @cindex @code{also}, too many word lists in search order
1.26      crook    13273: @cindex vocstack full, @code{also}
1.1       anton    13274: @code{abort" Vocstack full"}.
                   13275: 
                   13276: @end table
                   13277: 
                   13278: @c ***************************************************************
1.65      anton    13279: @node Standard vs Extensions, Model, ANS conformance, Top
                   13280: @chapter Should I use Gforth extensions?
                   13281: @cindex Gforth extensions
                   13282: 
                   13283: As you read through the rest of this manual, you will see documentation
                   13284: for @i{Standard} words, and documentation for some appealing Gforth
                   13285: @i{extensions}. You might ask yourself the question: @i{``Should I
                   13286: restrict myself to the standard, or should I use the extensions?''}
                   13287: 
                   13288: The answer depends on the goals you have for the program you are working
                   13289: on:
                   13290: 
                   13291: @itemize @bullet
                   13292: 
                   13293: @item Is it just for yourself or do you want to share it with others?
                   13294: 
                   13295: @item
                   13296: If you want to share it, do the others all use Gforth?
                   13297: 
                   13298: @item
                   13299: If it is just for yourself, do you want to restrict yourself to Gforth?
                   13300: 
                   13301: @end itemize
                   13302: 
                   13303: If restricting the program to Gforth is ok, then there is no reason not
                   13304: to use extensions.  It is still a good idea to keep to the standard
                   13305: where it is easy, in case you want to reuse these parts in another
                   13306: program that you want to be portable.
                   13307: 
                   13308: If you want to be able to port the program to other Forth systems, there
                   13309: are the following points to consider:
                   13310: 
                   13311: @itemize @bullet
                   13312: 
                   13313: @item
                   13314: Most Forth systems that are being maintained support the ANS Forth
                   13315: standard.  So if your program complies with the standard, it will be
                   13316: portable among many systems.
                   13317: 
                   13318: @item
                   13319: A number of the Gforth extensions can be implemented in ANS Forth using
                   13320: public-domain files provided in the @file{compat/} directory. These are
                   13321: mentioned in the text in passing.  There is no reason not to use these
                   13322: extensions, your program will still be ANS Forth compliant; just include
                   13323: the appropriate compat files with your program.
                   13324: 
                   13325: @item
                   13326: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                   13327: analyse your program and determine what non-Standard words it relies
                   13328: upon.  However, it does not check whether you use standard words in a
                   13329: non-standard way.
                   13330: 
                   13331: @item
                   13332: Some techniques are not standardized by ANS Forth, and are hard or
                   13333: impossible to implement in a standard way, but can be implemented in
                   13334: most Forth systems easily, and usually in similar ways (e.g., accessing
                   13335: word headers).  Forth has a rich historical precedent for programmers
                   13336: taking advantage of implementation-dependent features of their tools
                   13337: (for example, relying on a knowledge of the dictionary
                   13338: structure). Sometimes these techniques are necessary to extract every
                   13339: last bit of performance from the hardware, sometimes they are just a
                   13340: programming shorthand.
                   13341: 
                   13342: @item
                   13343: Does using a Gforth extension save more work than the porting this part
                   13344: to other Forth systems (if any) will cost?
                   13345: 
                   13346: @item
                   13347: Is the additional functionality worth the reduction in portability and
                   13348: the additional porting problems?
                   13349: 
                   13350: @end itemize
                   13351: 
                   13352: In order to perform these consideratios, you need to know what's
                   13353: standard and what's not.  This manual generally states if something is
                   13354: non-standard, but the authoritative source is the standard document.
                   13355: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
                   13356: into the thought processes of the technical committee.
                   13357: 
                   13358: Note also that portability between Forth systems is not the only
                   13359: portability issue; there is also the issue of portability between
                   13360: different platforms (processor/OS combinations).
                   13361: 
                   13362: @c ***************************************************************
                   13363: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1       anton    13364: @chapter Model
                   13365: 
                   13366: This chapter has yet to be written. It will contain information, on
                   13367: which internal structures you can rely.
                   13368: 
                   13369: @c ***************************************************************
                   13370: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   13371: @chapter Integrating Gforth into C programs
                   13372: 
                   13373: This is not yet implemented.
                   13374: 
                   13375: Several people like to use Forth as scripting language for applications
                   13376: that are otherwise written in C, C++, or some other language.
                   13377: 
                   13378: The Forth system ATLAST provides facilities for embedding it into
                   13379: applications; unfortunately it has several disadvantages: most
                   13380: importantly, it is not based on ANS Forth, and it is apparently dead
                   13381: (i.e., not developed further and not supported). The facilities
1.21      crook    13382: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    13383: making the switch should not be hard.
                   13384: 
                   13385: We also tried to design the interface such that it can easily be
                   13386: implemented by other Forth systems, so that we may one day arrive at a
                   13387: standardized interface. Such a standard interface would allow you to
                   13388: replace the Forth system without having to rewrite C code.
                   13389: 
                   13390: You embed the Gforth interpreter by linking with the library
                   13391: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   13392: global symbols in this library that belong to the interface, have the
                   13393: prefix @code{forth_}. (Global symbols that are used internally have the
                   13394: prefix @code{gforth_}).
                   13395: 
                   13396: You can include the declarations of Forth types and the functions and
                   13397: variables of the interface with @code{#include <forth.h>}.
                   13398: 
                   13399: Types.
                   13400: 
                   13401: Variables.
                   13402: 
                   13403: Data and FP Stack pointer. Area sizes.
                   13404: 
                   13405: functions.
                   13406: 
                   13407: forth_init(imagefile)
                   13408: forth_evaluate(string) exceptions?
                   13409: forth_goto(address) (or forth_execute(xt)?)
                   13410: forth_continue() (a corountining mechanism)
                   13411: 
                   13412: Adding primitives.
                   13413: 
                   13414: No checking.
                   13415: 
                   13416: Signals?
                   13417: 
                   13418: Accessing the Stacks
                   13419: 
1.26      crook    13420: @c ******************************************************************
1.1       anton    13421: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   13422: @chapter Emacs and Gforth
                   13423: @cindex Emacs and Gforth
                   13424: 
                   13425: @cindex @file{gforth.el}
                   13426: @cindex @file{forth.el}
                   13427: @cindex Rydqvist, Goran
                   13428: @cindex comment editing commands
                   13429: @cindex @code{\}, editing with Emacs
                   13430: @cindex debug tracer editing commands
                   13431: @cindex @code{~~}, removal with Emacs
                   13432: @cindex Forth mode in Emacs
                   13433: Gforth comes with @file{gforth.el}, an improved version of
                   13434: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    13435: improvements are:
                   13436: 
                   13437: @itemize @bullet
                   13438: @item
                   13439: A better (but still not perfect) handling of indentation.
                   13440: @item
                   13441: Comment paragraph filling (@kbd{M-q})
                   13442: @item
                   13443: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   13444: @item
                   13445: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41      anton    13446: @item
                   13447: Support of the @code{info-lookup} feature for looking up the
                   13448: documentation of a word.
1.26      crook    13449: @end itemize
                   13450: 
                   13451: I left the stuff I do not use alone, even though some of it only makes
                   13452: sense for TILE. To get a description of these features, enter Forth mode
                   13453: and type @kbd{C-h m}.
1.1       anton    13454: 
                   13455: @cindex source location of error or debugging output in Emacs
                   13456: @cindex error output, finding the source location in Emacs
                   13457: @cindex debugging output, finding the source location in Emacs
                   13458: In addition, Gforth supports Emacs quite well: The source code locations
                   13459: given in error messages, debugging output (from @code{~~}) and failed
                   13460: assertion messages are in the right format for Emacs' compilation mode
                   13461: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   13462: Manual}) so the source location corresponding to an error or other
                   13463: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   13464: @kbd{C-c C-c} for the error under the cursor).
                   13465: 
                   13466: @cindex @file{TAGS} file
                   13467: @cindex @file{etags.fs}
                   13468: @cindex viewing the source of a word in Emacs
1.43      anton    13469: @cindex @code{require}, placement in files
                   13470: @cindex @code{include}, placement in files
                   13471: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
1.26      crook    13472: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    13473: contains the definitions of all words defined afterwards. You can then
                   13474: find the source for a word using @kbd{M-.}. Note that emacs can use
                   13475: several tags files at the same time (e.g., one for the Gforth sources
                   13476: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   13477: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   13478: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43      anton    13479: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
                   13480: with @file{etags.fs}, you should avoid putting definitions both before
                   13481: and after @code{require} etc., otherwise you will see the same file
                   13482: visited several times by commands like @code{tags-search}.
1.1       anton    13483: 
1.41      anton    13484: @cindex viewing the documentation of a word in Emacs
                   13485: @cindex context-sensitive help
                   13486: Moreover, for words documented in this manual, you can look up the
                   13487: glossary entry quickly by using @kbd{C-h TAB}
1.80    ! anton    13488: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
1.41      anton    13489: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
1.42      anton    13490: later and does not work for words containing @code{:}.
1.41      anton    13491: 
                   13492: 
1.1       anton    13493: @cindex @file{.emacs}
                   13494: To get all these benefits, add the following lines to your @file{.emacs}
                   13495: file:
                   13496: 
                   13497: @example
                   13498: (autoload 'forth-mode "gforth.el")
                   13499: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
                   13500: @end example
                   13501: 
1.26      crook    13502: @c ******************************************************************
1.1       anton    13503: @node Image Files, Engine, Emacs and Gforth, Top
                   13504: @chapter Image Files
1.26      crook    13505: @cindex image file
                   13506: @cindex @file{.fi} files
1.1       anton    13507: @cindex precompiled Forth code
                   13508: @cindex dictionary in persistent form
                   13509: @cindex persistent form of dictionary
                   13510: 
                   13511: An image file is a file containing an image of the Forth dictionary,
                   13512: i.e., compiled Forth code and data residing in the dictionary.  By
                   13513: convention, we use the extension @code{.fi} for image files.
                   13514: 
                   13515: @menu
1.18      anton    13516: * Image Licensing Issues::      Distribution terms for images.
                   13517: * Image File Background::       Why have image files?
1.67      anton    13518: * Non-Relocatable Image Files::  don't always work.
1.18      anton    13519: * Data-Relocatable Image Files::  are better.
1.67      anton    13520: * Fully Relocatable Image Files::  better yet.
1.18      anton    13521: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    13522: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    13523: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    13524: @end menu
                   13525: 
1.18      anton    13526: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   13527: @section Image Licensing Issues
                   13528: @cindex license for images
                   13529: @cindex image license
                   13530: 
                   13531: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   13532: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   13533: original image; i.e., according to copyright law it is a derived work of
                   13534: the original image.
                   13535: 
                   13536: Since Gforth is distributed under the GNU GPL, the newly created image
                   13537: falls under the GNU GPL, too. In particular, this means that if you
                   13538: distribute the image, you have to make all of the sources for the image
                   13539: available, including those you wrote.  For details see @ref{License, ,
                   13540: GNU General Public License (Section 3)}.
                   13541: 
                   13542: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   13543: contains only code compiled from the sources you gave it; if none of
                   13544: these sources is under the GPL, the terms discussed above do not apply
                   13545: to the image. However, if your image needs an engine (a gforth binary)
                   13546: that is under the GPL, you should make sure that you distribute both in
                   13547: a way that is at most a @emph{mere aggregation}, if you don't want the
                   13548: terms of the GPL to apply to the image.
                   13549: 
                   13550: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    13551: @section Image File Background
                   13552: @cindex image file background
                   13553: 
1.80    ! anton    13554: Gforth consists not only of primitives (in the engine), but also of
1.1       anton    13555: definitions written in Forth. Since the Forth compiler itself belongs to
                   13556: those definitions, it is not possible to start the system with the
1.80    ! anton    13557: engine and the Forth source alone. Therefore we provide the Forth
1.26      crook    13558: code as an image file in nearly executable form. When Gforth starts up,
                   13559: a C routine loads the image file into memory, optionally relocates the
                   13560: addresses, then sets up the memory (stacks etc.) according to
                   13561: information in the image file, and (finally) starts executing Forth
                   13562: code.
1.1       anton    13563: 
                   13564: The image file variants represent different compromises between the
                   13565: goals of making it easy to generate image files and making them
                   13566: portable.
                   13567: 
                   13568: @cindex relocation at run-time
1.26      crook    13569: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    13570: run-time. This avoids many of the complications discussed below (image
                   13571: files are data relocatable without further ado), but costs performance
                   13572: (one addition per memory access).
                   13573: 
                   13574: @cindex relocation at load-time
1.26      crook    13575: By contrast, the Gforth loader performs relocation at image load time. The
                   13576: loader also has to replace tokens that represent primitive calls with the
1.1       anton    13577: appropriate code-field addresses (or code addresses in the case of
                   13578: direct threading).
                   13579: 
                   13580: There are three kinds of image files, with different degrees of
                   13581: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   13582: image files.
                   13583: 
                   13584: @cindex image file loader
                   13585: @cindex relocating loader
                   13586: @cindex loader for image files
                   13587: These image file variants have several restrictions in common; they are
                   13588: caused by the design of the image file loader:
                   13589: 
                   13590: @itemize @bullet
                   13591: @item
                   13592: There is only one segment; in particular, this means, that an image file
                   13593: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    13594: them). The contents of the stacks are not represented, either.
1.1       anton    13595: 
                   13596: @item
                   13597: The only kinds of relocation supported are: adding the same offset to
                   13598: all cells that represent data addresses; and replacing special tokens
                   13599: with code addresses or with pieces of machine code.
                   13600: 
                   13601: If any complex computations involving addresses are performed, the
                   13602: results cannot be represented in the image file. Several applications that
                   13603: use such computations come to mind:
                   13604: @itemize @minus
                   13605: @item
                   13606: Hashing addresses (or data structures which contain addresses) for table
                   13607: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   13608: purpose, you will have no problem, because the hash tables are
                   13609: recomputed automatically when the system is started. If you use your own
                   13610: hash tables, you will have to do something similar.
                   13611: 
                   13612: @item
                   13613: There's a cute implementation of doubly-linked lists that uses
                   13614: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   13615: in the image file, and restore the doubly-linked representation on
                   13616: startup.@footnote{In my opinion, though, you should think thrice before
                   13617: using a doubly-linked list (whatever implementation).}
                   13618: 
                   13619: @item
                   13620: The code addresses of run-time routines like @code{docol:} cannot be
                   13621: represented in the image file (because their tokens would be replaced by
                   13622: machine code in direct threaded implementations). As a workaround,
                   13623: compute these addresses at run-time with @code{>code-address} from the
                   13624: executions tokens of appropriate words (see the definitions of
1.80    ! anton    13625: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1       anton    13626: 
                   13627: @item
                   13628: On many architectures addresses are represented in machine code in some
                   13629: shifted or mangled form. You cannot put @code{CODE} words that contain
                   13630: absolute addresses in this form in a relocatable image file. Workarounds
                   13631: are representing the address in some relative form (e.g., relative to
                   13632: the CFA, which is present in some register), or loading the address from
                   13633: a place where it is stored in a non-mangled form.
                   13634: @end itemize
                   13635: @end itemize
                   13636: 
                   13637: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   13638: @section Non-Relocatable Image Files
                   13639: @cindex non-relocatable image files
1.26      crook    13640: @cindex image file, non-relocatable
1.1       anton    13641: 
                   13642: These files are simple memory dumps of the dictionary. They are specific
                   13643: to the executable (i.e., @file{gforth} file) they were created
                   13644: with. What's worse, they are specific to the place on which the
                   13645: dictionary resided when the image was created. Now, there is no
                   13646: guarantee that the dictionary will reside at the same place the next
                   13647: time you start Gforth, so there's no guarantee that a non-relocatable
                   13648: image will work the next time (Gforth will complain instead of crashing,
                   13649: though).
                   13650: 
                   13651: You can create a non-relocatable image file with
                   13652: 
1.44      crook    13653: 
1.1       anton    13654: doc-savesystem
                   13655: 
1.44      crook    13656: 
1.1       anton    13657: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   13658: @section Data-Relocatable Image Files
                   13659: @cindex data-relocatable image files
1.26      crook    13660: @cindex image file, data-relocatable
1.1       anton    13661: 
                   13662: These files contain relocatable data addresses, but fixed code addresses
                   13663: (instead of tokens). They are specific to the executable (i.e.,
                   13664: @file{gforth} file) they were created with. For direct threading on some
                   13665: architectures (e.g., the i386), data-relocatable images do not work. You
                   13666: get a data-relocatable image, if you use @file{gforthmi} with a
                   13667: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   13668: Relocatable Image Files}).
                   13669: 
                   13670: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   13671: @section Fully Relocatable Image Files
                   13672: @cindex fully relocatable image files
1.26      crook    13673: @cindex image file, fully relocatable
1.1       anton    13674: 
                   13675: @cindex @file{kern*.fi}, relocatability
                   13676: @cindex @file{gforth.fi}, relocatability
                   13677: These image files have relocatable data addresses, and tokens for code
                   13678: addresses. They can be used with different binaries (e.g., with and
                   13679: without debugging) on the same machine, and even across machines with
                   13680: the same data formats (byte order, cell size, floating point
                   13681: format). However, they are usually specific to the version of Gforth
                   13682: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   13683: are fully relocatable.
                   13684: 
                   13685: There are two ways to create a fully relocatable image file:
                   13686: 
                   13687: @menu
1.29      crook    13688: * gforthmi::                    The normal way
1.1       anton    13689: * cross.fs::                    The hard way
                   13690: @end menu
                   13691: 
                   13692: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   13693: @subsection @file{gforthmi}
                   13694: @cindex @file{comp-i.fs}
                   13695: @cindex @file{gforthmi}
                   13696: 
                   13697: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    13698: image @i{file} that contains everything you would load by invoking
                   13699: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    13700: @example
1.29      crook    13701: gforthmi @i{file} @i{options}
1.1       anton    13702: @end example
                   13703: 
                   13704: E.g., if you want to create an image @file{asm.fi} that has the file
                   13705: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   13706: like this:
                   13707: 
                   13708: @example
                   13709: gforthmi asm.fi asm.fs
                   13710: @end example
                   13711: 
1.27      crook    13712: @file{gforthmi} is implemented as a sh script and works like this: It
                   13713: produces two non-relocatable images for different addresses and then
                   13714: compares them. Its output reflects this: first you see the output (if
1.62      crook    13715: any) of the two Gforth invocations that produce the non-relocatable image
1.27      crook    13716: files, then you see the output of the comparing program: It displays the
                   13717: offset used for data addresses and the offset used for code addresses;
1.1       anton    13718: moreover, for each cell that cannot be represented correctly in the
1.44      crook    13719: image files, it displays a line like this:
1.1       anton    13720: 
                   13721: @example
                   13722:      78DC         BFFFFA50         BFFFFA40
                   13723: @end example
                   13724: 
                   13725: This means that at offset $78dc from @code{forthstart}, one input image
                   13726: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   13727: cannot be represented correctly in the output image, you should examine
                   13728: these places in the dictionary and verify that these cells are dead
                   13729: (i.e., not read before they are written).
1.39      anton    13730: 
                   13731: @cindex --application, @code{gforthmi} option
                   13732: If you insert the option @code{--application} in front of the image file
                   13733: name, you will get an image that uses the @code{--appl-image} option
                   13734: instead of the @code{--image-file} option (@pxref{Invoking
                   13735: Gforth}). When you execute such an image on Unix (by typing the image
                   13736: name as command), the Gforth engine will pass all options to the image
                   13737: instead of trying to interpret them as engine options.
1.1       anton    13738: 
1.27      crook    13739: If you type @file{gforthmi} with no arguments, it prints some usage
                   13740: instructions.
                   13741: 
1.1       anton    13742: @cindex @code{savesystem} during @file{gforthmi}
                   13743: @cindex @code{bye} during @file{gforthmi}
                   13744: @cindex doubly indirect threaded code
1.44      crook    13745: @cindex environment variables
                   13746: @cindex @code{GFORTHD} -- environment variable
                   13747: @cindex @code{GFORTH} -- environment variable
1.1       anton    13748: @cindex @code{gforth-ditc}
1.29      crook    13749: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    13750: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   13751: indirect threaded version of the @file{gforth} executable is used for
1.62      crook    13752: creating the non-relocatable images; you can pass the exact filename of
1.1       anton    13753: this executable through the environment variable @code{GFORTHD}
                   13754: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   13755: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    13756: data-relocatable image (because there is no code address offset). The
                   13757: normal @file{gforth} executable is used for creating the relocatable
                   13758: image; you can pass the exact filename of this executable through the
                   13759: environment variable @code{GFORTH}.
1.1       anton    13760: 
                   13761: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   13762: @subsection @file{cross.fs}
                   13763: @cindex @file{cross.fs}
                   13764: @cindex cross-compiler
                   13765: @cindex metacompiler
1.47      crook    13766: @cindex target compiler
1.1       anton    13767: 
                   13768: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47      crook    13769: programming language (@pxref{Cross Compiler}).
1.1       anton    13770: 
1.47      crook    13771: @code{cross} allows you to create image files for machines with
1.1       anton    13772: different data sizes and data formats than the one used for generating
                   13773: the image file. You can also use it to create an application image that
                   13774: does not contain a Forth compiler. These features are bought with
                   13775: restrictions and inconveniences in programming. E.g., addresses have to
                   13776: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   13777: order to make the code relocatable.
                   13778: 
                   13779: 
                   13780: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   13781: @section Stack and Dictionary Sizes
                   13782: @cindex image file, stack and dictionary sizes
                   13783: @cindex dictionary size default
                   13784: @cindex stack size default
                   13785: 
                   13786: If you invoke Gforth with a command line flag for the size
                   13787: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   13788: dictionary. If you save the dictionary with @code{savesystem} or create
                   13789: an image with @file{gforthmi}, this size will become the default
                   13790: for the resulting image file. E.g., the following will create a
1.21      crook    13791: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    13792: 
                   13793: @example
                   13794: gforthmi gforth.fi -m 1M
                   13795: @end example
                   13796: 
                   13797: In other words, if you want to set the default size for the dictionary
                   13798: and the stacks of an image, just invoke @file{gforthmi} with the
                   13799: appropriate options when creating the image.
                   13800: 
                   13801: @cindex stack size, cache-friendly
                   13802: Note: For cache-friendly behaviour (i.e., good performance), you should
                   13803: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   13804: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   13805: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   13806: 
                   13807: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   13808: @section Running Image Files
                   13809: @cindex running image files
                   13810: @cindex invoking image files
                   13811: @cindex image file invocation
                   13812: 
                   13813: @cindex -i, invoke image file
                   13814: @cindex --image file, invoke image file
1.29      crook    13815: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    13816: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   13817: @example
1.29      crook    13818: gforth -i @i{image}
1.1       anton    13819: @end example
                   13820: 
                   13821: @cindex executable image file
1.26      crook    13822: @cindex image file, executable
1.1       anton    13823: If your operating system supports starting scripts with a line of the
                   13824: form @code{#! ...}, you just have to type the image file name to start
                   13825: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    13826: just a convention). I.e., to run Gforth with the image file @i{image},
                   13827: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    13828: This works because every @code{.fi} file starts with a line of this
                   13829: format:
                   13830: 
                   13831: @example
                   13832: #! /usr/local/bin/gforth-0.4.0 -i
                   13833: @end example
                   13834: 
                   13835: The file and pathname for the Gforth engine specified on this line is
                   13836: the specific Gforth executable that it was built against; i.e. the value
                   13837: of the environment variable @code{GFORTH} at the time that
                   13838: @file{gforthmi} was executed.
1.1       anton    13839: 
1.27      crook    13840: You can make use of the same shell capability to make a Forth source
                   13841: file into an executable. For example, if you place this text in a file:
1.26      crook    13842: 
                   13843: @example
                   13844: #! /usr/local/bin/gforth
                   13845: 
                   13846: ." Hello, world" CR
                   13847: bye
                   13848: @end example
                   13849: 
                   13850: @noindent
1.27      crook    13851: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    13852: directly from the command line. The sequence @code{#!} is used in two
                   13853: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    13854: system@footnote{The Unix kernel actually recognises two types of files:
                   13855: executable files and files of data, where the data is processed by an
                   13856: interpreter that is specified on the ``interpreter line'' -- the first
                   13857: line of the file, starting with the sequence #!. There may be a small
                   13858: limit (e.g., 32) on the number of characters that may be specified on
                   13859: the interpreter line.} secondly it is treated as a comment character by
                   13860: Gforth. Because of the second usage, a space is required between
1.80    ! anton    13861: @code{#!} and the path to the executable (moreover, some Unixes
        !          13862: require the sequence @code{#! /}).
1.27      crook    13863: 
                   13864: The disadvantage of this latter technique, compared with using
1.80    ! anton    13865: @file{gforthmi}, is that it is slightly slower; the Forth source code is
        !          13866: compiled on-the-fly, each time the program is invoked.
1.26      crook    13867: 
1.1       anton    13868: doc-#!
                   13869: 
1.44      crook    13870: 
1.1       anton    13871: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   13872: @section Modifying the Startup Sequence
                   13873: @cindex startup sequence for image file
                   13874: @cindex image file initialization sequence
                   13875: @cindex initialization sequence of image file
                   13876: 
                   13877: You can add your own initialization to the startup sequence through the
1.26      crook    13878: deferred word @code{'cold}. @code{'cold} is invoked just before the
1.80    ! anton    13879: image-specific command line processing (i.e., loading files and
1.26      crook    13880: evaluating (@code{-e}) strings) starts.
1.1       anton    13881: 
                   13882: A sequence for adding your initialization usually looks like this:
                   13883: 
                   13884: @example
                   13885: :noname
                   13886:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   13887:     ... \ your stuff
                   13888: ; IS 'cold
                   13889: @end example
                   13890: 
                   13891: @cindex turnkey image files
1.26      crook    13892: @cindex image file, turnkey applications
1.1       anton    13893: You can make a turnkey image by letting @code{'cold} execute a word
                   13894: (your turnkey application) that never returns; instead, it exits Gforth
                   13895: via @code{bye} or @code{throw}.
                   13896: 
                   13897: @cindex command-line arguments, access
                   13898: @cindex arguments on the command line, access
                   13899: You can access the (image-specific) command-line arguments through the
1.26      crook    13900: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1       anton    13901: access to @code{argv}.
                   13902: 
1.26      crook    13903: If @code{'cold} exits normally, Gforth processes the command-line
                   13904: arguments as files to be loaded and strings to be evaluated.  Therefore,
                   13905: @code{'cold} should remove the arguments it has used in this case.
                   13906: 
1.44      crook    13907: 
                   13908: 
1.26      crook    13909: doc-'cold
1.1       anton    13910: doc-argc
                   13911: doc-argv
                   13912: doc-arg
                   13913: 
                   13914: 
1.44      crook    13915: 
1.1       anton    13916: @c ******************************************************************
1.13      pazsan   13917: @node Engine, Binding to System Library, Image Files, Top
1.1       anton    13918: @chapter Engine
                   13919: @cindex engine
                   13920: @cindex virtual machine
                   13921: 
1.26      crook    13922: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    13923: may be helpful for finding your way in the Gforth sources.
                   13924: 
1.66      anton    13925: The ideas in this section have also been published in Bernd Paysan,
                   13926: @cite{ANS fig/GNU/??? Forth} (in German), Forth-Tagung '93 and M. Anton
                   13927: Ertl, @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
                   13928: Portable Forth Engine}}, EuroForth '93.
1.1       anton    13929: 
                   13930: @menu
                   13931: * Portability::                 
                   13932: * Threading::                   
                   13933: * Primitives::                  
                   13934: * Performance::                 
                   13935: @end menu
                   13936: 
                   13937: @node Portability, Threading, Engine, Engine
                   13938: @section Portability
                   13939: @cindex engine portability
                   13940: 
1.26      crook    13941: An important goal of the Gforth Project is availability across a wide
                   13942: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   13943: achieved this goal by manually coding the engine in assembly language
                   13944: for several then-popular processors. This approach is very
                   13945: labor-intensive and the results are short-lived due to progress in
                   13946: computer architecture.
1.1       anton    13947: 
                   13948: @cindex C, using C for the engine
                   13949: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   13950: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   13951: particularly popular for UNIX-based Forths due to the large variety of
                   13952: architectures of UNIX machines. Unfortunately an implementation in C
                   13953: does not mix well with the goals of efficiency and with using
                   13954: traditional techniques: Indirect or direct threading cannot be expressed
                   13955: in C, and switch threading, the fastest technique available in C, is
                   13956: significantly slower. Another problem with C is that it is very
                   13957: cumbersome to express double integer arithmetic.
                   13958: 
                   13959: @cindex GNU C for the engine
                   13960: @cindex long long
                   13961: Fortunately, there is a portable language that does not have these
                   13962: limitations: GNU C, the version of C processed by the GNU C compiler
                   13963: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   13964: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   13965: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   13966: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   13967: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
                   13968: double numbers@footnote{Unfortunately, long longs are not implemented
                   13969: properly on all machines (e.g., on alpha-osf1, long longs are only 64
                   13970: bits, the same size as longs (and pointers), but they should be twice as
1.4       anton    13971: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1       anton    13972: C Manual}). So, we had to implement doubles in C after all. Still, on
                   13973: most machines we can use long longs and achieve better performance than
                   13974: with the emulation package.}. GNU C is available for free on all
                   13975: important (and many unimportant) UNIX machines, VMS, 80386s running
                   13976: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   13977: on all these machines.
                   13978: 
                   13979: Writing in a portable language has the reputation of producing code that
                   13980: is slower than assembly. For our Forth engine we repeatedly looked at
                   13981: the code produced by the compiler and eliminated most compiler-induced
                   13982: inefficiencies by appropriate changes in the source code.
                   13983: 
                   13984: @cindex explicit register declarations
                   13985: @cindex --enable-force-reg, configuration flag
                   13986: @cindex -DFORCE_REG
                   13987: However, register allocation cannot be portably influenced by the
                   13988: programmer, leading to some inefficiencies on register-starved
                   13989: machines. We use explicit register declarations (@pxref{Explicit Reg
                   13990: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   13991: improve the speed on some machines. They are turned on by using the
                   13992: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   13993: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   13994: machine, but also on the compiler version: On some machines some
                   13995: compiler versions produce incorrect code when certain explicit register
                   13996: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   13997: 
                   13998: @node Threading, Primitives, Portability, Engine
                   13999: @section Threading
                   14000: @cindex inner interpreter implementation
                   14001: @cindex threaded code implementation
                   14002: 
                   14003: @cindex labels as values
                   14004: GNU C's labels as values extension (available since @code{gcc-2.0},
                   14005: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    14006: makes it possible to take the address of @i{label} by writing
                   14007: @code{&&@i{label}}.  This address can then be used in a statement like
                   14008: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    14009: @code{goto x}.
                   14010: 
1.26      crook    14011: @cindex @code{NEXT}, indirect threaded
1.1       anton    14012: @cindex indirect threaded inner interpreter
                   14013: @cindex inner interpreter, indirect threaded
1.26      crook    14014: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    14015: @example
                   14016: cfa = *ip++;
                   14017: ca = *cfa;
                   14018: goto *ca;
                   14019: @end example
                   14020: @cindex instruction pointer
                   14021: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   14022: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   14023: execution token and points to the code field of the next word to be
                   14024: executed; The @code{ca} (code address) fetched from there points to some
                   14025: executable code, e.g., a primitive or the colon definition handler
                   14026: @code{docol}.
                   14027: 
1.26      crook    14028: @cindex @code{NEXT}, direct threaded
1.1       anton    14029: @cindex direct threaded inner interpreter
                   14030: @cindex inner interpreter, direct threaded
                   14031: Direct threading is even simpler:
                   14032: @example
                   14033: ca = *ip++;
                   14034: goto *ca;
                   14035: @end example
                   14036: 
                   14037: Of course we have packaged the whole thing neatly in macros called
1.26      crook    14038: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    14039: 
                   14040: @menu
                   14041: * Scheduling::                  
                   14042: * Direct or Indirect Threaded?::  
                   14043: * DOES>::                       
                   14044: @end menu
                   14045: 
                   14046: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   14047: @subsection Scheduling
                   14048: @cindex inner interpreter optimization
                   14049: 
                   14050: There is a little complication: Pipelined and superscalar processors,
                   14051: i.e., RISC and some modern CISC machines can process independent
                   14052: instructions while waiting for the results of an instruction. The
                   14053: compiler usually reorders (schedules) the instructions in a way that
                   14054: achieves good usage of these delay slots. However, on our first tries
                   14055: the compiler did not do well on scheduling primitives. E.g., for
                   14056: @code{+} implemented as
                   14057: @example
                   14058: n=sp[0]+sp[1];
                   14059: sp++;
                   14060: sp[0]=n;
                   14061: NEXT;
                   14062: @end example
1.26      crook    14063: the @code{NEXT} comes strictly after the other code, i.e., there is nearly no
1.1       anton    14064: scheduling. After a little thought the problem becomes clear: The
1.21      crook    14065: compiler cannot know that @code{sp} and @code{ip} point to different
                   14066: addresses (and the version of @code{gcc} we used would not know it even
                   14067: if it was possible), so it could not move the load of the cfa above the
                   14068: store to the TOS. Indeed the pointers could be the same, if code on or
                   14069: very near the top of stack were executed. In the interest of speed we
                   14070: chose to forbid this probably unused ``feature'' and helped the compiler
1.26      crook    14071: in scheduling: @code{NEXT} is divided into the loading part (@code{NEXT_P1})
1.21      crook    14072: and the goto part (@code{NEXT_P2}). @code{+} now looks like:
1.1       anton    14073: @example
                   14074: n=sp[0]+sp[1];
                   14075: sp++;
                   14076: NEXT_P1;
                   14077: sp[0]=n;
                   14078: NEXT_P2;
                   14079: @end example
                   14080: This can be scheduled optimally by the compiler.
                   14081: 
                   14082: This division can be turned off with the switch @code{-DCISC_NEXT}. This
                   14083: switch is on by default on machines that do not profit from scheduling
                   14084: (e.g., the 80386), in order to preserve registers.
                   14085: 
                   14086: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
                   14087: @subsection Direct or Indirect Threaded?
                   14088: @cindex threading, direct or indirect?
                   14089: 
                   14090: @cindex -DDIRECT_THREADED
                   14091: Both! After packaging the nasty details in macro definitions we
                   14092: realized that we could switch between direct and indirect threading by
                   14093: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
                   14094: defining a few machine-specific macros for the direct-threading case.
                   14095: On the Forth level we also offer access words that hide the
                   14096: differences between the threading methods (@pxref{Threading Words}).
                   14097: 
                   14098: Indirect threading is implemented completely machine-independently.
                   14099: Direct threading needs routines for creating jumps to the executable
1.21      crook    14100: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
                   14101: machine-dependent, but they do not amount to many source lines. Therefore,
                   14102: even porting direct threading to a new machine requires little effort.
1.1       anton    14103: 
                   14104: @cindex --enable-indirect-threaded, configuration flag
                   14105: @cindex --enable-direct-threaded, configuration flag
                   14106: The default threading method is machine-dependent. You can enforce a
                   14107: specific threading method when building Gforth with the configuration
                   14108: flag @code{--enable-direct-threaded} or
                   14109: @code{--enable-indirect-threaded}. Note that direct threading is not
                   14110: supported on all machines.
                   14111: 
                   14112: @node DOES>,  , Direct or Indirect Threaded?, Threading
                   14113: @subsection DOES>
                   14114: @cindex @code{DOES>} implementation
                   14115: 
1.26      crook    14116: @cindex @code{dodoes} routine
                   14117: @cindex @code{DOES>}-code
1.1       anton    14118: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   14119: the chunk of code executed by every word defined by a
                   14120: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
                   14121: the Forth code to be executed, i.e. the code after the
1.26      crook    14122: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1       anton    14123: 
1.21      crook    14124: In fig-Forth the code field points directly to the @code{dodoes} and the
1.45      crook    14125: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
1.29      crook    14126: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1       anton    14127: the Forth-79 and all later standards, because in fig-Forth this address
                   14128: lies in the body (which is illegal in these standards). However, by
                   14129: making the code field larger for all words this solution becomes legal
                   14130: again. We use this approach for the indirect threaded version and for
                   14131: direct threading on some machines. Leaving a cell unused in most words
                   14132: is a bit wasteful, but on the machines we are targeting this is hardly a
                   14133: problem. The other reason for having a code field size of two cells is
                   14134: to avoid having different image files for direct and indirect threaded
                   14135: systems (direct threaded systems require two-cell code fields on many
                   14136: machines).
                   14137: 
1.26      crook    14138: @cindex @code{DOES>}-handler
1.1       anton    14139: The other approach is that the code field points or jumps to the cell
1.26      crook    14140: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
                   14141: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
                   14142: @code{DOES>}-code address by computing the code address, i.e., the address of
1.45      crook    14143: the jump to @code{dodoes}, and add the length of that jump field. A variant of
1.1       anton    14144: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
                   14145: return address (which can be found in the return register on RISCs) is
1.26      crook    14146: the @code{DOES>}-code address. Since the two cells available in the code field
1.1       anton    14147: are used up by the jump to the code address in direct threading on many
                   14148: architectures, we use this approach for direct threading on these
                   14149: architectures. We did not want to add another cell to the code field.
                   14150: 
                   14151: @node Primitives, Performance, Threading, Engine
                   14152: @section Primitives
                   14153: @cindex primitives, implementation
                   14154: @cindex virtual machine instructions, implementation
                   14155: 
                   14156: @menu
                   14157: * Automatic Generation::        
                   14158: * TOS Optimization::            
                   14159: * Produced code::               
                   14160: @end menu
                   14161: 
                   14162: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   14163: @subsection Automatic Generation
                   14164: @cindex primitives, automatic generation
                   14165: 
                   14166: @cindex @file{prims2x.fs}
                   14167: Since the primitives are implemented in a portable language, there is no
                   14168: longer any need to minimize the number of primitives. On the contrary,
                   14169: having many primitives has an advantage: speed. In order to reduce the
                   14170: number of errors in primitives and to make programming them easier, we
                   14171: provide a tool, the primitive generator (@file{prims2x.fs}), that
                   14172: automatically generates most (and sometimes all) of the C code for a
                   14173: primitive from the stack effect notation.  The source for a primitive
                   14174: has the following form:
                   14175: 
                   14176: @cindex primitive source format
                   14177: @format
1.58      anton    14178: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
1.29      crook    14179: [@code{""}@i{glossary entry}@code{""}]
                   14180: @i{C code}
1.1       anton    14181: [@code{:}
1.29      crook    14182: @i{Forth code}]
1.1       anton    14183: @end format
                   14184: 
                   14185: The items in brackets are optional. The category and glossary fields
                   14186: are there for generating the documentation, the Forth code is there
                   14187: for manual implementations on machines without GNU C. E.g., the source
                   14188: for the primitive @code{+} is:
                   14189: @example
1.58      anton    14190: +    ( n1 n2 -- n )   core    plus
1.1       anton    14191: n = n1+n2;
                   14192: @end example
                   14193: 
                   14194: This looks like a specification, but in fact @code{n = n1+n2} is C
                   14195: code. Our primitive generation tool extracts a lot of information from
                   14196: the stack effect notations@footnote{We use a one-stack notation, even
                   14197: though we have separate data and floating-point stacks; The separate
                   14198: notation can be generated easily from the unified notation.}: The number
                   14199: of items popped from and pushed on the stack, their type, and by what
                   14200: name they are referred to in the C code. It then generates a C code
                   14201: prelude and postlude for each primitive. The final C code for @code{+}
                   14202: looks like this:
                   14203: 
                   14204: @example
1.46      pazsan   14205: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
1.1       anton    14206: /*  */                          /* documentation */
                   14207: @{
                   14208: DEF_CA                          /* definition of variable ca (indirect threading) */
                   14209: Cell n1;                        /* definitions of variables */
                   14210: Cell n2;
                   14211: Cell n;
                   14212: n1 = (Cell) sp[1];              /* input */
                   14213: n2 = (Cell) TOS;
                   14214: sp += 1;                        /* stack adjustment */
                   14215: NAME("+")                       /* debugging output (with -DDEBUG) */
                   14216: @{
                   14217: n = n1+n2;                      /* C code taken from the source */
                   14218: @}
                   14219: NEXT_P1;                        /* NEXT part 1 */
                   14220: TOS = (Cell)n;                  /* output */
                   14221: NEXT_P2;                        /* NEXT part 2 */
                   14222: @}
                   14223: @end example
                   14224: 
                   14225: This looks long and inefficient, but the GNU C compiler optimizes quite
                   14226: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   14227: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   14228: using them as intermediate storage also adds no cost.
                   14229: 
1.26      crook    14230: There are also other optimizations that are not illustrated by this
                   14231: example: assignments between simple variables are usually for free (copy
1.1       anton    14232: propagation). If one of the stack items is not used by the primitive
                   14233: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   14234: (dead code elimination). On the other hand, there are some things that
                   14235: the compiler does not do, therefore they are performed by
                   14236: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   14237: a stack item to the place where it just came from (e.g., @code{over}).
                   14238: 
                   14239: While programming a primitive is usually easy, there are a few cases
                   14240: where the programmer has to take the actions of the generator into
                   14241: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    14242: fall through to @code{NEXT}.
1.1       anton    14243: 
                   14244: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   14245: @subsection TOS Optimization
                   14246: @cindex TOS optimization for primitives
                   14247: @cindex primitives, keeping the TOS in a register
                   14248: 
                   14249: An important optimization for stack machine emulators, e.g., Forth
                   14250: engines, is keeping  one or more of the top stack items in
1.29      crook    14251: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   14252: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    14253: @itemize @bullet
                   14254: @item
1.29      crook    14255: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    14256: due to fewer loads from and stores to the stack.
1.29      crook    14257: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   14258: @i{y<n}, due to additional moves between registers.
1.1       anton    14259: @end itemize
                   14260: 
                   14261: @cindex -DUSE_TOS
                   14262: @cindex -DUSE_NO_TOS
                   14263: In particular, keeping one item in a register is never a disadvantage,
                   14264: if there are enough registers. Keeping two items in registers is a
                   14265: disadvantage for frequent words like @code{?branch}, constants,
                   14266: variables, literals and @code{i}. Therefore our generator only produces
                   14267: code that keeps zero or one items in registers. The generated C code
                   14268: covers both cases; the selection between these alternatives is made at
                   14269: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   14270: code for @code{+} is just a simple variable name in the one-item case,
                   14271: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   14272: GNU C compiler tries to keep simple variables like @code{TOS} in
                   14273: registers, and it usually succeeds, if there are enough registers.
                   14274: 
                   14275: @cindex -DUSE_FTOS
                   14276: @cindex -DUSE_NO_FTOS
                   14277: The primitive generator performs the TOS optimization for the
                   14278: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   14279: operations the benefit of this optimization is even larger:
                   14280: floating-point operations take quite long on most processors, but can be
                   14281: performed in parallel with other operations as long as their results are
                   14282: not used. If the FP-TOS is kept in a register, this works. If
                   14283: it is kept on the stack, i.e., in memory, the store into memory has to
                   14284: wait for the result of the floating-point operation, lengthening the
                   14285: execution time of the primitive considerably.
                   14286: 
                   14287: The TOS optimization makes the automatic generation of primitives a
                   14288: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   14289: @code{TOS} is not sufficient. There are some special cases to
                   14290: consider:
                   14291: @itemize @bullet
                   14292: @item In the case of @code{dup ( w -- w w )} the generator must not
                   14293: eliminate the store to the original location of the item on the stack,
                   14294: if the TOS optimization is turned on.
                   14295: @item Primitives with stack effects of the form @code{--}
1.29      crook    14296: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   14297: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    14298: must load the TOS from the stack at the end. But for the null stack
                   14299: effect @code{--} no stores or loads should be generated.
                   14300: @end itemize
                   14301: 
                   14302: @node Produced code,  , TOS Optimization, Primitives
                   14303: @subsection Produced code
                   14304: @cindex primitives, assembly code listing
                   14305: 
                   14306: @cindex @file{engine.s}
                   14307: To see what assembly code is produced for the primitives on your machine
                   14308: with your compiler and your flag settings, type @code{make engine.s} and
                   14309: look at the resulting file @file{engine.s}.
                   14310: 
                   14311: @node  Performance,  , Primitives, Engine
                   14312: @section Performance
                   14313: @cindex performance of some Forth interpreters
                   14314: @cindex engine performance
                   14315: @cindex benchmarking Forth systems
                   14316: @cindex Gforth performance
                   14317: 
                   14318: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
                   14319: impossible to write a significantly faster engine.
                   14320: 
                   14321: On register-starved machines like the 386 architecture processors
                   14322: improvements are possible, because @code{gcc} does not utilize the
                   14323: registers as well as a human, even with explicit register declarations;
                   14324: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   14325: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   14326: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40      anton    14327: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
                   14328: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
                   14329: registers fit in real registers (and we can even afford to use the TOS
                   14330: optimization), resulting in a speedup of 1.14 on the sieve over the
                   14331: earlier results.
1.1       anton    14332: 
                   14333: @cindex Win32Forth performance
                   14334: @cindex NT Forth performance
                   14335: @cindex eforth performance
                   14336: @cindex ThisForth performance
                   14337: @cindex PFE performance
                   14338: @cindex TILE performance
1.40      anton    14339: The potential advantage of assembly language implementations
1.1       anton    14340: is not necessarily realized in complete Forth systems: We compared
1.40      anton    14341: Gforth-0.4.9 (direct threaded, compiled with @code{gcc-2.95.1} and
1.1       anton    14342: @code{-DFORCE_REG}) with Win32Forth 1.2093, LMI's NT Forth (Beta, May
                   14343: 1994) and Eforth (with and without peephole (aka pinhole) optimization
                   14344: of the threaded code); all these systems were written in assembly
                   14345: language. We also compared Gforth with three systems written in C:
                   14346: PFE-0.9.14 (compiled with @code{gcc-2.6.3} with the default
                   14347: configuration for Linux: @code{-O2 -fomit-frame-pointer -DUSE_REGS
1.21      crook    14348: -DUNROLL_NEXT}), ThisForth Beta (compiled with @code{gcc-2.6.3 -O3
                   14349: -fomit-frame-pointer}; ThisForth employs peephole optimization of the
1.1       anton    14350: threaded code) and TILE (compiled with @code{make opt}). We benchmarked
                   14351: Gforth, PFE, ThisForth and TILE on a 486DX2/66 under Linux. Kenneth
                   14352: O'Heskin kindly provided the results for Win32Forth and NT Forth on a
                   14353: 486DX2/66 with similar memory performance under Windows NT. Marcel
                   14354: Hendrix ported Eforth to Linux, then extended it to run the benchmarks,
                   14355: added the peephole optimizer, ran the benchmarks and reported the
                   14356: results.
1.40      anton    14357: 
1.1       anton    14358: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   14359: matrix multiplication come from the Stanford integer benchmarks and have
                   14360: been translated into Forth by Martin Fraeman; we used the versions
                   14361: included in the TILE Forth package, but with bigger data set sizes; and
                   14362: a recursive Fibonacci number computation for benchmarking calling
                   14363: performance. The following table shows the time taken for the benchmarks
                   14364: scaled by the time taken by Gforth (in other words, it shows the speedup
                   14365: factor that Gforth achieved over the other systems).
                   14366: 
                   14367: @example
1.40      anton    14368: relative      Win32-    NT       eforth       This-      
1.1       anton    14369:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
1.40      anton    14370: sieve     1.00  1.58  1.30   1.58  0.97  1.80  3.63  9.79
                   14371: bubble    1.00  1.55  1.67   1.75  1.04  1.78        4.59
                   14372: matmul    1.00  1.67  1.53   1.66  0.84  1.79        4.63
                   14373: fib       1.00  1.75  1.53   1.40  0.99  1.99  3.43  4.93
1.1       anton    14374: @end example
                   14375: 
1.26      crook    14376: You may be quite surprised by the good performance of Gforth when
                   14377: compared with systems written in assembly language. One important reason
                   14378: for the disappointing performance of these other systems is probably
                   14379: that they are not written optimally for the 486 (e.g., they use the
                   14380: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   14381: but costly method for relocating the Forth image: like @code{cforth}, it
                   14382: computes the actual addresses at run time, resulting in two address
                   14383: computations per @code{NEXT} (@pxref{Image File Background}).
                   14384: 
1.40      anton    14385: Only Eforth with the peephole optimizer performs comparable to
                   14386: Gforth. The speedups achieved with peephole optimization of threaded
                   14387: code are quite remarkable. Adding a peephole optimizer to Gforth should
                   14388: cause similar speedups.
1.1       anton    14389: 
                   14390: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   14391: explained with the self-imposed restriction of the latter systems to
                   14392: standard C, which makes efficient threading impossible (however, the
1.4       anton    14393: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    14394: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   14395: Moreover, current C compilers have a hard time optimizing other aspects
                   14396: of the ThisForth and the TILE source.
                   14397: 
1.26      crook    14398: The performance of Gforth on 386 architecture processors varies widely
                   14399: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   14400: allocate any of the virtual machine registers into real machine
                   14401: registers by itself and would not work correctly with explicit register
1.40      anton    14402: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26      crook    14403: the Sieve) than the one measured above.
1.1       anton    14404: 
1.26      crook    14405: Note that there have been several releases of Win32Forth since the
                   14406: release presented here, so the results presented above may have little
1.40      anton    14407: predictive value for the performance of Win32Forth today (results for
                   14408: the current release on an i486DX2/66 are welcome).
1.1       anton    14409: 
                   14410: @cindex @file{Benchres}
1.66      anton    14411: In
                   14412: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
                   14413: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1       anton    14414: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66      anton    14415: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
                   14416: several native code systems; that version of Gforth is slower on a 486
                   14417: than the direct threaded version used here. You can find a newer version
                   14418: of these measurements at
1.47      crook    14419: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1       anton    14420: find numbers for Gforth on various machines in @file{Benchres}.
                   14421: 
1.26      crook    14422: @c ******************************************************************
1.13      pazsan   14423: @node Binding to System Library, Cross Compiler, Engine, Top
1.14      pazsan   14424: @chapter Binding to System Library
1.13      pazsan   14425: 
                   14426: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14      pazsan   14427: @chapter Cross Compiler
1.47      crook    14428: @cindex @file{cross.fs}
                   14429: @cindex cross-compiler
                   14430: @cindex metacompiler
                   14431: @cindex target compiler
1.13      pazsan   14432: 
1.46      pazsan   14433: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
                   14434: mostly written in Forth, including crucial parts like the outer
                   14435: interpreter and compiler, it needs compiled Forth code to get
                   14436: started. The cross compiler allows to create new images for other
                   14437: architectures, even running under another Forth system.
1.13      pazsan   14438: 
                   14439: @menu
1.67      anton    14440: * Using the Cross Compiler::    
                   14441: * How the Cross Compiler Works::  
1.13      pazsan   14442: @end menu
                   14443: 
1.21      crook    14444: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   14445: @section Using the Cross Compiler
1.46      pazsan   14446: 
                   14447: The cross compiler uses a language that resembles Forth, but isn't. The
                   14448: main difference is that you can execute Forth code after definition,
                   14449: while you usually can't execute the code compiled by cross, because the
                   14450: code you are compiling is typically for a different computer than the
                   14451: one you are compiling on.
                   14452: 
                   14453: The Makefile is already set up to allow you to create kernels for new
                   14454: architectures with a simple make command. The generic kernels using the
                   14455: GCC compiled virtual machine are created in the normal build process
                   14456: with @code{make}. To create a embedded Gforth executable for e.g. the
                   14457: 8086 processor (running on a DOS machine), type
                   14458: 
                   14459: @example
                   14460: make kernl-8086.fi
                   14461: @end example
                   14462: 
                   14463: This will use the machine description from the @file{arch/8086}
                   14464: directory to create a new kernel. A machine file may look like that:
                   14465: 
                   14466: @example
                   14467: \ Parameter for target systems                         06oct92py
                   14468: 
                   14469:     4 Constant cell             \ cell size in bytes
                   14470:     2 Constant cell<<           \ cell shift to bytes
                   14471:     5 Constant cell>bit         \ cell shift to bits
                   14472:     8 Constant bits/char        \ bits per character
                   14473:     8 Constant bits/byte        \ bits per byte [default: 8]
                   14474:     8 Constant float            \ bytes per float
                   14475:     8 Constant /maxalign        \ maximum alignment in bytes
                   14476: false Constant bigendian        \ byte order
                   14477: ( true=big, false=little )
                   14478: 
                   14479: include machpc.fs               \ feature list
                   14480: @end example
                   14481: 
                   14482: This part is obligatory for the cross compiler itself, the feature list
                   14483: is used by the kernel to conditionally compile some features in and out,
                   14484: depending on whether the target supports these features.
                   14485: 
                   14486: There are some optional features, if you define your own primitives,
                   14487: have an assembler, or need special, nonstandard preparation to make the
                   14488: boot process work. @code{asm-include} include an assembler,
                   14489: @code{prims-include} includes primitives, and @code{>boot} prepares for
                   14490: booting.
                   14491: 
                   14492: @example
                   14493: : asm-include    ." Include assembler" cr
                   14494:   s" arch/8086/asm.fs" included ;
                   14495: 
                   14496: : prims-include  ." Include primitives" cr
                   14497:   s" arch/8086/prim.fs" included ;
                   14498: 
                   14499: : >boot          ." Prepare booting" cr
                   14500:   s" ' boot >body into-forth 1+ !" evaluate ;
                   14501: @end example
                   14502: 
                   14503: These words are used as sort of macro during the cross compilation in
                   14504: the file @file{kernel/main.fs}. Instead of using this macros, it would
                   14505: be possible --- but more complicated --- to write a new kernel project
                   14506: file, too.
                   14507: 
                   14508: @file{kernel/main.fs} expects the machine description file name on the
                   14509: stack; the cross compiler itself (@file{cross.fs}) assumes that either
                   14510: @code{mach-file} leaves a counted string on the stack, or
                   14511: @code{machine-file} leaves an address, count pair of the filename on the
                   14512: stack.
                   14513: 
                   14514: The feature list is typically controlled using @code{SetValue}, generic
                   14515: files that are used by several projects can use @code{DefaultValue}
                   14516: instead. Both functions work like @code{Value}, when the value isn't
                   14517: defined, but @code{SetValue} works like @code{to} if the value is
                   14518: defined, and @code{DefaultValue} doesn't set anything, if the value is
                   14519: defined.
                   14520: 
                   14521: @example
                   14522: \ generic mach file for pc gforth                       03sep97jaw
                   14523: 
                   14524: true DefaultValue NIL  \ relocating
                   14525: 
                   14526: >ENVIRON
                   14527: 
                   14528: true DefaultValue file          \ controls the presence of the
                   14529:                                 \ file access wordset
                   14530: true DefaultValue OS            \ flag to indicate a operating system
                   14531: 
                   14532: true DefaultValue prims         \ true: primitives are c-code
                   14533: 
                   14534: true DefaultValue floating      \ floating point wordset is present
                   14535: 
                   14536: true DefaultValue glocals       \ gforth locals are present
                   14537:                                 \ will be loaded
                   14538: true DefaultValue dcomps        \ double number comparisons
                   14539: 
                   14540: true DefaultValue hash          \ hashing primitives are loaded/present
                   14541: 
                   14542: true DefaultValue xconds        \ used together with glocals,
                   14543:                                 \ special conditionals supporting gforths'
                   14544:                                 \ local variables
                   14545: true DefaultValue header        \ save a header information
                   14546: 
                   14547: true DefaultValue backtrace     \ enables backtrace code
                   14548: 
                   14549: false DefaultValue ec
                   14550: false DefaultValue crlf
                   14551: 
                   14552: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
                   14553: 
                   14554: &16 KB          DefaultValue stack-size
                   14555: &15 KB &512 +   DefaultValue fstack-size
                   14556: &15 KB          DefaultValue rstack-size
                   14557: &14 KB &512 +   DefaultValue lstack-size
                   14558: @end example
1.13      pazsan   14559: 
1.48      anton    14560: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
1.14      pazsan   14561: @section How the Cross Compiler Works
1.13      pazsan   14562: 
                   14563: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    14564: @appendix Bugs
1.1       anton    14565: @cindex bug reporting
                   14566: 
1.21      crook    14567: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    14568: 
                   14569: If you find a bug, please send a bug report to
1.33      anton    14570: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21      crook    14571: information:
                   14572: 
                   14573: @itemize @bullet
                   14574: @item
                   14575: The Gforth version used (it is announced at the start of an
                   14576: interactive Gforth session).
                   14577: @item
                   14578: The machine and operating system (on Unix
                   14579: systems @code{uname -a} will report this information).
                   14580: @item
                   14581: The installation options (send the file @file{config.status}).
                   14582: @item
                   14583: A complete list of changes (if any) you (or your installer) have made to the
                   14584: Gforth sources.
                   14585: @item
                   14586: A program (or a sequence of keyboard commands) that reproduces the bug.
                   14587: @item
                   14588: A description of what you think constitutes the buggy behaviour.
                   14589: @end itemize
1.1       anton    14590: 
                   14591: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   14592: to Report Bugs, gcc.info, GNU C Manual}.
                   14593: 
                   14594: 
1.21      crook    14595: @node Origin, Forth-related information, Bugs, Top
                   14596: @appendix Authors and Ancestors of Gforth
1.1       anton    14597: 
                   14598: @section Authors and Contributors
                   14599: @cindex authors of Gforth
                   14600: @cindex contributors to Gforth
                   14601: 
                   14602: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
                   14603: Ertl. The third major author was Jens Wilke.  Lennart Benschop (who was
                   14604: one of Gforth's first users, in mid-1993) and Stuart Ramsden inspired us
                   14605: with their continuous feedback. Lennart Benshop contributed
                   14606: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
                   14607: support for calling C libraries. Helpful comments also came from Paul
                   14608: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.58      anton    14609: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
                   14610: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
                   14611: helpful comments from many others; thank you all, sorry for not listing
                   14612: you here (but digging through my mailbox to extract your names is on my
                   14613: to-do list). Since the release of Gforth-0.4.0 Neal Crook worked on the
                   14614: manual.
1.1       anton    14615: 
                   14616: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   14617: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    14618: was developed across the Internet, and its authors did not meet
1.20      pazsan   14619: physically for the first 4 years of development.
1.1       anton    14620: 
                   14621: @section Pedigree
1.26      crook    14622: @cindex pedigree of Gforth
1.1       anton    14623: 
1.20      pazsan   14624: Gforth descends from bigFORTH (1993) and fig-Forth. Gforth and PFE (by
1.1       anton    14625: Dirk Zoller) will cross-fertilize each other. Of course, a significant
                   14626: part of the design of Gforth was prescribed by ANS Forth.
                   14627: 
1.20      pazsan   14628: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    14629: 32 bit native code version of VolksForth for the Atari ST, written
                   14630: mostly by Dietrich Weineck.
                   14631: 
                   14632: VolksForth descends from F83. It was written by Klaus Schleisiek, Bernd
                   14633: Pennemann, Georg Rehfeld and Dietrich Weineck for the C64 (called
                   14634: UltraForth there) in the mid-80s and ported to the Atari ST in 1986.
                   14635: 
                   14636: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   14637: Forth-83 standard. !! Pedigree? When?
                   14638: 
                   14639: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   14640: 1979. Robert Selzer and Bill Ragsdale developed the original
                   14641: implementation of fig-Forth for the 6502 based on microForth.
                   14642: 
                   14643: The principal architect of microForth was Dean Sanderson. microForth was
                   14644: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   14645: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   14646: Z80.
                   14647: 
                   14648: All earlier Forth systems were custom-made, usually by Charles Moore,
                   14649: who discovered (as he puts it) Forth during the late 60s. The first full
                   14650: Forth existed in 1971.
                   14651: 
                   14652: A part of the information in this section comes from @cite{The Evolution
                   14653: of Forth} by Elizabeth D. Rather, Donald R. Colburn and Charles
                   14654: H. Moore, presented at the HOPL-II conference and preprinted in SIGPLAN
                   14655: Notices 28(3), 1993.  You can find more historical and genealogical
                   14656: information about Forth there.
                   14657: 
1.21      crook    14658: @node Forth-related information, Word Index, Origin, Top
                   14659: @appendix Other Forth-related information
                   14660: @cindex Forth-related information
                   14661: 
                   14662: @menu
1.67      anton    14663: * Internet resources::          
                   14664: * Books::                       
                   14665: * The Forth Interest Group::    
                   14666: * Conferences::                 
1.21      crook    14667: @end menu
                   14668: 
                   14669: 
                   14670: @node Internet resources, Books, Forth-related information, Forth-related information
                   14671: @section Internet resources
1.26      crook    14672: @cindex internet resources
1.21      crook    14673: 
                   14674: @cindex comp.lang.forth
                   14675: @cindex frequently asked questions
1.45      crook    14676: There is an active news group (comp.lang.forth) discussing Forth and
1.21      crook    14677: Forth-related issues. A frequently-asked-questions (FAQ) list
1.45      crook    14678: is posted to the news group regularly, and archived at these sites:
1.21      crook    14679: 
                   14680: @itemize @bullet
                   14681: @item
1.47      crook    14682: @uref{ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.forth/}
1.21      crook    14683: @item
1.47      crook    14684: @uref{ftp://ftp.forth.org/pub/Forth/FAQ/}
1.21      crook    14685: @end itemize
                   14686: 
                   14687: The FAQ list should be considered mandatory reading before posting to
1.45      crook    14688: the news group.
1.21      crook    14689: 
                   14690: Here are some other web sites holding Forth-related material:
                   14691: 
                   14692: @itemize @bullet
                   14693: @item
1.47      crook    14694: @uref{http://www.taygeta.com/forth.html} -- Skip Carter's Forth pages.
1.21      crook    14695: @item
1.47      crook    14696: @uref{http://www.jwdt.com/~paysan/gforth.html} -- the Gforth home page.
1.21      crook    14697: @item
1.47      crook    14698: @uref{http://www.minerva.com/uathena.htm} -- home of ANS Forth Standard.
1.21      crook    14699: @item
1.47      crook    14700: @uref{http://dec.bournemouth.ac.uk/forth/index.html} -- the Forth
1.21      crook    14701: Research page, including links to the Journal of Forth Application and
                   14702: Research (JFAR) and a searchable Forth bibliography.
                   14703: @end itemize
                   14704: 
                   14705: 
                   14706: @node Books, The Forth Interest Group, Internet resources, Forth-related information
                   14707: @section Books
1.26      crook    14708: @cindex books on Forth
1.21      crook    14709: 
                   14710: As the Standard is relatively new, there are not many books out yet. It
                   14711: is not recommended to learn Forth by using Gforth and a book that is not
                   14712: written for ANS Forth, as you will not know your mistakes from the
                   14713: deviations of the book. However, books based on the Forth-83 standard
                   14714: should be ok, because ANS Forth is primarily an extension of Forth-83.
1.44      crook    14715: Refer to the Forth FAQ for details of Forth-related books.
1.21      crook    14716: 
                   14717: @cindex standard document for ANS Forth
                   14718: @cindex ANS Forth document
                   14719: The definite reference if you want to write ANS Forth programs is, of
1.26      crook    14720: course, the ANS Forth document. It is available in printed form from the
1.21      crook    14721: National Standards Institute Sales Department (Tel.: USA (212) 642-4900;
                   14722: Fax.: USA (212) 302-1286) as document @cite{X3.215-1994} for about
                   14723: $200. You can also get it from Global Engineering Documents (Tel.: USA
                   14724: (800) 854-7179; Fax.: (303) 843-9880) for about $300.
                   14725: 
                   14726: @cite{dpANS6}, the last draft of the standard, which was then submitted
                   14727: to ANSI for publication is available electronically and for free in some
                   14728: MS Word format, and it has been converted to HTML
1.47      crook    14729: (@uref{http://www.taygeta.com/forth/dpans.html}; this HTML version also
1.44      crook    14730: includes the answers to Requests for Interpretation (RFIs). Some
                   14731: pointers to these versions can be found through
1.47      crook    14732: @*@uref{http://www.complang.tuwien.ac.at/projects/forth.html}.
1.44      crook    14733: 
1.21      crook    14734: 
                   14735: @node The Forth Interest Group, Conferences, Books, Forth-related information
                   14736: @section The Forth Interest Group
                   14737: @cindex Forth interest group (FIG)
                   14738: 
                   14739: The Forth Interest Group (FIG) is a world-wide, non-profit,
1.26      crook    14740: member-supported organisation. It publishes a regular magazine,
                   14741: @var{FORTH Dimensions}, and offers other benefits of membership. You can
                   14742: contact the FIG through their office email address:
                   14743: @email{office@@forth.org} or by visiting their web site at
1.47      crook    14744: @uref{http://www.forth.org/}. This web site also includes links to FIG
1.26      crook    14745: chapters in other countries and American cities
1.47      crook    14746: (@uref{http://www.forth.org/chapters.html}).
1.21      crook    14747: 
1.48      anton    14748: @node Conferences,  , The Forth Interest Group, Forth-related information
1.21      crook    14749: @section Conferences
                   14750: @cindex Conferences
                   14751: 
                   14752: There are several regular conferences related to Forth. They are all
1.26      crook    14753: well-publicised in @var{FORTH Dimensions} and on the comp.lang.forth
1.45      crook    14754: news group:
1.21      crook    14755: 
                   14756: @itemize @bullet
                   14757: @item
                   14758: FORML -- the Forth modification laboratory convenes every year near
                   14759: Monterey, California.
                   14760: @item
                   14761: The Rochester Forth Conference -- an annual conference traditionally
                   14762: held in Rochester, New York.
                   14763: @item
                   14764: EuroForth -- this European conference takes place annually.
                   14765: @end itemize
                   14766: 
                   14767: 
1.41      anton    14768: @node Word Index, Name Index, Forth-related information, Top
1.1       anton    14769: @unnumbered Word Index
                   14770: 
1.26      crook    14771: This index is a list of Forth words that have ``glossary'' entries
                   14772: within this manual. Each word is listed with its stack effect and
                   14773: wordset.
1.1       anton    14774: 
                   14775: @printindex fn
                   14776: 
1.41      anton    14777: @node Name Index, Concept Index, Word Index, Top
                   14778: @unnumbered Name Index
                   14779: 
                   14780: This index is a list of Forth words that have ``glossary'' entries
                   14781: within this manual.
                   14782: 
                   14783: @printindex ky
                   14784: 
                   14785: @node Concept Index,  , Name Index, Top
1.1       anton    14786: @unnumbered Concept and Word Index
                   14787: 
1.26      crook    14788: Not all entries listed in this index are present verbatim in the
                   14789: text. This index also duplicates, in abbreviated form, all of the words
                   14790: listed in the Word Index (only the names are listed for the words here).
1.1       anton    14791: 
                   14792: @printindex cp
                   14793: 
                   14794: @contents
                   14795: @bye
                   14796: 

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