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

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
                    170: * Concept Index::               A menu covering many topics
1.12      anton     171: 
1.91      anton     172: @detailmenu
                    173:  --- 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::          
1.87      anton     211: * Files Tutorial::              
1.48      anton     212: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                    213: * Execution Tokens Tutorial::   
                    214: * Exceptions Tutorial::         
                    215: * Defining Words Tutorial::     
                    216: * Arrays and Records Tutorial::  
                    217: * POSTPONE Tutorial::           
                    218: * Literal Tutorial::            
                    219: * Advanced macros Tutorial::    
                    220: * Compilation Tokens Tutorial::  
                    221: * Wordlists and Search Order Tutorial::  
1.29      crook     222: 
1.24      anton     223: An Introduction to ANS Forth
                    224: 
1.67      anton     225: * Introducing the Text Interpreter::  
                    226: * Stacks and Postfix notation::  
                    227: * Your first definition::       
                    228: * How does that work?::         
                    229: * Forth is written in Forth::   
                    230: * Review - elements of a Forth system::  
                    231: * Where to go next::            
                    232: * Exercises::                   
1.24      anton     233: 
1.12      anton     234: Forth Words
                    235: 
                    236: * Notation::                    
1.65      anton     237: * Case insensitivity::          
                    238: * Comments::                    
                    239: * Boolean Flags::               
1.12      anton     240: * Arithmetic::                  
                    241: * Stack Manipulation::          
                    242: * Memory::                      
                    243: * Control Structures::          
                    244: * Defining Words::              
1.65      anton     245: * Interpretation and Compilation Semantics::  
1.47      crook     246: * Tokens for Words::            
1.81      anton     247: * Compiling words::             
1.65      anton     248: * The Text Interpreter::        
                    249: * Word Lists::                  
                    250: * Environmental Queries::       
1.12      anton     251: * Files::                       
                    252: * Blocks::                      
                    253: * Other I/O::                   
1.78      anton     254: * Locals::                      
                    255: * Structures::                  
                    256: * Object-oriented Forth::       
1.12      anton     257: * Programming Tools::           
                    258: * Assembler and Code Words::    
                    259: * Threading Words::             
1.65      anton     260: * Passing Commands to the OS::  
                    261: * Keeping track of Time::       
                    262: * Miscellaneous Words::         
1.12      anton     263: 
                    264: Arithmetic
                    265: 
                    266: * Single precision::            
1.67      anton     267: * Double precision::            Double-cell integer arithmetic
1.12      anton     268: * Bitwise operations::          
1.67      anton     269: * Numeric comparison::          
1.32      anton     270: * Mixed precision::             Operations with single and double-cell integers
1.12      anton     271: * Floating Point::              
                    272: 
                    273: Stack Manipulation
                    274: 
                    275: * Data stack::                  
                    276: * Floating point stack::        
                    277: * Return stack::                
                    278: * Locals stack::                
                    279: * Stack pointer manipulation::  
                    280: 
                    281: Memory
                    282: 
1.32      anton     283: * Memory model::                
                    284: * Dictionary allocation::       
                    285: * Heap Allocation::             
                    286: * Memory Access::               
                    287: * Address arithmetic::          
                    288: * Memory Blocks::               
1.12      anton     289: 
                    290: Control Structures
                    291: 
1.41      anton     292: * Selection::                   IF ... ELSE ... ENDIF
                    293: * Simple Loops::                BEGIN ...
1.32      anton     294: * Counted Loops::               DO
1.67      anton     295: * Arbitrary control structures::  
                    296: * Calls and returns::           
1.12      anton     297: * Exception Handling::          
                    298: 
                    299: Defining Words
                    300: 
1.67      anton     301: * CREATE::                      
1.44      crook     302: * Variables::                   Variables and user variables
1.67      anton     303: * Constants::                   
1.44      crook     304: * Values::                      Initialised variables
1.67      anton     305: * Colon Definitions::           
1.44      crook     306: * Anonymous Definitions::       Definitions without names
1.71      anton     307: * Supplying names::             Passing definition names as strings
1.67      anton     308: * User-defined Defining Words::  
1.44      crook     309: * Deferred words::              Allow forward references
1.67      anton     310: * Aliases::                     
1.47      crook     311: 
1.63      anton     312: User-defined Defining Words
                    313: 
                    314: * CREATE..DOES> applications::  
                    315: * CREATE..DOES> details::       
                    316: * Advanced does> usage example::  
1.91      anton     317: * @code{Const-does>}::          
1.63      anton     318: 
1.47      crook     319: Interpretation and Compilation Semantics
                    320: 
1.67      anton     321: * Combined words::              
1.12      anton     322: 
1.71      anton     323: Tokens for Words
                    324: 
                    325: * Execution token::             represents execution/interpretation semantics
                    326: * Compilation token::           represents compilation semantics
                    327: * Name token::                  represents named words
                    328: 
1.82      anton     329: Compiling words
                    330: 
                    331: * Literals::                    Compiling data values
                    332: * Macros::                      Compiling words
                    333: 
1.21      crook     334: The Text Interpreter
                    335: 
1.67      anton     336: * Input Sources::               
                    337: * Number Conversion::           
                    338: * Interpret/Compile states::    
                    339: * Interpreter Directives::      
1.21      crook     340: 
1.26      crook     341: Word Lists
                    342: 
1.75      anton     343: * Vocabularies::                
1.67      anton     344: * Why use word lists?::         
1.75      anton     345: * Word list example::           
1.26      crook     346: 
                    347: Files
                    348: 
1.48      anton     349: * Forth source files::          
                    350: * General files::               
                    351: * Search Paths::                
                    352: 
                    353: Search Paths
                    354: 
1.75      anton     355: * Source Search Paths::         
1.26      crook     356: * General Search Paths::        
                    357: 
                    358: Other I/O
                    359: 
1.32      anton     360: * Simple numeric output::       Predefined formats
                    361: * Formatted numeric output::    Formatted (pictured) output
                    362: * String Formats::              How Forth stores strings in memory
1.67      anton     363: * Displaying characters and strings::  Other stuff
1.32      anton     364: * Input::                       Input
1.26      crook     365: 
                    366: Locals
                    367: 
                    368: * Gforth locals::               
                    369: * ANS Forth locals::            
                    370: 
                    371: Gforth locals
                    372: 
                    373: * Where are locals visible by name?::  
                    374: * How long do locals live?::    
1.78      anton     375: * Locals programming style::    
                    376: * Locals implementation::       
1.26      crook     377: 
1.12      anton     378: Structures
                    379: 
                    380: * Why explicit structure support?::  
                    381: * Structure Usage::             
                    382: * Structure Naming Convention::  
                    383: * Structure Implementation::    
                    384: * Structure Glossary::          
                    385: 
                    386: Object-oriented Forth
                    387: 
1.48      anton     388: * Why object-oriented programming?::  
                    389: * Object-Oriented Terminology::  
                    390: * Objects::                     
                    391: * OOF::                         
                    392: * Mini-OOF::                    
1.23      crook     393: * Comparison with other object models::  
1.12      anton     394: 
1.24      anton     395: The @file{objects.fs} model
1.12      anton     396: 
                    397: * Properties of the Objects model::  
                    398: * Basic Objects Usage::         
1.41      anton     399: * The Objects base class::      
1.12      anton     400: * Creating objects::            
                    401: * Object-Oriented Programming Style::  
                    402: * Class Binding::               
                    403: * Method conveniences::         
                    404: * Classes and Scoping::         
1.41      anton     405: * Dividing classes::            
1.12      anton     406: * Object Interfaces::           
                    407: * Objects Implementation::      
                    408: * Objects Glossary::            
                    409: 
1.24      anton     410: The @file{oof.fs} model
1.12      anton     411: 
1.67      anton     412: * Properties of the OOF model::  
                    413: * Basic OOF Usage::             
                    414: * The OOF base class::          
                    415: * Class Declaration::           
                    416: * Class Implementation::        
1.12      anton     417: 
1.24      anton     418: The @file{mini-oof.fs} model
1.23      crook     419: 
1.48      anton     420: * Basic Mini-OOF Usage::        
                    421: * Mini-OOF Example::            
                    422: * Mini-OOF Implementation::     
1.23      crook     423: 
1.78      anton     424: Programming Tools
                    425: 
                    426: * Examining::                   
                    427: * Forgetting words::            
                    428: * Debugging::                   Simple and quick.
                    429: * Assertions::                  Making your programs self-checking.
                    430: * Singlestep Debugger::         Executing your program word by word.
                    431: 
                    432: Assembler and Code Words
                    433: 
                    434: * Code and ;code::              
                    435: * Common Assembler::            Assembler Syntax
                    436: * Common Disassembler::         
                    437: * 386 Assembler::               Deviations and special cases
                    438: * Alpha Assembler::             Deviations and special cases
                    439: * MIPS assembler::              Deviations and special cases
                    440: * Other assemblers::            How to write them
                    441: 
1.12      anton     442: Tools
                    443: 
                    444: * ANS Report::                  Report the words used, sorted by wordset.
                    445: 
                    446: ANS conformance
                    447: 
                    448: * The Core Words::              
                    449: * The optional Block word set::  
                    450: * The optional Double Number word set::  
                    451: * The optional Exception word set::  
                    452: * The optional Facility word set::  
                    453: * The optional File-Access word set::  
                    454: * The optional Floating-Point word set::  
                    455: * The optional Locals word set::  
                    456: * The optional Memory-Allocation word set::  
                    457: * The optional Programming-Tools word set::  
                    458: * The optional Search-Order word set::  
                    459: 
                    460: The Core Words
                    461: 
                    462: * core-idef::                   Implementation Defined Options                   
                    463: * core-ambcond::                Ambiguous Conditions                
                    464: * core-other::                  Other System Documentation                  
                    465: 
                    466: The optional Block word set
                    467: 
                    468: * block-idef::                  Implementation Defined Options
                    469: * block-ambcond::               Ambiguous Conditions               
                    470: * block-other::                 Other System Documentation                 
                    471: 
                    472: The optional Double Number word set
                    473: 
                    474: * double-ambcond::              Ambiguous Conditions              
                    475: 
                    476: The optional Exception word set
                    477: 
                    478: * exception-idef::              Implementation Defined Options              
                    479: 
                    480: The optional Facility word set
                    481: 
                    482: * facility-idef::               Implementation Defined Options               
                    483: * facility-ambcond::            Ambiguous Conditions            
                    484: 
                    485: The optional File-Access word set
                    486: 
                    487: * file-idef::                   Implementation Defined Options
                    488: * file-ambcond::                Ambiguous Conditions                
                    489: 
                    490: The optional Floating-Point word set
                    491: 
                    492: * floating-idef::               Implementation Defined Options
                    493: * floating-ambcond::            Ambiguous Conditions            
                    494: 
                    495: The optional Locals word set
                    496: 
                    497: * locals-idef::                 Implementation Defined Options                 
                    498: * locals-ambcond::              Ambiguous Conditions              
                    499: 
                    500: The optional Memory-Allocation word set
                    501: 
                    502: * memory-idef::                 Implementation Defined Options                 
                    503: 
                    504: The optional Programming-Tools word set
                    505: 
                    506: * programming-idef::            Implementation Defined Options            
                    507: * programming-ambcond::         Ambiguous Conditions         
                    508: 
                    509: The optional Search-Order word set
                    510: 
                    511: * search-idef::                 Implementation Defined Options                 
                    512: * search-ambcond::              Ambiguous Conditions              
                    513: 
                    514: Image Files
                    515: 
1.24      anton     516: * Image Licensing Issues::      Distribution terms for images.
                    517: * Image File Background::       Why have image files?
1.67      anton     518: * Non-Relocatable Image Files::  don't always work.
1.24      anton     519: * Data-Relocatable Image Files::  are better.
1.67      anton     520: * Fully Relocatable Image Files::  better yet.
1.24      anton     521: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     522: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     523: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     524: 
                    525: Fully Relocatable Image Files
                    526: 
1.27      crook     527: * gforthmi::                    The normal way
1.12      anton     528: * cross.fs::                    The hard way
                    529: 
                    530: Engine
                    531: 
                    532: * Portability::                 
                    533: * Threading::                   
                    534: * Primitives::                  
                    535: * Performance::                 
                    536: 
                    537: Threading
                    538: 
                    539: * Scheduling::                  
                    540: * Direct or Indirect Threaded?::  
                    541: * DOES>::                       
                    542: 
                    543: Primitives
                    544: 
                    545: * Automatic Generation::        
                    546: * TOS Optimization::            
                    547: * Produced code::               
1.13      pazsan    548: 
                    549: Cross Compiler
                    550: 
1.67      anton     551: * Using the Cross Compiler::    
                    552: * How the Cross Compiler Works::  
1.13      pazsan    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.
1.88      anton     563: 59 Temple Place, Suite 330, Boston, MA 02111, USA
1.1       anton     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
1.88      anton     909: Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
1.1       anton     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
1.89      anton    1048: messages (@pxref{Error messages}).  You should use it for debugged,
                   1049: performance-critical programs.
1.30      anton    1050: 
1.29      crook    1051: In general, the command line looks like this:
1.21      crook    1052: 
                   1053: @example
1.30      anton    1054: gforth[-fast] [engine options] [image options]
1.21      crook    1055: @end example
                   1056: 
1.30      anton    1057: The engine options must come before the rest of the command
1.29      crook    1058: line. They are:
1.26      crook    1059: 
1.29      crook    1060: @table @code
                   1061: @cindex -i, command-line option
                   1062: @cindex --image-file, command-line option
                   1063: @item --image-file @i{file}
                   1064: @itemx -i @i{file}
                   1065: Loads the Forth image @i{file} instead of the default
                   1066: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook    1067: 
1.39      anton    1068: @cindex --appl-image, command-line option
                   1069: @item --appl-image @i{file}
                   1070: Loads the image @i{file} and leaves all further command-line arguments
1.65      anton    1071: to the image (instead of processing them as engine options).  This is
                   1072: useful for building executable application images on Unix, built with
1.39      anton    1073: @code{gforthmi --application ...}.
                   1074: 
1.29      crook    1075: @cindex --path, command-line option
                   1076: @cindex -p, command-line option
                   1077: @item --path @i{path}
                   1078: @itemx -p @i{path}
                   1079: Uses @i{path} for searching the image file and Forth source code files
                   1080: instead of the default in the environment variable @code{GFORTHPATH} or
                   1081: the path specified at installation time (e.g.,
                   1082: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                   1083: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook    1084: 
1.29      crook    1085: @cindex --dictionary-size, command-line option
                   1086: @cindex -m, command-line option
                   1087: @cindex @i{size} parameters for command-line options
                   1088: @cindex size of the dictionary and the stacks
                   1089: @item --dictionary-size @i{size}
                   1090: @itemx -m @i{size}
                   1091: Allocate @i{size} space for the Forth dictionary space instead of
                   1092: using the default specified in the image (typically 256K). The
                   1093: @i{size} specification for this and subsequent options consists of
                   1094: an integer and a unit (e.g.,
                   1095: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                   1096: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                   1097: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                   1098: @code{e} is used.
1.21      crook    1099: 
1.29      crook    1100: @cindex --data-stack-size, command-line option
                   1101: @cindex -d, command-line option
                   1102: @item --data-stack-size @i{size}
                   1103: @itemx -d @i{size}
                   1104: Allocate @i{size} space for the data stack instead of using the
                   1105: default specified in the image (typically 16K).
1.21      crook    1106: 
1.29      crook    1107: @cindex --return-stack-size, command-line option
                   1108: @cindex -r, command-line option
                   1109: @item --return-stack-size @i{size}
                   1110: @itemx -r @i{size}
                   1111: Allocate @i{size} space for the return stack instead of using the
                   1112: default specified in the image (typically 15K).
1.21      crook    1113: 
1.29      crook    1114: @cindex --fp-stack-size, command-line option
                   1115: @cindex -f, command-line option
                   1116: @item --fp-stack-size @i{size}
                   1117: @itemx -f @i{size}
                   1118: Allocate @i{size} space for the floating point stack instead of
                   1119: using the default specified in the image (typically 15.5K). In this case
                   1120: the unit specifier @code{e} refers to floating point numbers.
1.21      crook    1121: 
1.48      anton    1122: @cindex --locals-stack-size, command-line option
                   1123: @cindex -l, command-line option
                   1124: @item --locals-stack-size @i{size}
                   1125: @itemx -l @i{size}
                   1126: Allocate @i{size} space for the locals stack instead of using the
                   1127: default specified in the image (typically 14.5K).
                   1128: 
                   1129: @cindex -h, command-line option
                   1130: @cindex --help, command-line option
                   1131: @item --help
                   1132: @itemx -h
                   1133: Print a message about the command-line options
                   1134: 
                   1135: @cindex -v, command-line option
                   1136: @cindex --version, command-line option
                   1137: @item --version
                   1138: @itemx -v
                   1139: Print version and exit
                   1140: 
                   1141: @cindex --debug, command-line option
                   1142: @item --debug
                   1143: Print some information useful for debugging on startup.
                   1144: 
                   1145: @cindex --offset-image, command-line option
                   1146: @item --offset-image
                   1147: Start the dictionary at a slightly different position than would be used
                   1148: otherwise (useful for creating data-relocatable images,
                   1149: @pxref{Data-Relocatable Image Files}).
                   1150: 
                   1151: @cindex --no-offset-im, command-line option
                   1152: @item --no-offset-im
                   1153: Start the dictionary at the normal position.
                   1154: 
                   1155: @cindex --clear-dictionary, command-line option
                   1156: @item --clear-dictionary
                   1157: Initialize all bytes in the dictionary to 0 before loading the image
                   1158: (@pxref{Data-Relocatable Image Files}).
                   1159: 
                   1160: @cindex --die-on-signal, command-line-option
                   1161: @item --die-on-signal
                   1162: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                   1163: or the segmentation violation SIGSEGV) by translating it into a Forth
                   1164: @code{THROW}. With this option, Gforth exits if it receives such a
                   1165: signal. This option is useful when the engine and/or the image might be
                   1166: severely broken (such that it causes another signal before recovering
                   1167: from the first); this option avoids endless loops in such cases.
                   1168: @end table
                   1169: 
                   1170: @cindex loading files at startup
                   1171: @cindex executing code on startup
                   1172: @cindex batch processing with Gforth
                   1173: As explained above, the image-specific command-line arguments for the
                   1174: default image @file{gforth.fi} consist of a sequence of filenames and
                   1175: @code{-e @var{forth-code}} options that are interpreted in the sequence
                   1176: in which they are given. The @code{-e @var{forth-code}} or
                   1177: @code{--evaluate @var{forth-code}} option evaluates the Forth
                   1178: code. This option takes only one argument; if you want to evaluate more
                   1179: Forth words, you have to quote them or use @code{-e} several times. To exit
                   1180: after processing the command line (instead of entering interactive mode)
                   1181: append @code{-e bye} to the command line.
                   1182: 
                   1183: @cindex versions, invoking other versions of Gforth
                   1184: If you have several versions of Gforth installed, @code{gforth} will
                   1185: invoke the version that was installed last. @code{gforth-@i{version}}
                   1186: invokes a specific version. If your environment contains the variable
                   1187: @code{GFORTHPATH}, you may want to override it by using the
                   1188: @code{--path} option.
                   1189: 
                   1190: Not yet implemented:
                   1191: On startup the system first executes the system initialization file
                   1192: (unless the option @code{--no-init-file} is given; note that the system
                   1193: resulting from using this option may not be ANS Forth conformant). Then
                   1194: the user initialization file @file{.gforth.fs} is executed, unless the
1.62      crook    1195: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48      anton    1196: then in @file{~}, then in the normal path (see above).
                   1197: 
                   1198: 
                   1199: 
                   1200: @comment ----------------------------------------------
                   1201: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                   1202: @section Leaving Gforth
                   1203: @cindex Gforth - leaving
                   1204: @cindex leaving Gforth
                   1205: 
                   1206: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                   1207: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                   1208: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49      anton    1209: data are discarded.  For ways of saving the state of the system before
                   1210: leaving Gforth see @ref{Image Files}.
1.48      anton    1211: 
                   1212: doc-bye
                   1213: 
                   1214: 
                   1215: @comment ----------------------------------------------
1.65      anton    1216: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48      anton    1217: @section Command-line editing
                   1218: @cindex command-line editing
                   1219: 
                   1220: Gforth maintains a history file that records every line that you type to
                   1221: the text interpreter. This file is preserved between sessions, and is
                   1222: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
                   1223: repeatedly you can recall successively older commands from this (or
                   1224: previous) session(s). The full list of command-line editing facilities is:
                   1225: 
                   1226: @itemize @bullet
                   1227: @item
                   1228: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
                   1229: commands from the history buffer.
                   1230: @item
                   1231: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
                   1232: from the history buffer.
                   1233: @item
                   1234: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
                   1235: @item
                   1236: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
                   1237: @item
                   1238: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
                   1239: closing up the line.
                   1240: @item
                   1241: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
                   1242: @item
                   1243: @kbd{Ctrl-a} to move the cursor to the start of the line.
                   1244: @item
                   1245: @kbd{Ctrl-e} to move the cursor to the end of the line.
                   1246: @item
                   1247: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
                   1248: line.
                   1249: @item
                   1250: @key{TAB} to step through all possible full-word completions of the word
                   1251: currently being typed.
                   1252: @item
1.65      anton    1253: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
                   1254: using @code{bye}). 
                   1255: @item
                   1256: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
                   1257: character under the cursor.
1.48      anton    1258: @end itemize
                   1259: 
                   1260: When editing, displayable characters are inserted to the left of the
                   1261: cursor position; the line is always in ``insert'' (as opposed to
                   1262: ``overstrike'') mode.
                   1263: 
                   1264: @cindex history file
                   1265: @cindex @file{.gforth-history}
                   1266: On Unix systems, the history file is @file{~/.gforth-history} by
                   1267: default@footnote{i.e. it is stored in the user's home directory.}. You
                   1268: can find out the name and location of your history file using:
                   1269: 
                   1270: @example 
                   1271: history-file type \ Unix-class systems
                   1272: 
                   1273: history-file type \ Other systems
                   1274: history-dir  type
                   1275: @end example
                   1276: 
                   1277: If you enter long definitions by hand, you can use a text editor to
                   1278: paste them out of the history file into a Forth source file for reuse at
                   1279: a later time.
                   1280: 
                   1281: Gforth never trims the size of the history file, so you should do this
                   1282: periodically, if necessary.
                   1283: 
                   1284: @comment this is all defined in history.fs
                   1285: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
                   1286: @comment chosen?
                   1287: 
                   1288: 
                   1289: @comment ----------------------------------------------
1.65      anton    1290: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48      anton    1291: @section Environment variables
                   1292: @cindex environment variables
                   1293: 
                   1294: Gforth uses these environment variables:
                   1295: 
                   1296: @itemize @bullet
                   1297: @item
                   1298: @cindex @code{GFORTHHIST} -- environment variable
                   1299: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
                   1300: open/create the history file, @file{.gforth-history}. Default:
                   1301: @code{$HOME}.
                   1302: 
                   1303: @item
                   1304: @cindex @code{GFORTHPATH} -- environment variable
                   1305: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
                   1306: for Forth source-code files.
                   1307: 
                   1308: @item
                   1309: @cindex @code{GFORTH} -- environment variable
1.49      anton    1310: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1311: 
                   1312: @item
                   1313: @cindex @code{GFORTHD} -- environment variable
1.62      crook    1314: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1315: 
                   1316: @item
                   1317: @cindex @code{TMP}, @code{TEMP} - environment variable
                   1318: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
                   1319: location for the history file.
                   1320: @end itemize
                   1321: 
                   1322: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1323: @comment mentioning these.
                   1324: 
                   1325: All the Gforth environment variables default to sensible values if they
                   1326: are not set.
                   1327: 
                   1328: 
                   1329: @comment ----------------------------------------------
                   1330: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
                   1331: @section Gforth files
                   1332: @cindex Gforth files
                   1333: 
                   1334: When you install Gforth on a Unix system, it installs files in these
                   1335: locations by default:
                   1336: 
                   1337: @itemize @bullet
                   1338: @item
                   1339: @file{/usr/local/bin/gforth}
                   1340: @item
                   1341: @file{/usr/local/bin/gforthmi}
                   1342: @item
                   1343: @file{/usr/local/man/man1/gforth.1} - man page.
                   1344: @item
                   1345: @file{/usr/local/info} - the Info version of this manual.
                   1346: @item
                   1347: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
                   1348: @item
                   1349: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
                   1350: @item
                   1351: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
                   1352: @item
                   1353: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
                   1354: @end itemize
                   1355: 
                   1356: You can select different places for installation by using
                   1357: @code{configure} options (listed with @code{configure --help}).
                   1358: 
                   1359: @comment ----------------------------------------------
                   1360: @node Startup speed,  , Gforth Files, Gforth Environment
                   1361: @section Startup speed
                   1362: @cindex Startup speed
                   1363: @cindex speed, startup
                   1364: 
                   1365: If Gforth is used for CGI scripts or in shell scripts, its startup
                   1366: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
                   1367: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
                   1368: system time.
                   1369: 
                   1370: If startup speed is a problem, you may consider the following ways to
                   1371: improve it; or you may consider ways to reduce the number of startups
1.62      crook    1372: (for example, by using Fast-CGI).
1.48      anton    1373: 
                   1374: The first step to improve startup speed is to statically link Gforth, by
                   1375: building it with @code{XLDFLAGS=-static}.  This requires more memory for
                   1376: the code and will therefore slow down the first invocation, but
                   1377: subsequent invocations avoid the dynamic linking overhead.  Another
                   1378: disadvantage is that Gforth won't profit from library upgrades.  As a
                   1379: result, @code{gforth-static -e bye} takes about 17.1ms user and
                   1380: 8.2ms system time.
                   1381: 
                   1382: The next step to improve startup speed is to use a non-relocatable image
1.65      anton    1383: (@pxref{Non-Relocatable Image Files}).  You can create this image with
1.48      anton    1384: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
                   1385: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
                   1386: and a part of the copy-on-write overhead.  The disadvantage is that the
1.62      crook    1387: non-relocatable image does not work if the OS gives Gforth a different
1.48      anton    1388: address for the dictionary, for whatever reason; so you better provide a
                   1389: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
                   1390: bye} takes about 15.3ms user and 7.5ms system time.
                   1391: 
                   1392: The final step is to disable dictionary hashing in Gforth.  Gforth
                   1393: builds the hash table on startup, which takes much of the startup
                   1394: overhead. You can do this by commenting out the @code{include hash.fs}
                   1395: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
                   1396: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
                   1397: The disadvantages are that functionality like @code{table} and
                   1398: @code{ekey} is missing and that text interpretation (e.g., compiling)
                   1399: now takes much longer. So, you should only use this method if there is
                   1400: no significant text interpretation to perform (the script should be
1.62      crook    1401: compiled into the image, amongst other things).  @code{gforth-static -i
1.48      anton    1402: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
                   1403: 
                   1404: @c ******************************************************************
                   1405: @node Tutorial, Introduction, Gforth Environment, Top
                   1406: @chapter Forth Tutorial
                   1407: @cindex Tutorial
                   1408: @cindex Forth Tutorial
                   1409: 
1.67      anton    1410: @c Topics from nac's Introduction that could be mentioned:
                   1411: @c press <ret> after each line
                   1412: @c Prompt
                   1413: @c numbers vs. words in dictionary on text interpretation
                   1414: @c what happens on redefinition
                   1415: @c parsing words (in particular, defining words)
                   1416: 
1.83      anton    1417: The difference of this chapter from the Introduction
                   1418: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
                   1419: be used while sitting in front of a computer, and covers much more
                   1420: material, but does not explain how the Forth system works.
                   1421: 
1.62      crook    1422: This tutorial can be used with any ANS-compliant Forth; any
                   1423: Gforth-specific features are marked as such and you can skip them if you
                   1424: work with another Forth.  This tutorial does not explain all features of
                   1425: Forth, just enough to get you started and give you some ideas about the
                   1426: facilities available in Forth.  Read the rest of the manual and the
                   1427: standard when you are through this.
1.48      anton    1428: 
                   1429: The intended way to use this tutorial is that you work through it while
                   1430: sitting in front of the console, take a look at the examples and predict
                   1431: what they will do, then try them out; if the outcome is not as expected,
                   1432: find out why (e.g., by trying out variations of the example), so you
                   1433: understand what's going on.  There are also some assignments that you
                   1434: should solve.
                   1435: 
                   1436: This tutorial assumes that you have programmed before and know what,
                   1437: e.g., a loop is.
                   1438: 
                   1439: @c !! explain compat library
                   1440: 
                   1441: @menu
                   1442: * Starting Gforth Tutorial::    
                   1443: * Syntax Tutorial::             
                   1444: * Crash Course Tutorial::       
                   1445: * Stack Tutorial::              
                   1446: * Arithmetics Tutorial::        
                   1447: * Stack Manipulation Tutorial::  
                   1448: * Using files for Forth code Tutorial::  
                   1449: * Comments Tutorial::           
                   1450: * Colon Definitions Tutorial::  
                   1451: * Decompilation Tutorial::      
                   1452: * Stack-Effect Comments Tutorial::  
                   1453: * Types Tutorial::              
                   1454: * Factoring Tutorial::          
                   1455: * Designing the stack effect Tutorial::  
                   1456: * Local Variables Tutorial::    
                   1457: * Conditional execution Tutorial::  
                   1458: * Flags and Comparisons Tutorial::  
                   1459: * General Loops Tutorial::      
                   1460: * Counted loops Tutorial::      
                   1461: * Recursion Tutorial::          
                   1462: * Leaving definitions or loops Tutorial::  
                   1463: * Return Stack Tutorial::       
                   1464: * Memory Tutorial::             
                   1465: * Characters and Strings Tutorial::  
                   1466: * Alignment Tutorial::          
1.87      anton    1467: * Files Tutorial::              
1.48      anton    1468: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1469: * Execution Tokens Tutorial::   
                   1470: * Exceptions Tutorial::         
                   1471: * Defining Words Tutorial::     
                   1472: * Arrays and Records Tutorial::  
                   1473: * POSTPONE Tutorial::           
                   1474: * Literal Tutorial::            
                   1475: * Advanced macros Tutorial::    
                   1476: * Compilation Tokens Tutorial::  
                   1477: * Wordlists and Search Order Tutorial::  
                   1478: @end menu
                   1479: 
                   1480: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1481: @section Starting Gforth
1.66      anton    1482: @cindex starting Gforth tutorial
1.48      anton    1483: You can start Gforth by typing its name:
                   1484: 
                   1485: @example
                   1486: gforth
                   1487: @end example
                   1488: 
                   1489: That puts you into interactive mode; you can leave Gforth by typing
                   1490: @code{bye}.  While in Gforth, you can edit the command line and access
                   1491: the command line history with cursor keys, similar to bash.
                   1492: 
                   1493: 
                   1494: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1495: @section Syntax
1.66      anton    1496: @cindex syntax tutorial
1.48      anton    1497: 
                   1498: A @dfn{word} is a sequence of arbitrary characters (expcept white
                   1499: space).  Words are separated by white space.  E.g., each of the
                   1500: following lines contains exactly one word:
                   1501: 
                   1502: @example
                   1503: word
                   1504: !@@#$%^&*()
                   1505: 1234567890
                   1506: 5!a
                   1507: @end example
                   1508: 
                   1509: A frequent beginner's error is to leave away necessary white space,
                   1510: resulting in an error like @samp{Undefined word}; so if you see such an
                   1511: error, check if you have put spaces wherever necessary.
                   1512: 
                   1513: @example
                   1514: ." hello, world" \ correct
                   1515: ."hello, world"  \ gives an "Undefined word" error
                   1516: @end example
                   1517: 
1.65      anton    1518: Gforth and most other Forth systems ignore differences in case (they are
1.48      anton    1519: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1520: your system is case-sensitive, you may have to type all the examples
                   1521: given here in upper case.
                   1522: 
                   1523: 
                   1524: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1525: @section Crash Course
                   1526: 
                   1527: Type
                   1528: 
                   1529: @example
                   1530: 0 0 !
                   1531: here execute
                   1532: ' catch >body 20 erase abort
                   1533: ' (quit) >body 20 erase
                   1534: @end example
                   1535: 
                   1536: The last two examples are guaranteed to destroy parts of Gforth (and
                   1537: most other systems), so you better leave Gforth afterwards (if it has
                   1538: not finished by itself).  On some systems you may have to kill gforth
                   1539: from outside (e.g., in Unix with @code{kill}).
                   1540: 
                   1541: Now that you know how to produce crashes (and that there's not much to
                   1542: them), let's learn how to produce meaningful programs.
                   1543: 
                   1544: 
                   1545: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1546: @section Stack
1.66      anton    1547: @cindex stack tutorial
1.48      anton    1548: 
                   1549: The most obvious feature of Forth is the stack.  When you type in a
                   1550: number, it is pushed on the stack.  You can display the content of the
                   1551: stack with @code{.s}.
                   1552: 
                   1553: @example
                   1554: 1 2 .s
                   1555: 3 .s
                   1556: @end example
                   1557: 
                   1558: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1559: appear in @code{.s} output as they appeared in the input.
                   1560: 
                   1561: You can print the top of stack element with @code{.}.
                   1562: 
                   1563: @example
                   1564: 1 2 3 . . .
                   1565: @end example
                   1566: 
                   1567: In general, words consume their stack arguments (@code{.s} is an
                   1568: exception).
                   1569: 
                   1570: @assignment
                   1571: What does the stack contain after @code{5 6 7 .}?
                   1572: @endassignment
                   1573: 
                   1574: 
                   1575: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1576: @section Arithmetics
1.66      anton    1577: @cindex arithmetics tutorial
1.48      anton    1578: 
                   1579: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1580: operate on the top two stack items:
                   1581: 
                   1582: @example
1.67      anton    1583: 2 2 .s
                   1584: + .s
                   1585: .
1.48      anton    1586: 2 1 - .
                   1587: 7 3 mod .
                   1588: @end example
                   1589: 
                   1590: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1591: as in the corresponding infix expression (this is generally the case in
                   1592: Forth).
                   1593: 
                   1594: Parentheses are superfluous (and not available), because the order of
                   1595: the words unambiguously determines the order of evaluation and the
                   1596: operands:
                   1597: 
                   1598: @example
                   1599: 3 4 + 5 * .
                   1600: 3 4 5 * + .
                   1601: @end example
                   1602: 
                   1603: @assignment
                   1604: What are the infix expressions corresponding to the Forth code above?
                   1605: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1606: known as Postfix or RPN (Reverse Polish Notation).}.
                   1607: @endassignment
                   1608: 
                   1609: To change the sign, use @code{negate}:
                   1610: 
                   1611: @example
                   1612: 2 negate .
                   1613: @end example
                   1614: 
                   1615: @assignment
                   1616: Convert -(-3)*4-5 to Forth.
                   1617: @endassignment
                   1618: 
                   1619: @code{/mod} performs both @code{/} and @code{mod}.
                   1620: 
                   1621: @example
                   1622: 7 3 /mod . .
                   1623: @end example
                   1624: 
1.66      anton    1625: Reference: @ref{Arithmetic}.
                   1626: 
                   1627: 
1.48      anton    1628: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1629: @section Stack Manipulation
1.66      anton    1630: @cindex stack manipulation tutorial
1.48      anton    1631: 
                   1632: Stack manipulation words rearrange the data on the stack.
                   1633: 
                   1634: @example
                   1635: 1 .s drop .s
                   1636: 1 .s dup .s drop drop .s
                   1637: 1 2 .s over .s drop drop drop
                   1638: 1 2 .s swap .s drop drop
                   1639: 1 2 3 .s rot .s drop drop drop
                   1640: @end example
                   1641: 
                   1642: These are the most important stack manipulation words.  There are also
                   1643: variants that manipulate twice as many stack items:
                   1644: 
                   1645: @example
                   1646: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1647: @end example
                   1648: 
                   1649: Two more stack manipulation words are:
                   1650: 
                   1651: @example
                   1652: 1 2 .s nip .s drop
                   1653: 1 2 .s tuck .s 2drop drop
                   1654: @end example
                   1655: 
                   1656: @assignment
                   1657: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1658: manipulation words.
                   1659: 
                   1660: @example
                   1661: Given:          How do you get:
                   1662: 1 2 3           3 2 1           
                   1663: 1 2 3           1 2 3 2                 
                   1664: 1 2 3           1 2 3 3                 
                   1665: 1 2 3           1 3 3           
                   1666: 1 2 3           2 1 3           
                   1667: 1 2 3 4         4 3 2 1         
                   1668: 1 2 3           1 2 3 1 2 3             
                   1669: 1 2 3 4         1 2 3 4 1 2             
                   1670: 1 2 3
                   1671: 1 2 3           1 2 3 4                 
                   1672: 1 2 3           1 3             
                   1673: @end example
                   1674: @endassignment
                   1675: 
                   1676: @example
                   1677: 5 dup * .
                   1678: @end example
                   1679: 
                   1680: @assignment
                   1681: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1682: Write a piece of Forth code that expects two numbers on the stack
                   1683: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1684: @code{(a-b)(a+1)}.
                   1685: @endassignment
                   1686: 
1.66      anton    1687: Reference: @ref{Stack Manipulation}.
                   1688: 
                   1689: 
1.48      anton    1690: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1691: @section Using files for Forth code
1.66      anton    1692: @cindex loading Forth code, tutorial
                   1693: @cindex files containing Forth code, tutorial
1.48      anton    1694: 
                   1695: While working at the Forth command line is convenient for one-line
                   1696: examples and short one-off code, you probably want to store your source
                   1697: code in files for convenient editing and persistence.  You can use your
                   1698: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
                   1699: Gforth}) to create @var{file} and use
                   1700: 
                   1701: @example
                   1702: s" @var{file}" included
                   1703: @end example
                   1704: 
                   1705: to load it into your Forth system.  The file name extension I use for
                   1706: Forth files is @samp{.fs}.
                   1707: 
                   1708: You can easily start Gforth with some files loaded like this:
                   1709: 
                   1710: @example
                   1711: gforth @var{file1} @var{file2}
                   1712: @end example
                   1713: 
                   1714: If an error occurs during loading these files, Gforth terminates,
                   1715: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1716: a Gforth command line.  Starting the Forth system every time gives you a
                   1717: clean start every time, without interference from the results of earlier
                   1718: tries.
                   1719: 
                   1720: I often put all the tests in a file, then load the code and run the
                   1721: tests with
                   1722: 
                   1723: @example
                   1724: gforth @var{code} @var{tests} -e bye
                   1725: @end example
                   1726: 
                   1727: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1728: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1729: restart this command without ado.
                   1730: 
                   1731: The advantage of this approach is that the tests can be repeated easily
                   1732: every time the program ist changed, making it easy to catch bugs
                   1733: introduced by the change.
                   1734: 
1.66      anton    1735: Reference: @ref{Forth source files}.
                   1736: 
1.48      anton    1737: 
                   1738: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1739: @section Comments
1.66      anton    1740: @cindex comments tutorial
1.48      anton    1741: 
                   1742: @example
                   1743: \ That's a comment; it ends at the end of the line
                   1744: ( Another comment; it ends here: )  .s
                   1745: @end example
                   1746: 
                   1747: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1748: separated with white space from the following text.
                   1749: 
                   1750: @example
                   1751: \This gives an "Undefined word" error
                   1752: @end example
                   1753: 
                   1754: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1755: nest @code{(}-comments; and you cannot comment out text containing a
                   1756: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1757: avoid @code{)} in word names.}.
                   1758: 
                   1759: I use @code{\}-comments for descriptive text and for commenting out code
                   1760: of one or more line; I use @code{(}-comments for describing the stack
                   1761: effect, the stack contents, or for commenting out sub-line pieces of
                   1762: code.
                   1763: 
                   1764: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1765: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1766: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1767: with @kbd{M-q}.
                   1768: 
1.66      anton    1769: Reference: @ref{Comments}.
                   1770: 
1.48      anton    1771: 
                   1772: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1773: @section Colon Definitions
1.66      anton    1774: @cindex colon definitions, tutorial
                   1775: @cindex definitions, tutorial
                   1776: @cindex procedures, tutorial
                   1777: @cindex functions, tutorial
1.48      anton    1778: 
                   1779: are similar to procedures and functions in other programming languages.
                   1780: 
                   1781: @example
                   1782: : squared ( n -- n^2 )
                   1783:    dup * ;
                   1784: 5 squared .
                   1785: 7 squared .
                   1786: @end example
                   1787: 
                   1788: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1789: following comment describes its stack effect.  The words @code{dup *}
                   1790: are not executed, but compiled into the definition.  @code{;} ends the
                   1791: colon definition.
                   1792: 
                   1793: The newly-defined word can be used like any other word, including using
                   1794: it in other definitions:
                   1795: 
                   1796: @example
                   1797: : cubed ( n -- n^3 )
                   1798:    dup squared * ;
                   1799: -5 cubed .
                   1800: : fourth-power ( n -- n^4 )
                   1801:    squared squared ;
                   1802: 3 fourth-power .
                   1803: @end example
                   1804: 
                   1805: @assignment
                   1806: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1807: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1808: test your tests on the originals first).  Don't let the
                   1809: @samp{redefined}-Messages spook you, they are just warnings.
                   1810: @endassignment
                   1811: 
1.66      anton    1812: Reference: @ref{Colon Definitions}.
                   1813: 
1.48      anton    1814: 
                   1815: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1816: @section Decompilation
1.66      anton    1817: @cindex decompilation tutorial
                   1818: @cindex see tutorial
1.48      anton    1819: 
                   1820: You can decompile colon definitions with @code{see}:
                   1821: 
                   1822: @example
                   1823: see squared
                   1824: see cubed
                   1825: @end example
                   1826: 
                   1827: In Gforth @code{see} shows you a reconstruction of the source code from
                   1828: the executable code.  Informations that were present in the source, but
                   1829: not in the executable code, are lost (e.g., comments).
                   1830: 
1.65      anton    1831: You can also decompile the predefined words:
                   1832: 
                   1833: @example
                   1834: see .
                   1835: see +
                   1836: @end example
                   1837: 
                   1838: 
1.48      anton    1839: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1840: @section Stack-Effect Comments
1.66      anton    1841: @cindex stack-effect comments, tutorial
                   1842: @cindex --, tutorial
1.48      anton    1843: By convention the comment after the name of a definition describes the
                   1844: stack effect: The part in from of the @samp{--} describes the state of
                   1845: the stack before the execution of the definition, i.e., the parameters
                   1846: that are passed into the colon definition; the part behind the @samp{--}
                   1847: is the state of the stack after the execution of the definition, i.e.,
                   1848: the results of the definition.  The stack comment only shows the top
                   1849: stack items that the definition accesses and/or changes.
                   1850: 
                   1851: You should put a correct stack effect on every definition, even if it is
                   1852: just @code{( -- )}.  You should also add some descriptive comment to
                   1853: more complicated words (I usually do this in the lines following
                   1854: @code{:}).  If you don't do this, your code becomes unreadable (because
                   1855: you have to work through every definition before you can undertsand
                   1856: any).
                   1857: 
                   1858: @assignment
                   1859: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1860: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1861: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
1.65      anton    1862: are done, you can compare your stack effects to those in this manual
1.48      anton    1863: (@pxref{Word Index}).
                   1864: @endassignment
                   1865: 
                   1866: Sometimes programmers put comments at various places in colon
                   1867: definitions that describe the contents of the stack at that place (stack
                   1868: comments); i.e., they are like the first part of a stack-effect
                   1869: comment. E.g.,
                   1870: 
                   1871: @example
                   1872: : cubed ( n -- n^3 )
                   1873:    dup squared  ( n n^2 ) * ;
                   1874: @end example
                   1875: 
                   1876: In this case the stack comment is pretty superfluous, because the word
                   1877: is simple enough.  If you think it would be a good idea to add such a
                   1878: comment to increase readability, you should also consider factoring the
                   1879: word into several simpler words (@pxref{Factoring Tutorial,,
1.60      anton    1880: Factoring}), which typically eliminates the need for the stack comment;
1.48      anton    1881: however, if you decide not to refactor it, then having such a comment is
                   1882: better than not having it.
                   1883: 
                   1884: The names of the stack items in stack-effect and stack comments in the
                   1885: standard, in this manual, and in many programs specify the type through
                   1886: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1887: frequent prefixes are:
                   1888: 
                   1889: @table @code
                   1890: @item n
                   1891: signed integer
                   1892: @item u
                   1893: unsigned integer
                   1894: @item c
                   1895: character
                   1896: @item f
                   1897: Boolean flags, i.e. @code{false} or @code{true}.
                   1898: @item a-addr,a-
                   1899: Cell-aligned address
                   1900: @item c-addr,c-
                   1901: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1902: @item xt
                   1903: Execution token, same size as Cell
                   1904: @item w,x
                   1905: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1906: 16 bits (depending on your platform and Forth system). A cell is more
                   1907: commonly known as machine word, but the term @emph{word} already means
                   1908: something different in Forth.
                   1909: @item d
                   1910: signed double-cell integer
                   1911: @item ud
                   1912: unsigned double-cell integer
                   1913: @item r
                   1914: Float (on the FP stack)
                   1915: @end table
                   1916: 
                   1917: You can find a more complete list in @ref{Notation}.
                   1918: 
                   1919: @assignment
                   1920: Write stack-effect comments for all definitions you have written up to
                   1921: now.
                   1922: @endassignment
                   1923: 
                   1924: 
                   1925: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1926: @section Types
1.66      anton    1927: @cindex types tutorial
1.48      anton    1928: 
                   1929: In Forth the names of the operations are not overloaded; so similar
                   1930: operations on different types need different names; e.g., @code{+} adds
                   1931: integers, and you have to use @code{f+} to add floating-point numbers.
                   1932: The following prefixes are often used for related operations on
                   1933: different types:
                   1934: 
                   1935: @table @code
                   1936: @item (none)
                   1937: signed integer
                   1938: @item u
                   1939: unsigned integer
                   1940: @item c
                   1941: character
                   1942: @item d
                   1943: signed double-cell integer
                   1944: @item ud, du
                   1945: unsigned double-cell integer
                   1946: @item 2
                   1947: two cells (not-necessarily double-cell numbers)
                   1948: @item m, um
                   1949: mixed single-cell and double-cell operations
                   1950: @item f
                   1951: floating-point (note that in stack comments @samp{f} represents flags,
1.66      anton    1952: and @samp{r} represents FP numbers).
1.48      anton    1953: @end table
                   1954: 
                   1955: If there are no differences between the signed and the unsigned variant
                   1956: (e.g., for @code{+}), there is only the prefix-less variant.
                   1957: 
                   1958: Forth does not perform type checking, neither at compile time, nor at
                   1959: run time.  If you use the wrong oeration, the data are interpreted
                   1960: incorrectly:
                   1961: 
                   1962: @example
                   1963: -1 u.
                   1964: @end example
                   1965: 
                   1966: If you have only experience with type-checked languages until now, and
                   1967: have heard how important type-checking is, don't panic!  In my
                   1968: experience (and that of other Forthers), type errors in Forth code are
                   1969: usually easy to find (once you get used to it), the increased vigilance
                   1970: of the programmer tends to catch some harder errors in addition to most
                   1971: type errors, and you never have to work around the type system, so in
                   1972: most situations the lack of type-checking seems to be a win (projects to
                   1973: add type checking to Forth have not caught on).
                   1974: 
                   1975: 
                   1976: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   1977: @section Factoring
1.66      anton    1978: @cindex factoring tutorial
1.48      anton    1979: 
                   1980: If you try to write longer definitions, you will soon find it hard to
                   1981: keep track of the stack contents.  Therefore, good Forth programmers
                   1982: tend to write only short definitions (e.g., three lines).  The art of
                   1983: finding meaningful short definitions is known as factoring (as in
                   1984: factoring polynomials).
                   1985: 
                   1986: Well-factored programs offer additional advantages: smaller, more
                   1987: general words, are easier to test and debug and can be reused more and
                   1988: better than larger, specialized words.
                   1989: 
                   1990: So, if you run into difficulties with stack management, when writing
                   1991: code, try to define meaningful factors for the word, and define the word
                   1992: in terms of those.  Even if a factor contains only two words, it is
                   1993: often helpful.
                   1994: 
1.65      anton    1995: Good factoring is not easy, and it takes some practice to get the knack
                   1996: for it; but even experienced Forth programmers often don't find the
                   1997: right solution right away, but only when rewriting the program.  So, if
                   1998: you don't come up with a good solution immediately, keep trying, don't
                   1999: despair.
1.48      anton    2000: 
                   2001: @c example !!
                   2002: 
                   2003: 
                   2004: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   2005: @section Designing the stack effect
1.66      anton    2006: @cindex Stack effect design, tutorial
                   2007: @cindex design of stack effects, tutorial
1.48      anton    2008: 
                   2009: In other languages you can use an arbitrary order of parameters for a
1.65      anton    2010: function; and since there is only one result, you don't have to deal with
1.48      anton    2011: the order of results, either.
                   2012: 
                   2013: In Forth (and other stack-based languages, e.g., Postscript) the
                   2014: parameter and result order of a definition is important and should be
                   2015: designed well.  The general guideline is to design the stack effect such
                   2016: that the word is simple to use in most cases, even if that complicates
                   2017: the implementation of the word.  Some concrete rules are:
                   2018: 
                   2019: @itemize @bullet
                   2020: 
                   2021: @item
                   2022: Words consume all of their parameters (e.g., @code{.}).
                   2023: 
                   2024: @item
                   2025: If there is a convention on the order of parameters (e.g., from
                   2026: mathematics or another programming language), stick with it (e.g.,
                   2027: @code{-}).
                   2028: 
                   2029: @item
                   2030: If one parameter usually requires only a short computation (e.g., it is
                   2031: a constant), pass it on the top of the stack.  Conversely, parameters
                   2032: that usually require a long sequence of code to compute should be passed
                   2033: as the bottom (i.e., first) parameter.  This makes the code easier to
                   2034: read, because reader does not need to keep track of the bottom item
                   2035: through a long sequence of code (or, alternatively, through stack
1.49      anton    2036: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    2037: address on top of the stack because it is usually simpler to compute
                   2038: than the stored value (often the address is just a variable).
                   2039: 
                   2040: @item
                   2041: Similarly, results that are usually consumed quickly should be returned
                   2042: on the top of stack, whereas a result that is often used in long
                   2043: computations should be passed as bottom result.  E.g., the file words
                   2044: like @code{open-file} return the error code on the top of stack, because
                   2045: it is usually consumed quickly by @code{throw}; moreover, the error code
                   2046: has to be checked before doing anything with the other results.
                   2047: 
                   2048: @end itemize
                   2049: 
                   2050: These rules are just general guidelines, don't lose sight of the overall
                   2051: goal to make the words easy to use.  E.g., if the convention rule
                   2052: conflicts with the computation-length rule, you might decide in favour
                   2053: of the convention if the word will be used rarely, and in favour of the
                   2054: computation-length rule if the word will be used frequently (because
                   2055: with frequent use the cost of breaking the computation-length rule would
                   2056: be quite high, and frequent use makes it easier to remember an
                   2057: unconventional order).
                   2058: 
                   2059: @c example !! structure package
                   2060: 
1.65      anton    2061: 
1.48      anton    2062: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   2063: @section Local Variables
1.66      anton    2064: @cindex local variables, tutorial
1.48      anton    2065: 
                   2066: You can define local variables (@emph{locals}) in a colon definition:
                   2067: 
                   2068: @example
                   2069: : swap @{ a b -- b a @}
                   2070:   b a ;
                   2071: 1 2 swap .s 2drop
                   2072: @end example
                   2073: 
                   2074: (If your Forth system does not support this syntax, include
                   2075: @file{compat/anslocals.fs} first).
                   2076: 
                   2077: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   2078: takes two cells from the stack, puts the top of stack in @code{b} and
                   2079: the next stack element in @code{a}.  @code{--} starts a comment ending
                   2080: with @code{@}}.  After the locals definition, using the name of the
                   2081: local will push its value on the stack.  You can leave the comment
                   2082: part (@code{-- b a}) away:
                   2083: 
                   2084: @example
                   2085: : swap ( x1 x2 -- x2 x1 )
                   2086:   @{ a b @} b a ;
                   2087: @end example
                   2088: 
                   2089: In Gforth you can have several locals definitions, anywhere in a colon
                   2090: definition; in contrast, in a standard program you can have only one
                   2091: locals definition per colon definition, and that locals definition must
                   2092: be outside any controll structure.
                   2093: 
                   2094: With locals you can write slightly longer definitions without running
                   2095: into stack trouble.  However, I recommend trying to write colon
                   2096: definitions without locals for exercise purposes to help you gain the
                   2097: essential factoring skills.
                   2098: 
                   2099: @assignment
                   2100: Rewrite your definitions until now with locals
                   2101: @endassignment
                   2102: 
1.66      anton    2103: Reference: @ref{Locals}.
                   2104: 
1.48      anton    2105: 
                   2106: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   2107: @section Conditional execution
1.66      anton    2108: @cindex conditionals, tutorial
                   2109: @cindex if, tutorial
1.48      anton    2110: 
                   2111: In Forth you can use control structures only inside colon definitions.
                   2112: An @code{if}-structure looks like this:
                   2113: 
                   2114: @example
                   2115: : abs ( n1 -- +n2 )
                   2116:     dup 0 < if
                   2117:         negate
                   2118:     endif ;
                   2119: 5 abs .
                   2120: -5 abs .
                   2121: @end example
                   2122: 
                   2123: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   2124: the following code is performed, otherwise execution continues after the
1.51      pazsan   2125: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.48      anton    2126: elements and prioduces a flag:
                   2127: 
                   2128: @example
                   2129: 1 2 < .
                   2130: 2 1 < .
                   2131: 1 1 < .
                   2132: @end example
                   2133: 
                   2134: Actually the standard name for @code{endif} is @code{then}.  This
                   2135: tutorial presents the examples using @code{endif}, because this is often
                   2136: less confusing for people familiar with other programming languages
                   2137: where @code{then} has a different meaning.  If your system does not have
                   2138: @code{endif}, define it with
                   2139: 
                   2140: @example
                   2141: : endif postpone then ; immediate
                   2142: @end example
                   2143: 
                   2144: You can optionally use an @code{else}-part:
                   2145: 
                   2146: @example
                   2147: : min ( n1 n2 -- n )
                   2148:   2dup < if
                   2149:     drop
                   2150:   else
                   2151:     nip
                   2152:   endif ;
                   2153: 2 3 min .
                   2154: 3 2 min .
                   2155: @end example
                   2156: 
                   2157: @assignment
                   2158: Write @code{min} without @code{else}-part (hint: what's the definition
                   2159: of @code{nip}?).
                   2160: @endassignment
                   2161: 
1.66      anton    2162: Reference: @ref{Selection}.
                   2163: 
1.48      anton    2164: 
                   2165: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   2166: @section Flags and Comparisons
1.66      anton    2167: @cindex flags tutorial
                   2168: @cindex comparison tutorial
1.48      anton    2169: 
                   2170: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   2171: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   2172: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   2173: treated as true flag.
                   2174: 
                   2175: @example
                   2176: false .
                   2177: true .
                   2178: true hex u. decimal
                   2179: @end example
                   2180: 
                   2181: Comparison words produce canonical flags:
                   2182: 
                   2183: @example
                   2184: 1 1 = .
                   2185: 1 0= .
                   2186: 0 1 < .
                   2187: 0 0 < .
                   2188: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   2189: -1 1 < .
                   2190: @end example
                   2191: 
1.66      anton    2192: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
                   2193: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
                   2194: these combinations are standard (for details see the standard,
                   2195: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48      anton    2196: 
                   2197: You can use @code{and or xor invert} can be used as operations on
                   2198: canonical flags.  Actually they are bitwise operations:
                   2199: 
                   2200: @example
                   2201: 1 2 and .
                   2202: 1 2 or .
                   2203: 1 3 xor .
                   2204: 1 invert .
                   2205: @end example
                   2206: 
                   2207: You can convert a zero/non-zero flag into a canonical flag with
                   2208: @code{0<>} (and complement it on the way with @code{0=}).
                   2209: 
                   2210: @example
                   2211: 1 0= .
                   2212: 1 0<> .
                   2213: @end example
                   2214: 
1.65      anton    2215: You can use the all-bits-set feature of canonical flags and the bitwise
1.48      anton    2216: operation of the Boolean operations to avoid @code{if}s:
                   2217: 
                   2218: @example
                   2219: : foo ( n1 -- n2 )
                   2220:   0= if
                   2221:     14
                   2222:   else
                   2223:     0
                   2224:   endif ;
                   2225: 0 foo .
                   2226: 1 foo .
                   2227: 
                   2228: : foo ( n1 -- n2 )
                   2229:   0= 14 and ;
                   2230: 0 foo .
                   2231: 1 foo .
                   2232: @end example
                   2233: 
                   2234: @assignment
                   2235: Write @code{min} without @code{if}.
                   2236: @endassignment
                   2237: 
1.66      anton    2238: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
                   2239: @ref{Bitwise operations}.
                   2240: 
1.48      anton    2241: 
                   2242: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   2243: @section General Loops
1.66      anton    2244: @cindex loops, indefinite, tutorial
1.48      anton    2245: 
                   2246: The endless loop is the most simple one:
                   2247: 
                   2248: @example
                   2249: : endless ( -- )
                   2250:   0 begin
                   2251:     dup . 1+
                   2252:   again ;
                   2253: endless
                   2254: @end example
                   2255: 
                   2256: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   2257: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   2258: 
                   2259: A loop with one exit at any place looks like this:
                   2260: 
                   2261: @example
                   2262: : log2 ( +n1 -- n2 )
                   2263: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2264:   assert( dup 0> )
                   2265:   2/ 0 begin
                   2266:     over 0> while
                   2267:       1+ swap 2/ swap
                   2268:   repeat
                   2269:   nip ;
                   2270: 7 log2 .
                   2271: 8 log2 .
                   2272: @end example
                   2273: 
                   2274: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   2275: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    2276: continues behind the @code{while}.  @code{Repeat} jumps back to
                   2277: @code{begin}, just like @code{again}.
                   2278: 
                   2279: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90      anton    2280: However, @code{2/} is not one of them; it shifts its argument right by
1.48      anton    2281: one bit (arithmetic shift right):
                   2282: 
                   2283: @example
                   2284: -5 2 / .
                   2285: -5 2/ .
                   2286: @end example
                   2287: 
                   2288: @code{assert(} is no standard word, but you can get it on systems other
                   2289: then Gforth by including @file{compat/assert.fs}.  You can see what it
                   2290: does by trying
                   2291: 
                   2292: @example
                   2293: 0 log2 .
                   2294: @end example
                   2295: 
                   2296: Here's a loop with an exit at the end:
                   2297: 
                   2298: @example
                   2299: : log2 ( +n1 -- n2 )
                   2300: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2301:   assert( dup 0 > )
                   2302:   -1 begin
                   2303:     1+ swap 2/ swap
                   2304:     over 0 <=
                   2305:   until
                   2306:   nip ;
                   2307: @end example
                   2308: 
                   2309: @code{Until} consumes a flag; if it is non-zero, execution continues at
                   2310: the @code{begin}, otherwise after the @code{until}.
                   2311: 
                   2312: @assignment
                   2313: Write a definition for computing the greatest common divisor.
                   2314: @endassignment
                   2315: 
1.66      anton    2316: Reference: @ref{Simple Loops}.
                   2317: 
1.48      anton    2318: 
                   2319: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   2320: @section Counted loops
1.66      anton    2321: @cindex loops, counted, tutorial
1.48      anton    2322: 
                   2323: @example
                   2324: : ^ ( n1 u -- n )
                   2325: \ n = the uth power of u1
                   2326:   1 swap 0 u+do
                   2327:     over *
                   2328:   loop
                   2329:   nip ;
                   2330: 3 2 ^ .
                   2331: 4 3 ^ .
                   2332: @end example
                   2333: 
                   2334: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   2335: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   2336: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2337: times (or not at all, if @code{u3-u4<0}).
                   2338: 
                   2339: You can see the stack effect design rules at work in the stack effect of
                   2340: the loop start words: Since the start value of the loop is more
                   2341: frequently constant than the end value, the start value is passed on
                   2342: the top-of-stack.
                   2343: 
                   2344: You can access the counter of a counted loop with @code{i}:
                   2345: 
                   2346: @example
                   2347: : fac ( u -- u! )
                   2348:   1 swap 1+ 1 u+do
                   2349:     i *
                   2350:   loop ;
                   2351: 5 fac .
                   2352: 7 fac .
                   2353: @end example
                   2354: 
                   2355: There is also @code{+do}, which expects signed numbers (important for
                   2356: deciding whether to enter the loop).
                   2357: 
                   2358: @assignment
                   2359: Write a definition for computing the nth Fibonacci number.
                   2360: @endassignment
                   2361: 
1.65      anton    2362: You can also use increments other than 1:
                   2363: 
                   2364: @example
                   2365: : up2 ( n1 n2 -- )
                   2366:   +do
                   2367:     i .
                   2368:   2 +loop ;
                   2369: 10 0 up2
                   2370: 
                   2371: : down2 ( n1 n2 -- )
                   2372:   -do
                   2373:     i .
                   2374:   2 -loop ;
                   2375: 0 10 down2
                   2376: @end example
1.48      anton    2377: 
1.66      anton    2378: Reference: @ref{Counted Loops}.
                   2379: 
1.48      anton    2380: 
                   2381: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2382: @section Recursion
1.66      anton    2383: @cindex recursion tutorial
1.48      anton    2384: 
                   2385: Usually the name of a definition is not visible in the definition; but
                   2386: earlier definitions are usually visible:
                   2387: 
                   2388: @example
                   2389: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
                   2390: : / ( n1 n2 -- n )
                   2391:   dup 0= if
                   2392:     -10 throw \ report division by zero
                   2393:   endif
                   2394:   /           \ old version
                   2395: ;
                   2396: 1 0 /
                   2397: @end example
                   2398: 
                   2399: For recursive definitions you can use @code{recursive} (non-standard) or
                   2400: @code{recurse}:
                   2401: 
                   2402: @example
                   2403: : fac1 ( n -- n! ) recursive
                   2404:  dup 0> if
                   2405:    dup 1- fac1 *
                   2406:  else
                   2407:    drop 1
                   2408:  endif ;
                   2409: 7 fac1 .
                   2410: 
                   2411: : fac2 ( n -- n! )
                   2412:  dup 0> if
                   2413:    dup 1- recurse *
                   2414:  else
                   2415:    drop 1
                   2416:  endif ;
                   2417: 8 fac2 .
                   2418: @end example
                   2419: 
                   2420: @assignment
                   2421: Write a recursive definition for computing the nth Fibonacci number.
                   2422: @endassignment
                   2423: 
1.66      anton    2424: Reference (including indirect recursion): @xref{Calls and returns}.
                   2425: 
1.48      anton    2426: 
                   2427: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2428: @section Leaving definitions or loops
1.66      anton    2429: @cindex leaving definitions, tutorial
                   2430: @cindex leaving loops, tutorial
1.48      anton    2431: 
                   2432: @code{EXIT} exits the current definition right away.  For every counted
                   2433: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2434: before the @code{EXIT}:
                   2435: 
                   2436: @c !! real examples
                   2437: @example
                   2438: : ...
                   2439:  ... u+do
                   2440:    ... if
                   2441:      ... unloop exit
                   2442:    endif
                   2443:    ...
                   2444:  loop
                   2445:  ... ;
                   2446: @end example
                   2447: 
                   2448: @code{LEAVE} leaves the innermost counted loop right away:
                   2449: 
                   2450: @example
                   2451: : ...
                   2452:  ... u+do
                   2453:    ... if
                   2454:      ... leave
                   2455:    endif
                   2456:    ...
                   2457:  loop
                   2458:  ... ;
                   2459: @end example
                   2460: 
1.65      anton    2461: @c !! example
1.48      anton    2462: 
1.66      anton    2463: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
                   2464: 
                   2465: 
1.48      anton    2466: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2467: @section Return Stack
1.66      anton    2468: @cindex return stack tutorial
1.48      anton    2469: 
                   2470: In addition to the data stack Forth also has a second stack, the return
                   2471: stack; most Forth systems store the return addresses of procedure calls
                   2472: there (thus its name).  Programmers can also use this stack:
                   2473: 
                   2474: @example
                   2475: : foo ( n1 n2 -- )
                   2476:  .s
                   2477:  >r .s
1.50      anton    2478:  r@@ .
1.48      anton    2479:  >r .s
1.50      anton    2480:  r@@ .
1.48      anton    2481:  r> .
1.50      anton    2482:  r@@ .
1.48      anton    2483:  r> . ;
                   2484: 1 2 foo
                   2485: @end example
                   2486: 
                   2487: @code{>r} takes an element from the data stack and pushes it onto the
                   2488: return stack; conversely, @code{r>} moves an elementm from the return to
                   2489: the data stack; @code{r@@} pushes a copy of the top of the return stack
                   2490: on the return stack.
                   2491: 
                   2492: Forth programmers usually use the return stack for storing data
                   2493: temporarily, if using the data stack alone would be too complex, and
                   2494: factoring and locals are not an option:
                   2495: 
                   2496: @example
                   2497: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2498:  rot >r rot r> ;
                   2499: @end example
                   2500: 
                   2501: The return address of the definition and the loop control parameters of
                   2502: counted loops usually reside on the return stack, so you have to take
                   2503: all items, that you have pushed on the return stack in a colon
                   2504: definition or counted loop, from the return stack before the definition
                   2505: or loop ends.  You cannot access items that you pushed on the return
                   2506: stack outside some definition or loop within the definition of loop.
                   2507: 
                   2508: If you miscount the return stack items, this usually ends in a crash:
                   2509: 
                   2510: @example
                   2511: : crash ( n -- )
                   2512:   >r ;
                   2513: 5 crash
                   2514: @end example
                   2515: 
                   2516: You cannot mix using locals and using the return stack (according to the
                   2517: standard; Gforth has no problem).  However, they solve the same
                   2518: problems, so this shouldn't be an issue.
                   2519: 
                   2520: @assignment
                   2521: Can you rewrite any of the definitions you wrote until now in a better
                   2522: way using the return stack?
                   2523: @endassignment
                   2524: 
1.66      anton    2525: Reference: @ref{Return stack}.
                   2526: 
1.48      anton    2527: 
                   2528: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2529: @section Memory
1.66      anton    2530: @cindex memory access/allocation tutorial
1.48      anton    2531: 
                   2532: You can create a global variable @code{v} with
                   2533: 
                   2534: @example
                   2535: variable v ( -- addr )
                   2536: @end example
                   2537: 
                   2538: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2539: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2540: values into this cell and @code{@@} (fetch) to load the value from the
                   2541: stack into memory:
                   2542: 
                   2543: @example
                   2544: v .
                   2545: 5 v ! .s
1.50      anton    2546: v @@ .
1.48      anton    2547: @end example
                   2548: 
1.65      anton    2549: You can see a raw dump of memory with @code{dump}:
                   2550: 
                   2551: @example
                   2552: v 1 cells .s dump
                   2553: @end example
                   2554: 
                   2555: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
                   2556: generally, address units (aus)) that @code{n1 cells} occupy.  You can
                   2557: also reserve more memory:
1.48      anton    2558: 
                   2559: @example
                   2560: create v2 20 cells allot
1.65      anton    2561: v2 20 cells dump
1.48      anton    2562: @end example
                   2563: 
1.65      anton    2564: creates a word @code{v2} and reserves 20 uninitialized cells; the
                   2565: address pushed by @code{v2} points to the start of these 20 cells.  You
                   2566: can use address arithmetic to access these cells:
1.48      anton    2567: 
                   2568: @example
                   2569: 3 v2 5 cells + !
1.65      anton    2570: v2 20 cells dump
1.48      anton    2571: @end example
                   2572: 
                   2573: You can reserve and initialize memory with @code{,}:
                   2574: 
                   2575: @example
                   2576: create v3
                   2577:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2578: v3 @@ .
                   2579: v3 cell+ @@ .
                   2580: v3 2 cells + @@ .
1.65      anton    2581: v3 5 cells dump
1.48      anton    2582: @end example
                   2583: 
                   2584: @assignment
                   2585: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2586: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2587: one at @code{addr cell+} etc.
                   2588: @endassignment
                   2589: 
                   2590: You can also reserve memory without creating a new word:
                   2591: 
                   2592: @example
1.60      anton    2593: here 10 cells allot .
                   2594: here .
1.48      anton    2595: @end example
                   2596: 
                   2597: @code{Here} pushes the start address of the memory area.  You should
                   2598: store it somewhere, or you will have a hard time finding the memory area
                   2599: again.
                   2600: 
                   2601: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2602: the system's data structures for words etc. on Gforth and most other
                   2603: Forth systems.  It is managed like a stack: You can free the memory that
                   2604: you have just @code{allot}ed with
                   2605: 
                   2606: @example
                   2607: -10 cells allot
1.60      anton    2608: here .
1.48      anton    2609: @end example
                   2610: 
                   2611: Note that you cannot do this if you have created a new word in the
                   2612: meantime (because then your @code{allot}ed memory is no longer on the
                   2613: top of the dictionary ``stack'').
                   2614: 
                   2615: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2616: freeing memory in any order:
                   2617: 
                   2618: @example
                   2619: 10 cells allocate throw .s
                   2620: 20 cells allocate throw .s
                   2621: swap
                   2622: free throw
                   2623: free throw
                   2624: @end example
                   2625: 
                   2626: The @code{throw}s deal with errors (e.g., out of memory).
                   2627: 
1.65      anton    2628: And there is also a
                   2629: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   2630: garbage collector}, which eliminates the need to @code{free} memory
                   2631: explicitly.
1.48      anton    2632: 
1.66      anton    2633: Reference: @ref{Memory}.
                   2634: 
1.48      anton    2635: 
                   2636: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2637: @section Characters and Strings
1.66      anton    2638: @cindex strings tutorial
                   2639: @cindex characters tutorial
1.48      anton    2640: 
                   2641: On the stack characters take up a cell, like numbers.  In memory they
                   2642: have their own size (one 8-bit byte on most systems), and therefore
                   2643: require their own words for memory access:
                   2644: 
                   2645: @example
                   2646: create v4 
                   2647:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2648: v4 4 chars + c@@ .
1.65      anton    2649: v4 5 chars dump
1.48      anton    2650: @end example
                   2651: 
                   2652: The preferred representation of strings on the stack is @code{addr
                   2653: u-count}, where @code{addr} is the address of the first character and
                   2654: @code{u-count} is the number of characters in the string.
                   2655: 
                   2656: @example
                   2657: v4 5 type
                   2658: @end example
                   2659: 
                   2660: You get a string constant with
                   2661: 
                   2662: @example
                   2663: s" hello, world" .s
                   2664: type
                   2665: @end example
                   2666: 
                   2667: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2668: is a normal Forth word and must be delimited with white space (try what
                   2669: happens when you remove the space).
                   2670: 
                   2671: However, this interpretive use of @code{s"} is quite restricted: the
                   2672: string exists only until the next call of @code{s"} (some Forth systems
                   2673: keep more than one of these strings, but usually they still have a
1.62      crook    2674: limited lifetime).
1.48      anton    2675: 
                   2676: @example
                   2677: s" hello," s" world" .s
                   2678: type
                   2679: type
                   2680: @end example
                   2681: 
1.62      crook    2682: You can also use @code{s"} in a definition, and the resulting
                   2683: strings then live forever (well, for as long as the definition):
1.48      anton    2684: 
                   2685: @example
                   2686: : foo s" hello," s" world" ;
                   2687: foo .s
                   2688: type
                   2689: type
                   2690: @end example
                   2691: 
                   2692: @assignment
                   2693: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2694: Implement @code{type ( addr u -- )}.
                   2695: @endassignment
                   2696: 
1.66      anton    2697: Reference: @ref{Memory Blocks}.
                   2698: 
                   2699: 
1.84      pazsan   2700: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48      anton    2701: @section Alignment
1.66      anton    2702: @cindex alignment tutorial
                   2703: @cindex memory alignment tutorial
1.48      anton    2704: 
                   2705: On many processors cells have to be aligned in memory, if you want to
                   2706: access them with @code{@@} and @code{!} (and even if the processor does
1.62      crook    2707: not require alignment, access to aligned cells is faster).
1.48      anton    2708: 
                   2709: @code{Create} aligns @code{here} (i.e., the place where the next
                   2710: allocation will occur, and that the @code{create}d word points to).
                   2711: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2712: address.  Adding a number of @code{cells} to an aligned address produces
                   2713: another aligned address.
                   2714: 
                   2715: However, address arithmetic involving @code{char+} and @code{chars} can
                   2716: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2717: a-addr )} produces the next aligned address:
                   2718: 
                   2719: @example
1.50      anton    2720: v3 char+ aligned .s @@ .
                   2721: v3 char+ .s @@ .
1.48      anton    2722: @end example
                   2723: 
                   2724: Similarly, @code{align} advances @code{here} to the next aligned
                   2725: address:
                   2726: 
                   2727: @example
                   2728: create v5 97 c,
                   2729: here .
                   2730: align here .
                   2731: 1000 ,
                   2732: @end example
                   2733: 
                   2734: Note that you should use aligned addresses even if your processor does
                   2735: not require them, if you want your program to be portable.
                   2736: 
1.66      anton    2737: Reference: @ref{Address arithmetic}.
                   2738: 
1.48      anton    2739: 
1.84      pazsan   2740: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
                   2741: @section Files
                   2742: @cindex files tutorial
                   2743: 
                   2744: This section gives a short introduction into how to use files inside
                   2745: Forth. It's broken up into five easy steps:
                   2746: 
                   2747: @enumerate 1
                   2748: @item Opened an ASCII text file for input
                   2749: @item Opened a file for output
                   2750: @item Read input file until string matched (or some other condition matched)
                   2751: @item Wrote some lines from input ( modified or not) to output
                   2752: @item Closed the files.
                   2753: @end enumerate
                   2754: 
                   2755: @subsection Open file for input
                   2756: 
                   2757: @example
                   2758: s" foo.in"  r/o open-file throw Value fd-in
                   2759: @end example
                   2760: 
                   2761: @subsection Create file for output
                   2762: 
                   2763: @example
                   2764: s" foo.out" w/o create-file throw Value fd-out
                   2765: @end example
                   2766: 
                   2767: The available file modes are r/o for read-only access, r/w for
                   2768: read-write access, and w/o for write-only access. You could open both
                   2769: files with r/w, too, if you like. All file words return error codes; for
                   2770: most applications, it's best to pass there error codes with @code{throw}
                   2771: to the outer error handler.
                   2772: 
                   2773: If you want words for opening and assigning, define them as follows:
                   2774: 
                   2775: @example
                   2776: 0 Value fd-in
                   2777: 0 Value fd-out
                   2778: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
                   2779: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
                   2780: @end example
                   2781: 
                   2782: Usage example:
                   2783: 
                   2784: @example
                   2785: s" foo.in" open-input
                   2786: s" foo.out" open-output
                   2787: @end example
                   2788: 
                   2789: @subsection Scan file for a particular line
                   2790: 
                   2791: @example
                   2792: 256 Constant max-line
                   2793: Create line-buffer  max-line 2 + allot
                   2794: 
                   2795: : scan-file ( addr u -- )
                   2796:   begin
                   2797:       line-buffer max-line fd-in read-line throw
                   2798:   while
                   2799:          >r 2dup line-buffer r> compare 0=
                   2800:      until
                   2801:   else
                   2802:      drop
                   2803:   then
                   2804:   2drop ;
                   2805: @end example
                   2806: 
                   2807: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94    ! anton    2808: the buffer at addr, and returns the number of bytes read, a flag that is
        !          2809: false when the end of file is reached, and an error code.
1.84      pazsan   2810: 
                   2811: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
                   2812: returns zero if both strings are equal. It returns a positive number if
                   2813: the first string is lexically greater, a negative if the second string
                   2814: is lexically greater.
                   2815: 
                   2816: We haven't seen this loop here; it has two exits. Since the @code{while}
                   2817: exits with the number of bytes read on the stack, we have to clean up
                   2818: that separately; that's after the @code{else}.
                   2819: 
                   2820: Usage example:
                   2821: 
                   2822: @example
                   2823: s" The text I search is here" scan-file
                   2824: @end example
                   2825: 
                   2826: @subsection Copy input to output
                   2827: 
                   2828: @example
                   2829: : copy-file ( -- )
                   2830:   begin
                   2831:       line-buffer max-line fd-in read-line throw
                   2832:   while
                   2833:       line-buffer swap fd-out write-file throw
                   2834:   repeat ;
                   2835: @end example
                   2836: 
                   2837: @subsection Close files
                   2838: 
                   2839: @example
                   2840: fd-in close-file throw
                   2841: fd-out close-file throw
                   2842: @end example
                   2843: 
                   2844: Likewise, you can put that into definitions, too:
                   2845: 
                   2846: @example
                   2847: : close-input ( -- )  fd-in close-file throw ;
                   2848: : close-output ( -- )  fd-out close-file throw ;
                   2849: @end example
                   2850: 
                   2851: @assignment
                   2852: How could you modify @code{copy-file} so that it copies until a second line is
                   2853: matched? Can you write a program that extracts a section of a text file,
                   2854: given the line that starts and the line that terminates that section?
                   2855: @endassignment
                   2856: 
                   2857: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48      anton    2858: @section Interpretation and Compilation Semantics and Immediacy
1.66      anton    2859: @cindex semantics tutorial
                   2860: @cindex interpretation semantics tutorial
                   2861: @cindex compilation semantics tutorial
                   2862: @cindex immediate, tutorial
1.48      anton    2863: 
                   2864: When a word is compiled, it behaves differently from being interpreted.
                   2865: E.g., consider @code{+}:
                   2866: 
                   2867: @example
                   2868: 1 2 + .
                   2869: : foo + ;
                   2870: @end example
                   2871: 
                   2872: These two behaviours are known as compilation and interpretation
                   2873: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2874: is to append the interpretation semantics to the currently defined word
                   2875: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2876: later, the interpretation semantics of @code{+} (i.e., adding two
                   2877: numbers) will be performed.
                   2878: 
                   2879: However, there are words with non-default compilation semantics, e.g.,
                   2880: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2881: change the compilation semantics of the last defined word to be equal to
                   2882: the interpretation semantics:
                   2883: 
                   2884: @example
                   2885: : [FOO] ( -- )
                   2886:  5 . ; immediate
                   2887: 
                   2888: [FOO]
                   2889: : bar ( -- )
                   2890:   [FOO] ;
                   2891: bar
                   2892: see bar
                   2893: @end example
                   2894: 
                   2895: Two conventions to mark words with non-default compilation semnatics are
                   2896: names with brackets (more frequently used) and to write them all in
                   2897: upper case (less frequently used).
                   2898: 
                   2899: In Gforth (and many other systems) you can also remove the
                   2900: interpretation semantics with @code{compile-only} (the compilation
                   2901: semantics is derived from the original interpretation semantics):
                   2902: 
                   2903: @example
                   2904: : flip ( -- )
                   2905:  6 . ; compile-only \ but not immediate
                   2906: flip
                   2907: 
                   2908: : flop ( -- )
                   2909:  flip ;
                   2910: flop
                   2911: @end example
                   2912: 
                   2913: In this example the interpretation semantics of @code{flop} is equal to
                   2914: the original interpretation semantics of @code{flip}.
                   2915: 
                   2916: The text interpreter has two states: in interpret state, it performs the
                   2917: interpretation semantics of words it encounters; in compile state, it
                   2918: performs the compilation semantics of these words.
                   2919: 
                   2920: Among other things, @code{:} switches into compile state, and @code{;}
                   2921: switches back to interpret state.  They contain the factors @code{]}
                   2922: (switch to compile state) and @code{[} (switch to interpret state), that
                   2923: do nothing but switch the state.
                   2924: 
                   2925: @example
                   2926: : xxx ( -- )
                   2927:   [ 5 . ]
                   2928: ;
                   2929: 
                   2930: xxx
                   2931: see xxx
                   2932: @end example
                   2933: 
                   2934: These brackets are also the source of the naming convention mentioned
                   2935: above.
                   2936: 
1.66      anton    2937: Reference: @ref{Interpretation and Compilation Semantics}.
                   2938: 
1.48      anton    2939: 
                   2940: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2941: @section Execution Tokens
1.66      anton    2942: @cindex execution tokens tutorial
                   2943: @cindex XT tutorial
1.48      anton    2944: 
                   2945: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2946: cell representing the interpretation semantics of a word.  You can
                   2947: execute this semantics with @code{execute}:
                   2948: 
                   2949: @example
                   2950: ' + .s
                   2951: 1 2 rot execute .
                   2952: @end example
                   2953: 
                   2954: The XT is similar to a function pointer in C.  However, parameter
                   2955: passing through the stack makes it a little more flexible:
                   2956: 
                   2957: @example
                   2958: : map-array ( ... addr u xt -- ... )
1.50      anton    2959: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2960: \ at addr and containing u elements
1.48      anton    2961:   @{ xt @}
                   2962:   cells over + swap ?do
1.50      anton    2963:     i @@ xt execute
1.48      anton    2964:   1 cells +loop ;
                   2965: 
                   2966: create a 3 , 4 , 2 , -1 , 4 ,
                   2967: a 5 ' . map-array .s
                   2968: 0 a 5 ' + map-array .
                   2969: s" max-n" environment? drop .s
                   2970: a 5 ' min map-array .
                   2971: @end example
                   2972: 
                   2973: You can use map-array with the XTs of words that consume one element
                   2974: more than they produce.  In theory you can also use it with other XTs,
                   2975: but the stack effect then depends on the size of the array, which is
                   2976: hard to understand.
                   2977: 
1.51      pazsan   2978: Since XTs are cell-sized, you can store them in memory and manipulate
                   2979: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2980: word with @code{compile,}:
                   2981: 
                   2982: @example
                   2983: : foo1 ( n1 n2 -- n )
                   2984:    [ ' + compile, ] ;
                   2985: see foo
                   2986: @end example
                   2987: 
                   2988: This is non-standard, because @code{compile,} has no compilation
                   2989: semantics in the standard, but it works in good Forth systems.  For the
                   2990: broken ones, use
                   2991: 
                   2992: @example
                   2993: : [compile,] compile, ; immediate
                   2994: 
                   2995: : foo1 ( n1 n2 -- n )
                   2996:    [ ' + ] [compile,] ;
                   2997: see foo
                   2998: @end example
                   2999: 
                   3000: @code{'} is a word with default compilation semantics; it parses the
                   3001: next word when its interpretation semantics are executed, not during
                   3002: compilation:
                   3003: 
                   3004: @example
                   3005: : foo ( -- xt )
                   3006:   ' ;
                   3007: see foo
                   3008: : bar ( ... "word" -- ... )
                   3009:   ' execute ;
                   3010: see bar
1.60      anton    3011: 1 2 bar + .
1.48      anton    3012: @end example
                   3013: 
                   3014: You often want to parse a word during compilation and compile its XT so
                   3015: it will be pushed on the stack at run-time.  @code{[']} does this:
                   3016: 
                   3017: @example
                   3018: : xt-+ ( -- xt )
                   3019:   ['] + ;
                   3020: see xt-+
                   3021: 1 2 xt-+ execute .
                   3022: @end example
                   3023: 
                   3024: Many programmers tend to see @code{'} and the word it parses as one
                   3025: unit, and expect it to behave like @code{[']} when compiled, and are
                   3026: confused by the actual behaviour.  If you are, just remember that the
                   3027: Forth system just takes @code{'} as one unit and has no idea that it is
                   3028: a parsing word (attempts to convenience programmers in this issue have
                   3029: usually resulted in even worse pitfalls, see
1.66      anton    3030: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
                   3031: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48      anton    3032: 
                   3033: Note that the state of the interpreter does not come into play when
1.51      pazsan   3034: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    3035: compile state, it still gives you the interpretation semantics.  And
                   3036: whatever that state is, @code{execute} performs the semantics
1.66      anton    3037: represented by the XT (i.e., for XTs produced with @code{'} the
                   3038: interpretation semantics).
                   3039: 
                   3040: Reference: @ref{Tokens for Words}.
1.48      anton    3041: 
                   3042: 
                   3043: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   3044: @section Exceptions
1.66      anton    3045: @cindex exceptions tutorial
1.48      anton    3046: 
                   3047: @code{throw ( n -- )} causes an exception unless n is zero.
                   3048: 
                   3049: @example
                   3050: 100 throw .s
                   3051: 0 throw .s
                   3052: @end example
                   3053: 
                   3054: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   3055: it catches exceptions and pushes the number of the exception on the
                   3056: stack (or 0, if the xt executed without exception).  If there was an
                   3057: exception, the stacks have the same depth as when entering @code{catch}:
                   3058: 
                   3059: @example
                   3060: .s
                   3061: 3 0 ' / catch .s
                   3062: 3 2 ' / catch .s
                   3063: @end example
                   3064: 
                   3065: @assignment
                   3066: Try the same with @code{execute} instead of @code{catch}.
                   3067: @endassignment
                   3068: 
                   3069: @code{Throw} always jumps to the dynamically next enclosing
                   3070: @code{catch}, even if it has to leave several call levels to achieve
                   3071: this:
                   3072: 
                   3073: @example
                   3074: : foo 100 throw ;
                   3075: : foo1 foo ." after foo" ;
1.51      pazsan   3076: : bar ['] foo1 catch ;
1.60      anton    3077: bar .
1.48      anton    3078: @end example
                   3079: 
                   3080: It is often important to restore a value upon leaving a definition, even
                   3081: if the definition is left through an exception.  You can ensure this
                   3082: like this:
                   3083: 
                   3084: @example
                   3085: : ...
                   3086:    save-x
1.51      pazsan   3087:    ['] word-changing-x catch ( ... n )
1.48      anton    3088:    restore-x
                   3089:    ( ... n ) throw ;
                   3090: @end example
                   3091: 
1.55      anton    3092: Gforth provides an alternative syntax in addition to @code{catch}:
1.48      anton    3093: @code{try ... recover ... endtry}.  If the code between @code{try} and
                   3094: @code{recover} has an exception, the stack depths are restored, the
                   3095: exception number is pushed on the stack, and the code between
                   3096: @code{recover} and @code{endtry} is performed.  E.g., the definition for
                   3097: @code{catch} is
                   3098: 
                   3099: @example
                   3100: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
                   3101:   try
                   3102:     execute 0
                   3103:   recover
                   3104:     nip
                   3105:   endtry ;
                   3106: @end example
                   3107: 
                   3108: The equivalent to the restoration code above is
                   3109: 
                   3110: @example
                   3111: : ...
                   3112:   save-x
                   3113:   try
1.92      anton    3114:     word-changing-x 0
                   3115:   recover endtry
1.48      anton    3116:   restore-x
                   3117:   throw ;
                   3118: @end example
                   3119: 
1.92      anton    3120: This works if @code{word-changing-x} does not change the stack depth,
                   3121: otherwise you should add some code between @code{recover} and
                   3122: @code{endtry} to balance the stack.
1.48      anton    3123: 
1.66      anton    3124: Reference: @ref{Exception Handling}.
                   3125: 
1.48      anton    3126: 
                   3127: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   3128: @section Defining Words
1.66      anton    3129: @cindex defining words tutorial
                   3130: @cindex does> tutorial
                   3131: @cindex create...does> tutorial
                   3132: 
                   3133: @c before semantics?
1.48      anton    3134: 
                   3135: @code{:}, @code{create}, and @code{variable} are definition words: They
                   3136: define other words.  @code{Constant} is another definition word:
                   3137: 
                   3138: @example
                   3139: 5 constant foo
                   3140: foo .
                   3141: @end example
                   3142: 
                   3143: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   3144: (floating point) with @code{variable} and @code{constant}.
                   3145: 
                   3146: You can also define your own defining words.  E.g.:
                   3147: 
                   3148: @example
                   3149: : variable ( "name" -- )
                   3150:   create 0 , ;
                   3151: @end example
                   3152: 
                   3153: You can also define defining words that create words that do something
                   3154: other than just producing their address:
                   3155: 
                   3156: @example
                   3157: : constant ( n "name" -- )
                   3158:   create ,
                   3159: does> ( -- n )
1.50      anton    3160:   ( addr ) @@ ;
1.48      anton    3161: 
                   3162: 5 constant foo
                   3163: foo .
                   3164: @end example
                   3165: 
                   3166: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   3167: @code{does>} replaces @code{;}, but it also does something else: It
                   3168: changes the last defined word such that it pushes the address of the
                   3169: body of the word and then performs the code after the @code{does>}
                   3170: whenever it is called.
                   3171: 
                   3172: In the example above, @code{constant} uses @code{,} to store 5 into the
                   3173: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   3174: the body onto the stack, then (in the code after the @code{does>})
                   3175: fetches the 5 from there.
                   3176: 
                   3177: The stack comment near the @code{does>} reflects the stack effect of the
                   3178: defined word, not the stack effect of the code after the @code{does>}
                   3179: (the difference is that the code expects the address of the body that
                   3180: the stack comment does not show).
                   3181: 
                   3182: You can use these definition words to do factoring in cases that involve
                   3183: (other) definition words.  E.g., a field offset is always added to an
                   3184: address.  Instead of defining
                   3185: 
                   3186: @example
                   3187: 2 cells constant offset-field1
                   3188: @end example
                   3189: 
                   3190: and using this like
                   3191: 
                   3192: @example
                   3193: ( addr ) offset-field1 +
                   3194: @end example
                   3195: 
                   3196: you can define a definition word
                   3197: 
                   3198: @example
                   3199: : simple-field ( n "name" -- )
                   3200:   create ,
                   3201: does> ( n1 -- n1+n )
1.50      anton    3202:   ( addr ) @@ + ;
1.48      anton    3203: @end example
1.21      crook    3204: 
1.48      anton    3205: Definition and use of field offsets now look like this:
1.21      crook    3206: 
1.48      anton    3207: @example
                   3208: 2 cells simple-field field1
1.60      anton    3209: create mystruct 4 cells allot
                   3210: mystruct .s field1 .s drop
1.48      anton    3211: @end example
1.21      crook    3212: 
1.48      anton    3213: If you want to do something with the word without performing the code
                   3214: after the @code{does>}, you can access the body of a @code{create}d word
                   3215: with @code{>body ( xt -- addr )}:
1.21      crook    3216: 
1.48      anton    3217: @example
                   3218: : value ( n "name" -- )
                   3219:   create ,
                   3220: does> ( -- n1 )
1.50      anton    3221:   @@ ;
1.48      anton    3222: : to ( n "name" -- )
                   3223:   ' >body ! ;
1.21      crook    3224: 
1.48      anton    3225: 5 value foo
                   3226: foo .
                   3227: 7 to foo
                   3228: foo .
                   3229: @end example
1.21      crook    3230: 
1.48      anton    3231: @assignment
                   3232: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   3233: XT (at the start the XT of @code{abort}), and upon execution
                   3234: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   3235: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   3236: recursion is one application of @code{defer}.
                   3237: @endassignment
1.29      crook    3238: 
1.66      anton    3239: Reference: @ref{User-defined Defining Words}.
                   3240: 
                   3241: 
1.48      anton    3242: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   3243: @section Arrays and Records
1.66      anton    3244: @cindex arrays tutorial
                   3245: @cindex records tutorial
                   3246: @cindex structs tutorial
1.29      crook    3247: 
1.48      anton    3248: Forth has no standard words for defining data structures such as arrays
                   3249: and records (structs in C terminology), but you can build them yourself
                   3250: based on address arithmetic.  You can also define words for defining
                   3251: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    3252: 
1.48      anton    3253: One of the first projects a Forth newcomer sets out upon when learning
                   3254: about defining words is an array defining word (possibly for
                   3255: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   3256: learn something from it.  However, don't be disappointed when you later
                   3257: learn that you have little use for these words (inappropriate use would
                   3258: be even worse).  I have not yet found a set of useful array words yet;
                   3259: the needs are just too diverse, and named, global arrays (the result of
                   3260: naive use of defining words) are often not flexible enough (e.g.,
1.66      anton    3261: consider how to pass them as parameters).  Another such project is a set
                   3262: of words to help dealing with strings.
1.29      crook    3263: 
1.48      anton    3264: On the other hand, there is a useful set of record words, and it has
                   3265: been defined in @file{compat/struct.fs}; these words are predefined in
                   3266: Gforth.  They are explained in depth elsewhere in this manual (see
                   3267: @pxref{Structures}).  The @code{simple-field} example above is
                   3268: simplified variant of fields in this package.
1.21      crook    3269: 
                   3270: 
1.48      anton    3271: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   3272: @section @code{POSTPONE}
1.66      anton    3273: @cindex postpone tutorial
1.21      crook    3274: 
1.48      anton    3275: You can compile the compilation semantics (instead of compiling the
                   3276: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    3277: 
1.48      anton    3278: @example
                   3279: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   3280:  POSTPONE + ; immediate
1.48      anton    3281: : foo ( n1 n2 -- n )
                   3282:  MY-+ ;
                   3283: 1 2 foo .
                   3284: see foo
                   3285: @end example
1.21      crook    3286: 
1.48      anton    3287: During the definition of @code{foo} the text interpreter performs the
                   3288: compilation semantics of @code{MY-+}, which performs the compilation
                   3289: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   3290: 
                   3291: This example also displays separate stack comments for the compilation
                   3292: semantics and for the stack effect of the compiled code.  For words with
                   3293: default compilation semantics these stack effects are usually not
                   3294: displayed; the stack effect of the compilation semantics is always
                   3295: @code{( -- )} for these words, the stack effect for the compiled code is
                   3296: the stack effect of the interpretation semantics.
                   3297: 
                   3298: Note that the state of the interpreter does not come into play when
                   3299: performing the compilation semantics in this way.  You can also perform
                   3300: it interpretively, e.g.:
                   3301: 
                   3302: @example
                   3303: : foo2 ( n1 n2 -- n )
                   3304:  [ MY-+ ] ;
                   3305: 1 2 foo .
                   3306: see foo
                   3307: @end example
1.21      crook    3308: 
1.48      anton    3309: However, there are some broken Forth systems where this does not always
1.62      crook    3310: work, and therefore this practice was been declared non-standard in
1.48      anton    3311: 1999.
                   3312: @c !! repair.fs
                   3313: 
                   3314: Here is another example for using @code{POSTPONE}:
1.44      crook    3315: 
1.48      anton    3316: @example
                   3317: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   3318:  POSTPONE negate POSTPONE + ; immediate compile-only
                   3319: : bar ( n1 n2 -- n )
                   3320:   MY-- ;
                   3321: 2 1 bar .
                   3322: see bar
                   3323: @end example
1.21      crook    3324: 
1.48      anton    3325: You can define @code{ENDIF} in this way:
1.21      crook    3326: 
1.48      anton    3327: @example
                   3328: : ENDIF ( Compilation: orig -- )
                   3329:   POSTPONE then ; immediate
                   3330: @end example
1.21      crook    3331: 
1.48      anton    3332: @assignment
                   3333: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   3334: @code{2dup}, but compiles @code{over over}.
                   3335: @endassignment
1.29      crook    3336: 
1.66      anton    3337: @c !! @xref{Macros} for reference
                   3338: 
                   3339: 
1.48      anton    3340: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3341: @section @code{Literal}
1.66      anton    3342: @cindex literal tutorial
1.29      crook    3343: 
1.48      anton    3344: You cannot @code{POSTPONE} numbers:
1.21      crook    3345: 
1.48      anton    3346: @example
                   3347: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3348: @end example
                   3349: 
1.48      anton    3350: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3351: 
1.48      anton    3352: @example
                   3353: : [FOO] ( compilation: --; run-time: -- n )
                   3354:   500 POSTPONE literal ; immediate
1.29      crook    3355: 
1.60      anton    3356: : flip [FOO] ;
1.48      anton    3357: flip .
                   3358: see flip
                   3359: @end example
1.29      crook    3360: 
1.48      anton    3361: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3362: semantics are executed) and pushes it at run-time (when the code it
                   3363: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3364: number computed at compile time into the current word:
1.29      crook    3365: 
1.48      anton    3366: @example
                   3367: : bar ( -- n )
                   3368:   [ 2 2 + ] literal ;
                   3369: see bar
                   3370: @end example
1.29      crook    3371: 
1.48      anton    3372: @assignment
                   3373: Write @code{]L} which allows writing the example above as @code{: bar (
                   3374: -- n ) [ 2 2 + ]L ;}
                   3375: @endassignment
                   3376: 
1.66      anton    3377: @c !! @xref{Macros} for reference
                   3378: 
1.48      anton    3379: 
                   3380: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3381: @section Advanced macros
1.66      anton    3382: @cindex macros, advanced tutorial
                   3383: @cindex run-time code generation, tutorial
1.48      anton    3384: 
1.66      anton    3385: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
                   3386: Execution Tokens}.  It frequently performs @code{execute}, a relatively
                   3387: expensive operation in some Forth implementations.  You can use
1.48      anton    3388: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3389: and produce a word that contains the word to be performed directly:
                   3390: 
                   3391: @c use ]] ... [[
                   3392: @example
                   3393: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3394: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3395: \ array beginning at addr and containing u elements
                   3396:   @{ xt @}
                   3397:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3398:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3399:   1 cells POSTPONE literal POSTPONE +loop ;
                   3400: 
                   3401: : sum-array ( addr u -- n )
                   3402:  0 rot rot [ ' + compile-map-array ] ;
                   3403: see sum-array
                   3404: a 5 sum-array .
                   3405: @end example
                   3406: 
                   3407: You can use the full power of Forth for generating the code; here's an
                   3408: example where the code is generated in a loop:
                   3409: 
                   3410: @example
                   3411: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3412: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3413:   POSTPONE tuck POSTPONE @@
1.48      anton    3414:   POSTPONE literal POSTPONE * POSTPONE +
                   3415:   POSTPONE swap POSTPONE cell+ ;
                   3416: 
                   3417: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3418: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3419:   0 postpone literal postpone swap
                   3420:   [ ' compile-vmul-step compile-map-array ]
                   3421:   postpone drop ;
                   3422: see compile-vmul
                   3423: 
                   3424: : a-vmul ( addr -- n )
1.51      pazsan   3425: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3426:  [ a 5 compile-vmul ] ;
                   3427: see a-vmul
                   3428: a a-vmul .
                   3429: @end example
                   3430: 
                   3431: This example uses @code{compile-map-array} to show off, but you could
1.66      anton    3432: also use @code{map-array} instead (try it now!).
1.48      anton    3433: 
                   3434: You can use this technique for efficient multiplication of large
                   3435: matrices.  In matrix multiplication, you multiply every line of one
                   3436: matrix with every column of the other matrix.  You can generate the code
                   3437: for one line once, and use it for every column.  The only downside of
                   3438: this technique is that it is cumbersome to recover the memory consumed
                   3439: by the generated code when you are done (and in more complicated cases
                   3440: it is not possible portably).
                   3441: 
1.66      anton    3442: @c !! @xref{Macros} for reference
                   3443: 
                   3444: 
1.48      anton    3445: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3446: @section Compilation Tokens
1.66      anton    3447: @cindex compilation tokens, tutorial
                   3448: @cindex CT, tutorial
1.48      anton    3449: 
                   3450: This section is Gforth-specific.  You can skip it.
                   3451: 
                   3452: @code{' word compile,} compiles the interpretation semantics.  For words
                   3453: with default compilation semantics this is the same as performing the
                   3454: compilation semantics.  To represent the compilation semantics of other
                   3455: words (e.g., words like @code{if} that have no interpretation
                   3456: semantics), Gforth has the concept of a compilation token (CT,
                   3457: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3458: You can perform the compilation semantics represented by a CT with
                   3459: @code{execute}:
1.29      crook    3460: 
1.48      anton    3461: @example
                   3462: : foo2 ( n1 n2 -- n )
                   3463:    [ comp' + execute ] ;
                   3464: see foo
                   3465: @end example
1.29      crook    3466: 
1.48      anton    3467: You can compile the compilation semantics represented by a CT with
                   3468: @code{postpone,}:
1.30      anton    3469: 
1.48      anton    3470: @example
                   3471: : foo3 ( -- )
                   3472:   [ comp' + postpone, ] ;
                   3473: see foo3
                   3474: @end example
1.30      anton    3475: 
1.51      pazsan   3476: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3477: @code{comp'} is particularly useful for words that have no
                   3478: interpretation semantics:
1.29      crook    3479: 
1.30      anton    3480: @example
1.48      anton    3481: ' if
1.60      anton    3482: comp' if .s 2drop
1.30      anton    3483: @end example
                   3484: 
1.66      anton    3485: Reference: @ref{Tokens for Words}.
                   3486: 
1.29      crook    3487: 
1.48      anton    3488: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3489: @section Wordlists and Search Order
1.66      anton    3490: @cindex wordlists tutorial
                   3491: @cindex search order, tutorial
1.48      anton    3492: 
                   3493: The dictionary is not just a memory area that allows you to allocate
                   3494: memory with @code{allot}, it also contains the Forth words, arranged in
                   3495: several wordlists.  When searching for a word in a wordlist,
                   3496: conceptually you start searching at the youngest and proceed towards
                   3497: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3498: you define a word with the same name as an older word, the new word
                   3499: shadows the older word.
                   3500: 
                   3501: Which wordlists are searched in which order is determined by the search
                   3502: order.  You can display the search order with @code{order}.  It displays
                   3503: first the search order, starting with the wordlist searched first, then
                   3504: it displays the wordlist that will contain newly defined words.
1.21      crook    3505: 
1.48      anton    3506: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3507: 
1.48      anton    3508: @example
                   3509: wordlist constant mywords
                   3510: @end example
1.21      crook    3511: 
1.48      anton    3512: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3513: defined words (the @emph{current} wordlist):
1.21      crook    3514: 
1.48      anton    3515: @example
                   3516: mywords set-current
                   3517: order
                   3518: @end example
1.26      crook    3519: 
1.48      anton    3520: Gforth does not display a name for the wordlist in @code{mywords}
                   3521: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3522: 
1.48      anton    3523: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3524: you want to put something into a specific wordlist without overall
                   3525: effect on the current wordlist, this typically looks like this:
1.21      crook    3526: 
1.48      anton    3527: @example
                   3528: get-current mywords set-current ( wid )
                   3529: create someword
                   3530: ( wid ) set-current
                   3531: @end example
1.21      crook    3532: 
1.48      anton    3533: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3534: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3535: searched wordlist is topmost.
1.21      crook    3536: 
1.48      anton    3537: @example
                   3538: get-order mywords swap 1+ set-order
                   3539: order
                   3540: @end example
1.21      crook    3541: 
1.48      anton    3542: Yes, the order of wordlists in the output of @code{order} is reversed
                   3543: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3544: 
1.48      anton    3545: @assignment
                   3546: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3547: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3548: removes the first searched wordlist from the search order.  Experiment
                   3549: with boundary conditions (you will see some crashes or situations that
                   3550: are hard or impossible to leave).
                   3551: @endassignment
1.21      crook    3552: 
1.48      anton    3553: The search order is a powerful foundation for providing features similar
                   3554: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3555: programs in this way has disadvantages for debugging and reuse/factoring
                   3556: that overcome the advantages in my experience (I don't do huge projects,
1.55      anton    3557: though).  These disadvantages are not so clear in other
1.82      anton    3558: languages/programming environments, because these languages are not so
1.48      anton    3559: strong in debugging and reuse.
1.21      crook    3560: 
1.66      anton    3561: @c !! example
                   3562: 
                   3563: Reference: @ref{Word Lists}.
1.21      crook    3564: 
1.29      crook    3565: @c ******************************************************************
1.48      anton    3566: @node Introduction, Words, Tutorial, Top
1.29      crook    3567: @comment node-name,     next,           previous, up
                   3568: @chapter An Introduction to ANS Forth
                   3569: @cindex Forth - an introduction
1.21      crook    3570: 
1.83      anton    3571: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
                   3572: that it is slower-paced in its examples, but uses them to dive deep into
                   3573: explaining Forth internals (not covered by the Tutorial).  Apart from
                   3574: that, this chapter covers far less material.  It is suitable for reading
                   3575: without using a computer.
                   3576: 
1.29      crook    3577: The primary purpose of this manual is to document Gforth. However, since
                   3578: Forth is not a widely-known language and there is a lack of up-to-date
                   3579: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3580: material.  For other sources of Forth-related
                   3581: information, see @ref{Forth-related information}.
1.21      crook    3582: 
1.29      crook    3583: The examples in this section should work on any ANS Forth; the
                   3584: output shown was produced using Gforth. Each example attempts to
                   3585: reproduce the exact output that Gforth produces. If you try out the
                   3586: examples (and you should), what you should type is shown @kbd{like this}
                   3587: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3588: that, where the example shows @key{RET} it means that you should
1.29      crook    3589: press the ``carriage return'' key. Unfortunately, some output formats for
                   3590: this manual cannot show the difference between @kbd{this} and
                   3591: @code{this} which will make trying out the examples harder (but not
                   3592: impossible).
1.21      crook    3593: 
1.29      crook    3594: Forth is an unusual language. It provides an interactive development
                   3595: environment which includes both an interpreter and compiler. Forth
                   3596: programming style encourages you to break a problem down into many
                   3597: @cindex factoring
                   3598: small fragments (@dfn{factoring}), and then to develop and test each
                   3599: fragment interactively. Forth advocates assert that breaking the
                   3600: edit-compile-test cycle used by conventional programming languages can
                   3601: lead to great productivity improvements.
1.21      crook    3602: 
1.29      crook    3603: @menu
1.67      anton    3604: * Introducing the Text Interpreter::  
                   3605: * Stacks and Postfix notation::  
                   3606: * Your first definition::       
                   3607: * How does that work?::         
                   3608: * Forth is written in Forth::   
                   3609: * Review - elements of a Forth system::  
                   3610: * Where to go next::            
                   3611: * Exercises::                   
1.29      crook    3612: @end menu
1.21      crook    3613: 
1.29      crook    3614: @comment ----------------------------------------------
                   3615: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3616: @section Introducing the Text Interpreter
                   3617: @cindex text interpreter
                   3618: @cindex outer interpreter
1.21      crook    3619: 
1.30      anton    3620: @c IMO this is too detailed and the pace is too slow for
                   3621: @c an introduction.  If you know German, take a look at
                   3622: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3623: @c to see how I do it - anton 
                   3624: 
1.44      crook    3625: @c nac-> Where I have accepted your comments 100% and modified the text
                   3626: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3627: @c response like this to attempt to rationalise what I have done. Of
                   3628: @c course, this is a very clumsy mechanism for something that would be
                   3629: @c done far more efficiently over a beer. Please delete any dialogue
                   3630: @c you consider closed.
                   3631: 
1.29      crook    3632: When you invoke the Forth image, you will see a startup banner printed
                   3633: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3634: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3635: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3636: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3637: about the text interpreter as you read through this chapter, for more
                   3638: detail @pxref{The Text Interpreter}).
1.21      crook    3639: 
1.29      crook    3640: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3641: input. Type a number and press the @key{RET} key:
1.21      crook    3642: 
1.26      crook    3643: @example
1.30      anton    3644: @kbd{45@key{RET}}  ok
1.26      crook    3645: @end example
1.21      crook    3646: 
1.29      crook    3647: Rather than give you a prompt to invite you to input something, the text
                   3648: interpreter prints a status message @i{after} it has processed a line
                   3649: of input. The status message in this case (``@code{ ok}'' followed by
                   3650: carriage-return) indicates that the text interpreter was able to process
                   3651: all of your input successfully. Now type something illegal:
                   3652: 
                   3653: @example
1.30      anton    3654: @kbd{qwer341@key{RET}}
1.29      crook    3655: :1: Undefined word
                   3656: qwer341
                   3657: ^^^^^^^
                   3658: $400D2BA8 Bounce
                   3659: $400DBDA8 no.extensions
                   3660: @end example
1.23      crook    3661: 
1.29      crook    3662: The exact text, other than the ``Undefined word'' may differ slightly on
                   3663: your system, but the effect is the same; when the text interpreter
                   3664: detects an error, it discards any remaining text on a line, resets
1.49      anton    3665: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
                   3666: messages}.
1.23      crook    3667: 
1.29      crook    3668: The text interpreter waits for you to press carriage-return, and then
                   3669: processes your input line. Starting at the beginning of the line, it
                   3670: breaks the line into groups of characters separated by spaces. For each
                   3671: group of characters in turn, it makes two attempts to do something:
1.23      crook    3672: 
1.29      crook    3673: @itemize @bullet
                   3674: @item
1.44      crook    3675: @cindex name dictionary
1.29      crook    3676: It tries to treat it as a command. It does this by searching a @dfn{name
                   3677: dictionary}. If the group of characters matches an entry in the name
                   3678: dictionary, the name dictionary provides the text interpreter with
                   3679: information that allows the text interpreter perform some actions. In
                   3680: Forth jargon, we say that the group
                   3681: @cindex word
                   3682: @cindex definition
                   3683: @cindex execution token
                   3684: @cindex xt
                   3685: of characters names a @dfn{word}, that the dictionary search returns an
                   3686: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3687: word, and that the text interpreter executes the xt. Often, the terms
                   3688: @dfn{word} and @dfn{definition} are used interchangeably.
                   3689: @item
                   3690: If the text interpreter fails to find a match in the name dictionary, it
                   3691: tries to treat the group of characters as a number in the current number
                   3692: base (when you start up Forth, the current number base is base 10). If
                   3693: the group of characters legitimately represents a number, the text
                   3694: interpreter pushes the number onto a stack (we'll learn more about that
                   3695: in the next section).
                   3696: @end itemize
1.23      crook    3697: 
1.29      crook    3698: If the text interpreter is unable to do either of these things with any
                   3699: group of characters, it discards the group of characters and the rest of
                   3700: the line, then prints an error message. If the text interpreter reaches
                   3701: the end of the line without error, it prints the status message ``@code{ ok}''
                   3702: followed by carriage-return.
1.21      crook    3703: 
1.29      crook    3704: This is the simplest command we can give to the text interpreter:
1.23      crook    3705: 
                   3706: @example
1.30      anton    3707: @key{RET}  ok
1.23      crook    3708: @end example
1.21      crook    3709: 
1.29      crook    3710: The text interpreter did everything we asked it to do (nothing) without
                   3711: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3712: command:
1.21      crook    3713: 
1.23      crook    3714: @example
1.30      anton    3715: @kbd{12 dup fred dup@key{RET}}
1.29      crook    3716: :1: Undefined word
                   3717: 12 dup fred dup
                   3718:        ^^^^
                   3719: $400D2BA8 Bounce
                   3720: $400DBDA8 no.extensions
1.23      crook    3721: @end example
1.21      crook    3722: 
1.29      crook    3723: When you press the carriage-return key, the text interpreter starts to
                   3724: work its way along the line:
1.21      crook    3725: 
1.29      crook    3726: @itemize @bullet
                   3727: @item
                   3728: When it gets to the space after the @code{2}, it takes the group of
                   3729: characters @code{12} and looks them up in the name
                   3730: dictionary@footnote{We can't tell if it found them or not, but assume
                   3731: for now that it did not}. There is no match for this group of characters
                   3732: in the name dictionary, so it tries to treat them as a number. It is
                   3733: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3734: (whatever that means).
                   3735: @item
                   3736: The text interpreter resumes scanning the line and gets the next group
                   3737: of characters, @code{dup}. It looks it up in the name dictionary and
                   3738: (you'll have to take my word for this) finds it, and executes the word
                   3739: @code{dup} (whatever that means).
                   3740: @item
                   3741: Once again, the text interpreter resumes scanning the line and gets the
                   3742: group of characters @code{fred}. It looks them up in the name
                   3743: dictionary, but can't find them. It tries to treat them as a number, but
                   3744: they don't represent any legal number.
                   3745: @end itemize
1.21      crook    3746: 
1.29      crook    3747: At this point, the text interpreter gives up and prints an error
                   3748: message. The error message shows exactly how far the text interpreter
                   3749: got in processing the line. In particular, it shows that the text
                   3750: interpreter made no attempt to do anything with the final character
                   3751: group, @code{dup}, even though we have good reason to believe that the
                   3752: text interpreter would have no problem looking that word up and
                   3753: executing it a second time.
1.21      crook    3754: 
                   3755: 
1.29      crook    3756: @comment ----------------------------------------------
                   3757: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3758: @section Stacks, postfix notation and parameter passing
                   3759: @cindex text interpreter
                   3760: @cindex outer interpreter
1.21      crook    3761: 
1.29      crook    3762: In procedural programming languages (like C and Pascal), the
                   3763: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3764: functions or procedures are called with @dfn{explicit parameters}. For
                   3765: example, in C we might write:
1.21      crook    3766: 
1.23      crook    3767: @example
1.29      crook    3768: total = total + new_volume(length,height,depth);
1.23      crook    3769: @end example
1.21      crook    3770: 
1.23      crook    3771: @noindent
1.29      crook    3772: where new_volume is a function-call to another piece of code, and total,
                   3773: length, height and depth are all variables. length, height and depth are
                   3774: parameters to the function-call.
1.21      crook    3775: 
1.29      crook    3776: In Forth, the equivalent of the function or procedure is the
                   3777: @dfn{definition} and parameters are implicitly passed between
                   3778: definitions using a shared stack that is visible to the
                   3779: programmer. Although Forth does support variables, the existence of the
                   3780: stack means that they are used far less often than in most other
                   3781: programming languages. When the text interpreter encounters a number, it
                   3782: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3783: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3784: used for any operation is implied unambiguously by the operation being
                   3785: performed. The stack used for all integer operations is called the @dfn{data
                   3786: stack} and, since this is the stack used most commonly, references to
                   3787: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3788: 
1.29      crook    3789: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3790: 
1.23      crook    3791: @example
1.30      anton    3792: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3793: @end example
1.21      crook    3794: 
1.29      crook    3795: Then this instructs the text interpreter to placed three numbers on the
                   3796: (data) stack. An analogy for the behaviour of the stack is to take a
                   3797: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3798: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3799: you take a card off the pile then, unless you're prepared to fiddle a
                   3800: bit, the card that you take off will be the 3 (``first-out''). The
                   3801: number that will be first-out of the stack is called the @dfn{top of
                   3802: stack}, which
                   3803: @cindex TOS definition
                   3804: is often abbreviated to @dfn{TOS}.
1.21      crook    3805: 
1.29      crook    3806: To understand how parameters are passed in Forth, consider the
                   3807: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3808: be surprised to learn that this definition performs addition. More
                   3809: precisely, it adds two number together and produces a result. Where does
                   3810: it get the two numbers from? It takes the top two numbers off the
                   3811: stack. Where does it place the result? On the stack. You can act-out the
                   3812: behaviour of @code{+} with your playing cards like this:
1.21      crook    3813: 
                   3814: @itemize @bullet
                   3815: @item
1.29      crook    3816: Pick up two cards from the stack on the table
1.21      crook    3817: @item
1.29      crook    3818: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3819: numbers''
1.21      crook    3820: @item
1.29      crook    3821: Decide that the answer is 5
1.21      crook    3822: @item
1.29      crook    3823: Shuffle the two cards back into the pack and find a 5
1.21      crook    3824: @item
1.29      crook    3825: Put a 5 on the remaining ace that's on the table.
1.21      crook    3826: @end itemize
                   3827: 
1.29      crook    3828: If you don't have a pack of cards handy but you do have Forth running,
                   3829: you can use the definition @code{.s} to show the current state of the stack,
                   3830: without affecting the stack. Type:
1.21      crook    3831: 
                   3832: @example
1.30      anton    3833: @kbd{clearstack 1 2 3@key{RET}} ok
                   3834: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3835: @end example
                   3836: 
1.29      crook    3837: The text interpreter looks up the word @code{clearstack} and executes
                   3838: it; it tidies up the stack and removes any entries that may have been
                   3839: left on it by earlier examples. The text interpreter pushes each of the
                   3840: three numbers in turn onto the stack. Finally, the text interpreter
                   3841: looks up the word @code{.s} and executes it. The effect of executing
                   3842: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3843: followed by a list of all the items on the stack; the item on the far
                   3844: right-hand side is the TOS.
1.21      crook    3845: 
1.29      crook    3846: You can now type:
1.21      crook    3847: 
1.29      crook    3848: @example
1.30      anton    3849: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3850: @end example
1.21      crook    3851: 
1.29      crook    3852: @noindent
                   3853: which is correct; there are now 2 items on the stack and the result of
                   3854: the addition is 5.
1.23      crook    3855: 
1.29      crook    3856: If you're playing with cards, try doing a second addition: pick up the
                   3857: two cards, work out that their sum is 6, shuffle them into the pack,
                   3858: look for a 6 and place that on the table. You now have just one item on
                   3859: the stack. What happens if you try to do a third addition? Pick up the
                   3860: first card, pick up the second card -- ah! There is no second card. This
                   3861: is called a @dfn{stack underflow} and consitutes an error. If you try to
                   3862: do the same thing with Forth it will report an error (probably a Stack
                   3863: Underflow or an Invalid Memory Address error).
1.23      crook    3864: 
1.29      crook    3865: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3866: which simply accepts that there is a finite amount of storage space
                   3867: reserved for the stack. To stretch the playing card analogy, if you had
                   3868: enough packs of cards and you piled the cards up on the table, you would
                   3869: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3870: allows you to set the maximum size of the stacks. In general, the only
                   3871: time that you will get a stack overflow is because a definition has a
                   3872: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3873: 
1.29      crook    3874: There's one final use for the playing card analogy. If you model your
                   3875: stack using a pack of playing cards, the maximum number of items on
                   3876: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3877: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3878: possible numbers are positive integer numbers 1 through 13; you can't
                   3879: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3880: think about some of the cards, you can accommodate different
                   3881: numbers. For example, you could think of the Jack as representing 0,
                   3882: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3883: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3884: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3885: 
1.29      crook    3886: In that analogy, the limit was the amount of information that a single
                   3887: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3888: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3889: implementation dependent and affects the maximum value that a stack
                   3890: entry can hold. A Standard Forth provides a cell size of at least
                   3891: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3892: 
1.29      crook    3893: Forth does not do any type checking for you, so you are free to
                   3894: manipulate and combine stack items in any way you wish. A convenient way
                   3895: of treating stack items is as 2's complement signed integers, and that
                   3896: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3897: 
1.29      crook    3898: @example
1.30      anton    3899: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3900: @end example
1.21      crook    3901: 
1.29      crook    3902: If you use numbers and definitions like @code{+} in order to turn Forth
                   3903: into a great big pocket calculator, you will realise that it's rather
                   3904: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3905: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3906: result). The terminology used to describe this difference is to say that
                   3907: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3908: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3909: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3910: 
1.29      crook    3911: Whilst postfix notation might look confusing to begin with, it has
                   3912: several important advantages:
1.21      crook    3913: 
1.23      crook    3914: @itemize @bullet
                   3915: @item
1.29      crook    3916: it is unambiguous
1.23      crook    3917: @item
1.29      crook    3918: it is more concise
1.23      crook    3919: @item
1.29      crook    3920: it fits naturally with a stack-based system
1.23      crook    3921: @end itemize
1.21      crook    3922: 
1.29      crook    3923: To examine these claims in more detail, consider these sums:
1.21      crook    3924: 
1.29      crook    3925: @example
                   3926: 6 + 5 * 4 =
                   3927: 4 * 5 + 6 =
                   3928: @end example
1.21      crook    3929: 
1.29      crook    3930: If you're just learning maths or your maths is very rusty, you will
                   3931: probably come up with the answer 44 for the first and 26 for the
                   3932: second. If you are a bit of a whizz at maths you will remember the
                   3933: @i{convention} that multiplication takes precendence over addition, and
                   3934: you'd come up with the answer 26 both times. To explain the answer 26
                   3935: to someone who got the answer 44, you'd probably rewrite the first sum
                   3936: like this:
1.21      crook    3937: 
1.29      crook    3938: @example
                   3939: 6 + (5 * 4) =
                   3940: @end example
1.21      crook    3941: 
1.29      crook    3942: If what you really wanted was to perform the addition before the
                   3943: multiplication, you would have to use parentheses to force it.
1.21      crook    3944: 
1.29      crook    3945: If you did the first two sums on a pocket calculator you would probably
                   3946: get the right answers, unless you were very cautious and entered them using
                   3947: these keystroke sequences:
1.21      crook    3948: 
1.29      crook    3949: 6 + 5 = * 4 =
                   3950: 4 * 5 = + 6 =
1.21      crook    3951: 
1.29      crook    3952: Postfix notation is unambiguous because the order that the operators
                   3953: are applied is always explicit; that also means that parentheses are
                   3954: never required. The operators are @i{active} (the act of quoting the
                   3955: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3956: 
1.29      crook    3957: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3958: equivalent ways:
1.26      crook    3959: 
                   3960: @example
1.29      crook    3961: 6 5 4 * +      or:
                   3962: 5 4 * 6 +
1.26      crook    3963: @end example
1.23      crook    3964: 
1.29      crook    3965: An important thing that you should notice about this notation is that
                   3966: the @i{order} of the numbers does not change; if you want to subtract
                   3967: 2 from 10 you type @code{10 2 -}.
1.1       anton    3968: 
1.29      crook    3969: The reason that Forth uses postfix notation is very simple to explain: it
                   3970: makes the implementation extremely simple, and it follows naturally from
                   3971: using the stack as a mechanism for passing parameters. Another way of
                   3972: thinking about this is to realise that all Forth definitions are
                   3973: @i{active}; they execute as they are encountered by the text
                   3974: interpreter. The result of this is that the syntax of Forth is trivially
                   3975: simple.
1.1       anton    3976: 
                   3977: 
                   3978: 
1.29      crook    3979: @comment ----------------------------------------------
                   3980: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3981: @section Your first Forth definition
                   3982: @cindex first definition
1.1       anton    3983: 
1.29      crook    3984: Until now, the examples we've seen have been trivial; we've just been
                   3985: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3986: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3987: again@footnote{That's not quite true. If you press the up-arrow key on
                   3988: your keyboard you should be able to scroll back to any earlier command,
                   3989: edit it and re-enter it.} In this section we'll see how to add new
                   3990: words to Forth's vocabulary.
1.1       anton    3991: 
1.29      crook    3992: The easiest way to create a new word is to use a @dfn{colon
                   3993: definition}. We'll define a few and try them out before worrying too
                   3994: much about how they work. Try typing in these examples; be careful to
                   3995: copy the spaces accurately:
1.1       anton    3996: 
1.29      crook    3997: @example
                   3998: : add-two 2 + . ;
                   3999: : greet ." Hello and welcome" ;
                   4000: : demo 5 add-two ;
                   4001: @end example
1.1       anton    4002: 
1.29      crook    4003: @noindent
                   4004: Now try them out:
1.1       anton    4005: 
1.29      crook    4006: @example
1.30      anton    4007: @kbd{greet@key{RET}} Hello and welcome  ok
                   4008: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   4009: @kbd{4 add-two@key{RET}} 6  ok
                   4010: @kbd{demo@key{RET}} 7  ok
                   4011: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    4012: @end example
1.1       anton    4013: 
1.29      crook    4014: The first new thing that we've introduced here is the pair of words
                   4015: @code{:} and @code{;}. These are used to start and terminate a new
                   4016: definition, respectively. The first word after the @code{:} is the name
                   4017: for the new definition.
1.1       anton    4018: 
1.29      crook    4019: As you can see from the examples, a definition is built up of words that
                   4020: have already been defined; Forth makes no distinction between
                   4021: definitions that existed when you started the system up, and those that
                   4022: you define yourself.
1.1       anton    4023: 
1.29      crook    4024: The examples also introduce the words @code{.} (dot), @code{."}
                   4025: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   4026: the stack and displays it. It's like @code{.s} except that it only
                   4027: displays the top item of the stack and it is destructive; after it has
                   4028: executed, the number is no longer on the stack. There is always one
                   4029: space printed after the number, and no spaces before it. Dot-quote
                   4030: defines a string (a sequence of characters) that will be printed when
                   4031: the word is executed. The string can contain any printable characters
                   4032: except @code{"}. A @code{"} has a special function; it is not a Forth
                   4033: word but it acts as a delimiter (the way that delimiters work is
                   4034: described in the next section). Finally, @code{dup} duplicates the value
                   4035: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    4036: 
1.29      crook    4037: We already know that the text interpreter searches through the
                   4038: dictionary to locate names. If you've followed the examples earlier, you
                   4039: will already have a definition called @code{add-two}. Lets try modifying
                   4040: it by typing in a new definition:
1.1       anton    4041: 
1.29      crook    4042: @example
1.30      anton    4043: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    4044: @end example
1.5       anton    4045: 
1.29      crook    4046: Forth recognised that we were defining a word that already exists, and
                   4047: printed a message to warn us of that fact. Let's try out the new
                   4048: definition:
1.5       anton    4049: 
1.29      crook    4050: @example
1.30      anton    4051: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    4052: @end example
1.1       anton    4053: 
1.29      crook    4054: @noindent
                   4055: All that we've actually done here, though, is to create a new
                   4056: definition, with a particular name. The fact that there was already a
                   4057: definition with the same name did not make any difference to the way
                   4058: that the new definition was created (except that Forth printed a warning
                   4059: message). The old definition of add-two still exists (try @code{demo}
                   4060: again to see that this is true). Any new definition will use the new
                   4061: definition of @code{add-two}, but old definitions continue to use the
                   4062: version that already existed at the time that they were @code{compiled}.
1.1       anton    4063: 
1.29      crook    4064: Before you go on to the next section, try defining and redefining some
                   4065: words of your own.
1.1       anton    4066: 
1.29      crook    4067: @comment ----------------------------------------------
                   4068: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   4069: @section How does that work?
                   4070: @cindex parsing words
1.1       anton    4071: 
1.30      anton    4072: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   4073: 
                   4074: @c Is it a good idea to talk about the interpretation semantics of a
                   4075: @c number? We don't have an xt to go along with it. - anton
                   4076: 
                   4077: @c Now that I have eliminated execution semantics, I wonder if it would not
                   4078: @c be better to keep them (or add run-time semantics), to make it easier to
                   4079: @c explain what compilation semantics usually does. - anton
                   4080: 
1.44      crook    4081: @c nac-> I removed the term ``default compilation sematics'' from the
                   4082: @c introductory chapter. Removing ``execution semantics'' was making
                   4083: @c everything simpler to explain, then I think the use of this term made
                   4084: @c everything more complex again. I replaced it with ``default
                   4085: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   4086: @c ``a definition that has neither the immediate nor the compile-only
1.83      anton    4087: @c flag set''.
                   4088: 
                   4089: @c anton: I have eliminated default semantics (except in one place where it
                   4090: @c means "default interpretation and compilation semantics"), because it
                   4091: @c makes no sense in the presence of combined words.  I reverted to
                   4092: @c "execution semantics" where necessary.
                   4093: 
                   4094: @c nac-> I reworded big chunks of the ``how does that work''
1.44      crook    4095: @c section (and, unusually for me, I think I even made it shorter!).  See
                   4096: @c what you think -- I know I have not addressed your primary concern
                   4097: @c that it is too heavy-going for an introduction. From what I understood
                   4098: @c of your course notes it looks as though they might be a good framework. 
                   4099: @c Things that I've tried to capture here are some things that came as a
                   4100: @c great revelation here when I first understood them. Also, I like the
                   4101: @c fact that a very simple code example shows up almost all of the issues
                   4102: @c that you need to understand to see how Forth works. That's unique and
                   4103: @c worthwhile to emphasise.
                   4104: 
1.83      anton    4105: @c anton: I think it's a good idea to present the details, especially those
                   4106: @c that you found to be a revelation, and probably the tutorial tries to be
                   4107: @c too superficial and does not get some of the things across that make
                   4108: @c Forth special.  I do believe that most of the time these things should
                   4109: @c be discussed at the end of a section or in separate sections instead of
                   4110: @c in the middle of a section (e.g., the stuff you added in "User-defined
                   4111: @c defining words" leads in a completely different direction from the rest
                   4112: @c of the section).
                   4113: 
1.29      crook    4114: Now we're going to take another look at the definition of @code{add-two}
                   4115: from the previous section. From our knowledge of the way that the text
                   4116: interpreter works, we would have expected this result when we tried to
                   4117: define @code{add-two}:
1.21      crook    4118: 
1.29      crook    4119: @example
1.44      crook    4120: @kbd{: add-two 2 + . ;@key{RET}}
1.29      crook    4121:   ^^^^^^^
                   4122: Error: Undefined word
                   4123: @end example
1.28      crook    4124: 
1.29      crook    4125: The reason that this didn't happen is bound up in the way that @code{:}
                   4126: works. The word @code{:} does two special things. The first special
                   4127: thing that it does prevents the text interpreter from ever seeing the
                   4128: characters @code{add-two}. The text interpreter uses a variable called
                   4129: @cindex modifying >IN
1.44      crook    4130: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    4131: input line. When it encounters the word @code{:} it behaves in exactly
                   4132: the same way as it does for any other word; it looks it up in the name
                   4133: dictionary, finds its xt and executes it. When @code{:} executes, it
                   4134: looks at the input buffer, finds the word @code{add-two} and advances the
                   4135: value of @code{>IN} to point past it. It then does some other stuff
                   4136: associated with creating the new definition (including creating an entry
                   4137: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   4138: completes, control returns to the text interpreter, which is oblivious
                   4139: to the fact that it has been tricked into ignoring part of the input
                   4140: line.
1.21      crook    4141: 
1.29      crook    4142: @cindex parsing words
                   4143: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   4144: prevent the text interpreter from acting on the whole of the input line
                   4145: -- are called @dfn{parsing words}.
1.21      crook    4146: 
1.29      crook    4147: @cindex @code{state} - effect on the text interpreter
                   4148: @cindex text interpreter - effect of state
                   4149: The second special thing that @code{:} does is change the value of a
                   4150: variable called @code{state}, which affects the way that the text
                   4151: interpreter behaves. When Gforth starts up, @code{state} has the value
                   4152: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   4153: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    4154: the text interpreter is said to be @dfn{compiling}.
                   4155: 
                   4156: In this example, the text interpreter is compiling when it processes the
                   4157: string ``@code{2 + . ;}''. It still breaks the string down into
                   4158: character sequences in the same way. However, instead of pushing the
                   4159: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   4160: into the definition of @code{add-two} that will make the number @code{2} get
                   4161: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   4162: the behaviours of @code{+} and @code{.} are also compiled into the
                   4163: definition.
                   4164: 
                   4165: One category of words don't get compiled. These so-called @dfn{immediate
                   4166: words} get executed (performed @i{now}) regardless of whether the text
                   4167: interpreter is interpreting or compiling. The word @code{;} is an
                   4168: immediate word. Rather than being compiled into the definition, it
                   4169: executes. Its effect is to terminate the current definition, which
                   4170: includes changing the value of @code{state} back to 0.
                   4171: 
                   4172: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   4173: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   4174: definition.
1.28      crook    4175: 
1.30      anton    4176: In Forth, every word or number can be described in terms of two
1.29      crook    4177: properties:
1.28      crook    4178: 
                   4179: @itemize @bullet
                   4180: @item
1.29      crook    4181: @cindex interpretation semantics
1.44      crook    4182: Its @dfn{interpretation semantics} describe how it will behave when the
                   4183: text interpreter encounters it in @dfn{interpret} state. The
                   4184: interpretation semantics of a word are represented by an @dfn{execution
                   4185: token}.
1.28      crook    4186: @item
1.29      crook    4187: @cindex compilation semantics
1.44      crook    4188: Its @dfn{compilation semantics} describe how it will behave when the
                   4189: text interpreter encounters it in @dfn{compile} state. The compilation
                   4190: semantics of a word are represented in an implementation-dependent way;
                   4191: Gforth uses a @dfn{compilation token}.
1.29      crook    4192: @end itemize
                   4193: 
                   4194: @noindent
                   4195: Numbers are always treated in a fixed way:
                   4196: 
                   4197: @itemize @bullet
1.28      crook    4198: @item
1.44      crook    4199: When the number is @dfn{interpreted}, its behaviour is to push the
                   4200: number onto the stack.
1.28      crook    4201: @item
1.30      anton    4202: When the number is @dfn{compiled}, a piece of code is appended to the
                   4203: current definition that pushes the number when it runs. (In other words,
                   4204: the compilation semantics of a number are to postpone its interpretation
                   4205: semantics until the run-time of the definition that it is being compiled
                   4206: into.)
1.29      crook    4207: @end itemize
                   4208: 
1.44      crook    4209: Words don't behave in such a regular way, but most have @i{default
                   4210: semantics} which means that they behave like this:
1.29      crook    4211: 
                   4212: @itemize @bullet
1.28      crook    4213: @item
1.30      anton    4214: The @dfn{interpretation semantics} of the word are to do something useful.
                   4215: @item
1.29      crook    4216: The @dfn{compilation semantics} of the word are to append its
1.30      anton    4217: @dfn{interpretation semantics} to the current definition (so that its
                   4218: run-time behaviour is to do something useful).
1.28      crook    4219: @end itemize
                   4220: 
1.30      anton    4221: @cindex immediate words
1.44      crook    4222: The actual behaviour of any particular word can be controlled by using
                   4223: the words @code{immediate} and @code{compile-only} when the word is
                   4224: defined. These words set flags in the name dictionary entry of the most
                   4225: recently defined word, and these flags are retrieved by the text
                   4226: interpreter when it finds the word in the name dictionary.
                   4227: 
                   4228: A word that is marked as @dfn{immediate} has compilation semantics that
                   4229: are identical to its interpretation semantics. In other words, it
                   4230: behaves like this:
1.29      crook    4231: 
                   4232: @itemize @bullet
                   4233: @item
1.30      anton    4234: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    4235: @item
1.30      anton    4236: The @dfn{compilation semantics} of the word are to do something useful
                   4237: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    4238: @end itemize
1.28      crook    4239: 
1.44      crook    4240: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   4241: performing the interpretation semantics of the word directly; an attempt
                   4242: to do so will generate an error. It is never necessary to use
                   4243: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   4244: provided by many implementations) but it is good etiquette to apply it
                   4245: to a word that will not behave correctly (and might have unexpected
                   4246: side-effects) in interpret state. For example, it is only legal to use
                   4247: the conditional word @code{IF} within a definition. If you forget this
                   4248: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   4249: @code{compile-only} allows the text interpreter to generate a helpful
                   4250: error message rather than subjecting you to the consequences of your
                   4251: folly.
                   4252: 
1.29      crook    4253: This example shows the difference between an immediate and a
                   4254: non-immediate word:
1.28      crook    4255: 
1.29      crook    4256: @example
                   4257: : show-state state @@ . ;
                   4258: : show-state-now show-state ; immediate
                   4259: : word1 show-state ;
                   4260: : word2 show-state-now ;
1.28      crook    4261: @end example
1.23      crook    4262: 
1.29      crook    4263: The word @code{immediate} after the definition of @code{show-state-now}
                   4264: makes that word an immediate word. These definitions introduce a new
                   4265: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   4266: variable, and leaves it on the stack. Therefore, the behaviour of
                   4267: @code{show-state} is to print a number that represents the current value
                   4268: of @code{state}.
1.28      crook    4269: 
1.29      crook    4270: When you execute @code{word1}, it prints the number 0, indicating that
                   4271: the system is interpreting. When the text interpreter compiled the
                   4272: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    4273: compilation semantics are to append its interpretation semantics to the
1.29      crook    4274: current definition. When you execute @code{word1}, it performs the
1.30      anton    4275: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    4276: (and therefore @code{show-state}) are executed, the system is
                   4277: interpreting.
1.28      crook    4278: 
1.30      anton    4279: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    4280: you should have seen the number -1 printed, followed by ``@code{
                   4281: ok}''. When the text interpreter compiled the definition of
                   4282: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    4283: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4284: semantics. It is executed straight away (even before the text
                   4285: interpreter has moved on to process another group of characters; the
                   4286: @code{;} in this example). The effect of executing it are to display the
                   4287: value of @code{state} @i{at the time that the definition of}
                   4288: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4289: system is compiling at this time. If you execute @code{word2} it does
                   4290: nothing at all.
1.28      crook    4291: 
1.29      crook    4292: @cindex @code{."}, how it works
                   4293: Before leaving the subject of immediate words, consider the behaviour of
                   4294: @code{."} in the definition of @code{greet}, in the previous
                   4295: section. This word is both a parsing word and an immediate word. Notice
                   4296: that there is a space between @code{."} and the start of the text
                   4297: @code{Hello and welcome}, but that there is no space between the last
                   4298: letter of @code{welcome} and the @code{"} character. The reason for this
                   4299: is that @code{."} is a Forth word; it must have a space after it so that
                   4300: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4301: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4302: is displayed, there is neither a space before the @code{H} nor after the
                   4303: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4304: that @code{greet} is defined. When it executes, its behaviour is to
                   4305: search forward in the input line looking for the delimiter. When it
                   4306: finds the delimiter, it updates @code{>IN} to point past the
                   4307: delimiter. It also compiles some magic code into the definition of
                   4308: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4309: compiles the string @code{Hello and welcome} into memory so that it is
                   4310: available to be printed later. When the text interpreter gains control,
                   4311: the next word it finds in the input stream is @code{;} and so it
                   4312: terminates the definition of @code{greet}.
1.28      crook    4313: 
                   4314: 
                   4315: @comment ----------------------------------------------
1.29      crook    4316: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4317: @section Forth is written in Forth
                   4318: @cindex structure of Forth programs
                   4319: 
                   4320: When you start up a Forth compiler, a large number of definitions
                   4321: already exist. In Forth, you develop a new application using bottom-up
                   4322: programming techniques to create new definitions that are defined in
                   4323: terms of existing definitions. As you create each definition you can
                   4324: test and debug it interactively.
                   4325: 
                   4326: If you have tried out the examples in this section, you will probably
                   4327: have typed them in by hand; when you leave Gforth, your definitions will
                   4328: be lost. You can avoid this by using a text editor to enter Forth source
                   4329: code into a file, and then loading code from the file using
1.49      anton    4330: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    4331: processed by the text interpreter, just as though you had typed it in by
                   4332: hand@footnote{Actually, there are some subtle differences -- see
                   4333: @ref{The Text Interpreter}.}.
                   4334: 
                   4335: Gforth also supports the traditional Forth alternative to using text
1.49      anton    4336: files for program entry (@pxref{Blocks}).
1.28      crook    4337: 
1.29      crook    4338: In common with many, if not most, Forth compilers, most of Gforth is
                   4339: actually written in Forth. All of the @file{.fs} files in the
                   4340: installation directory@footnote{For example,
1.30      anton    4341: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4342: study to see examples of Forth programming.
1.28      crook    4343: 
1.29      crook    4344: Gforth maintains a history file that records every line that you type to
                   4345: the text interpreter. This file is preserved between sessions, and is
                   4346: used to provide a command-line recall facility. If you enter long
                   4347: definitions by hand, you can use a text editor to paste them out of the
                   4348: history file into a Forth source file for reuse at a later time
1.49      anton    4349: (for more information @pxref{Command-line editing}).
1.28      crook    4350: 
                   4351: 
                   4352: @comment ----------------------------------------------
1.29      crook    4353: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4354: @section Review - elements of a Forth system
                   4355: @cindex elements of a Forth system
1.28      crook    4356: 
1.29      crook    4357: To summarise this chapter:
1.28      crook    4358: 
                   4359: @itemize @bullet
                   4360: @item
1.29      crook    4361: Forth programs use @dfn{factoring} to break a problem down into small
                   4362: fragments called @dfn{words} or @dfn{definitions}.
                   4363: @item
                   4364: Forth program development is an interactive process.
                   4365: @item
                   4366: The main command loop that accepts input, and controls both
                   4367: interpretation and compilation, is called the @dfn{text interpreter}
                   4368: (also known as the @dfn{outer interpreter}).
                   4369: @item
                   4370: Forth has a very simple syntax, consisting of words and numbers
                   4371: separated by spaces or carriage-return characters. Any additional syntax
                   4372: is imposed by @dfn{parsing words}.
                   4373: @item
                   4374: Forth uses a stack to pass parameters between words. As a result, it
                   4375: uses postfix notation.
                   4376: @item
                   4377: To use a word that has previously been defined, the text interpreter
                   4378: searches for the word in the @dfn{name dictionary}.
                   4379: @item
1.30      anton    4380: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4381: @item
1.29      crook    4382: The text interpreter uses the value of @code{state} to select between
                   4383: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4384: semantics} of a word that it encounters.
1.28      crook    4385: @item
1.30      anton    4386: The relationship between the @dfn{interpretation semantics} and
                   4387: @dfn{compilation semantics} for a word
1.29      crook    4388: depend upon the way in which the word was defined (for example, whether
                   4389: it is an @dfn{immediate} word).
1.28      crook    4390: @item
1.29      crook    4391: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4392: definitions}) or in some other way (usually a lower-level language and
                   4393: as a result often called @dfn{low-level definitions}, @dfn{code
                   4394: definitions} or @dfn{primitives}).
1.28      crook    4395: @item
1.29      crook    4396: Many Forth systems are implemented mainly in Forth.
1.28      crook    4397: @end itemize
                   4398: 
                   4399: 
1.29      crook    4400: @comment ----------------------------------------------
1.48      anton    4401: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4402: @section Where To Go Next
                   4403: @cindex where to go next
1.28      crook    4404: 
1.29      crook    4405: Amazing as it may seem, if you have read (and understood) this far, you
                   4406: know almost all the fundamentals about the inner workings of a Forth
                   4407: system. You certainly know enough to be able to read and understand the
                   4408: rest of this manual and the ANS Forth document, to learn more about the
                   4409: facilities that Forth in general and Gforth in particular provide. Even
                   4410: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4411: However, that's not a good idea just yet... better to try writing some
1.29      crook    4412: programs in Gforth.
1.28      crook    4413: 
1.29      crook    4414: Forth has such a rich vocabulary that it can be hard to know where to
                   4415: start in learning it. This section suggests a few sets of words that are
                   4416: enough to write small but useful programs. Use the word index in this
                   4417: document to learn more about each word, then try it out and try to write
                   4418: small definitions using it. Start by experimenting with these words:
1.28      crook    4419: 
                   4420: @itemize @bullet
                   4421: @item
1.29      crook    4422: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4423: @item
                   4424: Comparison: @code{MIN MAX =}
                   4425: @item
                   4426: Logic: @code{AND OR XOR NOT}
                   4427: @item
                   4428: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4429: @item
1.29      crook    4430: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4431: @item
1.29      crook    4432: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4433: @item
1.29      crook    4434: Defining words: @code{: ; CREATE}
1.28      crook    4435: @item
1.29      crook    4436: Memory allocation words: @code{ALLOT ,}
1.28      crook    4437: @item
1.29      crook    4438: Tools: @code{SEE WORDS .S MARKER}
                   4439: @end itemize
                   4440: 
                   4441: When you have mastered those, go on to:
                   4442: 
                   4443: @itemize @bullet
1.28      crook    4444: @item
1.29      crook    4445: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4446: @item
1.29      crook    4447: Memory access: @code{@@ !}
1.28      crook    4448: @end itemize
1.23      crook    4449: 
1.29      crook    4450: When you have mastered these, there's nothing for it but to read through
                   4451: the whole of this manual and find out what you've missed.
                   4452: 
                   4453: @comment ----------------------------------------------
1.48      anton    4454: @node Exercises,  , Where to go next, Introduction
1.29      crook    4455: @section Exercises
                   4456: @cindex exercises
                   4457: 
                   4458: TODO: provide a set of programming excercises linked into the stuff done
                   4459: already and into other sections of the manual. Provide solutions to all
                   4460: the exercises in a .fs file in the distribution.
                   4461: 
                   4462: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4463: 
                   4464: @c excercises:
                   4465: @c 1. take inches and convert to feet and inches.
                   4466: @c 2. take temperature and convert from fahrenheight to celcius;
                   4467: @c    may need to care about symmetric vs floored??
                   4468: @c 3. take input line and do character substitution
                   4469: @c    to encipher or decipher
                   4470: @c 4. as above but work on a file for in and out
                   4471: @c 5. take input line and convert to pig-latin 
                   4472: @c
                   4473: @c thing of sets of things to exercise then come up with
                   4474: @c problems that need those things.
                   4475: 
                   4476: 
1.26      crook    4477: @c ******************************************************************
1.29      crook    4478: @node Words, Error messages, Introduction, Top
1.1       anton    4479: @chapter Forth Words
1.26      crook    4480: @cindex words
1.1       anton    4481: 
                   4482: @menu
                   4483: * Notation::                    
1.65      anton    4484: * Case insensitivity::          
                   4485: * Comments::                    
                   4486: * Boolean Flags::               
1.1       anton    4487: * Arithmetic::                  
                   4488: * Stack Manipulation::          
1.5       anton    4489: * Memory::                      
1.1       anton    4490: * Control Structures::          
                   4491: * Defining Words::              
1.65      anton    4492: * Interpretation and Compilation Semantics::  
1.47      crook    4493: * Tokens for Words::            
1.81      anton    4494: * Compiling words::             
1.65      anton    4495: * The Text Interpreter::        
                   4496: * Word Lists::                  
                   4497: * Environmental Queries::       
1.12      anton    4498: * Files::                       
                   4499: * Blocks::                      
                   4500: * Other I/O::                   
1.78      anton    4501: * Locals::                      
                   4502: * Structures::                  
                   4503: * Object-oriented Forth::       
1.12      anton    4504: * Programming Tools::           
                   4505: * Assembler and Code Words::    
                   4506: * Threading Words::             
1.65      anton    4507: * Passing Commands to the OS::  
                   4508: * Keeping track of Time::       
                   4509: * Miscellaneous Words::         
1.1       anton    4510: @end menu
                   4511: 
1.65      anton    4512: @node Notation, Case insensitivity, Words, Words
1.1       anton    4513: @section Notation
                   4514: @cindex notation of glossary entries
                   4515: @cindex format of glossary entries
                   4516: @cindex glossary notation format
                   4517: @cindex word glossary entry format
                   4518: 
                   4519: The Forth words are described in this section in the glossary notation
1.67      anton    4520: that has become a de-facto standard for Forth texts:
1.1       anton    4521: 
                   4522: @format
1.29      crook    4523: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4524: @end format
1.29      crook    4525: @i{Description}
1.1       anton    4526: 
                   4527: @table @var
                   4528: @item word
1.28      crook    4529: The name of the word.
1.1       anton    4530: 
                   4531: @item Stack effect
                   4532: @cindex stack effect
1.29      crook    4533: The stack effect is written in the notation @code{@i{before} --
                   4534: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4535: stack entries before and after the execution of the word. The rest of
                   4536: the stack is not touched by the word. The top of stack is rightmost,
                   4537: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4538: uses a separate floating point stack, but a unified stack
1.29      crook    4539: notation. Also, return stack effects are not shown in @i{stack
                   4540: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4541: the type and/or the function of the item. See below for a discussion of
                   4542: the types.
                   4543: 
                   4544: All words have two stack effects: A compile-time stack effect and a
                   4545: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4546: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4547: this standard behaviour, or the word does other unusual things at
                   4548: compile time, both stack effects are shown; otherwise only the run-time
                   4549: stack effect is shown.
                   4550: 
                   4551: @cindex pronounciation of words
                   4552: @item pronunciation
                   4553: How the word is pronounced.
                   4554: 
                   4555: @cindex wordset
1.67      anton    4556: @cindex environment wordset
1.1       anton    4557: @item wordset
1.21      crook    4558: The ANS Forth standard is divided into several word sets. A standard
                   4559: system need not support all of them. Therefore, in theory, the fewer
                   4560: word sets your program uses the more portable it will be. However, we
                   4561: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4562: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4563: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4564: describes words that will work in future releases of Gforth;
                   4565: @code{gforth-internal} words are more volatile. Environmental query
                   4566: strings are also displayed like words; you can recognize them by the
1.21      crook    4567: @code{environment} in the word set field.
1.1       anton    4568: 
                   4569: @item Description
                   4570: A description of the behaviour of the word.
                   4571: @end table
                   4572: 
                   4573: @cindex types of stack items
                   4574: @cindex stack item types
                   4575: The type of a stack item is specified by the character(s) the name
                   4576: starts with:
                   4577: 
                   4578: @table @code
                   4579: @item f
                   4580: @cindex @code{f}, stack item type
                   4581: Boolean flags, i.e. @code{false} or @code{true}.
                   4582: @item c
                   4583: @cindex @code{c}, stack item type
                   4584: Char
                   4585: @item w
                   4586: @cindex @code{w}, stack item type
                   4587: Cell, can contain an integer or an address
                   4588: @item n
                   4589: @cindex @code{n}, stack item type
                   4590: signed integer
                   4591: @item u
                   4592: @cindex @code{u}, stack item type
                   4593: unsigned integer
                   4594: @item d
                   4595: @cindex @code{d}, stack item type
                   4596: double sized signed integer
                   4597: @item ud
                   4598: @cindex @code{ud}, stack item type
                   4599: double sized unsigned integer
                   4600: @item r
                   4601: @cindex @code{r}, stack item type
                   4602: Float (on the FP stack)
1.21      crook    4603: @item a-
1.1       anton    4604: @cindex @code{a_}, stack item type
                   4605: Cell-aligned address
1.21      crook    4606: @item c-
1.1       anton    4607: @cindex @code{c_}, stack item type
                   4608: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4609: @item f-
1.1       anton    4610: @cindex @code{f_}, stack item type
                   4611: Float-aligned address
1.21      crook    4612: @item df-
1.1       anton    4613: @cindex @code{df_}, stack item type
                   4614: Address aligned for IEEE double precision float
1.21      crook    4615: @item sf-
1.1       anton    4616: @cindex @code{sf_}, stack item type
                   4617: Address aligned for IEEE single precision float
                   4618: @item xt
                   4619: @cindex @code{xt}, stack item type
                   4620: Execution token, same size as Cell
                   4621: @item wid
                   4622: @cindex @code{wid}, stack item type
1.21      crook    4623: Word list ID, same size as Cell
1.68      anton    4624: @item ior, wior
                   4625: @cindex ior type description
                   4626: @cindex wior type description
                   4627: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
1.1       anton    4628: @item f83name
                   4629: @cindex @code{f83name}, stack item type
                   4630: Pointer to a name structure
                   4631: @item "
                   4632: @cindex @code{"}, stack item type
1.12      anton    4633: string in the input stream (not on the stack). The terminating character
                   4634: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4635: quotes.
                   4636: @end table
                   4637: 
1.65      anton    4638: @comment ----------------------------------------------
                   4639: @node Case insensitivity, Comments, Notation, Words
                   4640: @section Case insensitivity
                   4641: @cindex case sensitivity
                   4642: @cindex upper and lower case
                   4643: 
                   4644: Gforth is case-insensitive; you can enter definitions and invoke
                   4645: Standard words using upper, lower or mixed case (however,
                   4646: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   4647: options}).
                   4648: 
                   4649: ANS Forth only @i{requires} implementations to recognise Standard words
                   4650: when they are typed entirely in upper case. Therefore, a Standard
                   4651: program must use upper case for all Standard words. You can use whatever
                   4652: case you like for words that you define, but in a Standard program you
                   4653: have to use the words in the same case that you defined them.
                   4654: 
                   4655: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   4656: wordlists, @pxref{Word Lists}).
                   4657: 
                   4658: Two people have asked how to convert Gforth to be case-sensitive; while
                   4659: we think this is a bad idea, you can change all wordlists into tables
                   4660: like this:
                   4661: 
                   4662: @example
                   4663: ' table-find forth-wordlist wordlist-map @ !
                   4664: @end example
                   4665: 
                   4666: Note that you now have to type the predefined words in the same case
                   4667: that we defined them, which are varying.  You may want to convert them
                   4668: to your favourite case before doing this operation (I won't explain how,
                   4669: because if you are even contemplating doing this, you'd better have
                   4670: enough knowledge of Forth systems to know this already).
                   4671: 
                   4672: @node Comments, Boolean Flags, Case insensitivity, Words
1.21      crook    4673: @section Comments
1.26      crook    4674: @cindex comments
1.21      crook    4675: 
1.29      crook    4676: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4677: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4678: 
1.44      crook    4679: 
1.23      crook    4680: doc-(
1.21      crook    4681: doc-\
1.23      crook    4682: doc-\G
1.21      crook    4683: 
1.44      crook    4684: 
1.21      crook    4685: @node Boolean Flags, Arithmetic, Comments, Words
                   4686: @section Boolean Flags
1.26      crook    4687: @cindex Boolean flags
1.21      crook    4688: 
                   4689: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4690: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4691: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4692: a cell that has @i{any} bit set as @code{true}.
1.67      anton    4693: @c on and off to Memory? 
                   4694: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44      crook    4695: 
1.21      crook    4696: doc-true
                   4697: doc-false
1.29      crook    4698: doc-on
                   4699: doc-off
1.21      crook    4700: 
1.44      crook    4701: 
1.21      crook    4702: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4703: @section Arithmetic
                   4704: @cindex arithmetic words
                   4705: 
                   4706: @cindex division with potentially negative operands
                   4707: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4708: overflow on addition or multiplication, you may hear about division by
                   4709: zero if you are lucky. The operator is written after the operands, but
                   4710: the operands are still in the original order. I.e., the infix @code{2-1}
                   4711: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4712: operators. If you perform division with potentially negative operands,
                   4713: you do not want to use @code{/} or @code{/mod} with its undefined
                   4714: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4715: former, @pxref{Mixed precision}).
1.26      crook    4716: @comment TODO discuss the different division forms and the std approach
1.1       anton    4717: 
                   4718: @menu
                   4719: * Single precision::            
1.67      anton    4720: * Double precision::            Double-cell integer arithmetic
1.1       anton    4721: * Bitwise operations::          
1.67      anton    4722: * Numeric comparison::          
1.29      crook    4723: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4724: * Floating Point::              
                   4725: @end menu
                   4726: 
1.67      anton    4727: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1       anton    4728: @subsection Single precision
                   4729: @cindex single precision arithmetic words
                   4730: 
1.67      anton    4731: @c !! cell undefined
                   4732: 
                   4733: By default, numbers in Forth are single-precision integers that are one
1.26      crook    4734: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4735: treat them. For the rules used by the text interpreter for recognising
                   4736: single-precision integers see @ref{Number Conversion}.
1.21      crook    4737: 
1.67      anton    4738: These words are all defined for signed operands, but some of them also
                   4739: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
                   4740: @code{*}.
1.44      crook    4741: 
1.1       anton    4742: doc-+
1.21      crook    4743: doc-1+
1.1       anton    4744: doc--
1.21      crook    4745: doc-1-
1.1       anton    4746: doc-*
                   4747: doc-/
                   4748: doc-mod
                   4749: doc-/mod
                   4750: doc-negate
                   4751: doc-abs
                   4752: doc-min
                   4753: doc-max
1.27      crook    4754: doc-floored
1.1       anton    4755: 
1.44      crook    4756: 
1.67      anton    4757: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21      crook    4758: @subsection Double precision
                   4759: @cindex double precision arithmetic words
                   4760: 
1.49      anton    4761: For the rules used by the text interpreter for
                   4762: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4763: 
                   4764: A double precision number is represented by a cell pair, with the most
1.67      anton    4765: significant cell at the TOS. It is trivial to convert an unsigned single
                   4766: to a double: simply push a @code{0} onto the TOS. Since numbers are
                   4767: represented by Gforth using 2's complement arithmetic, converting a
                   4768: signed single to a (signed) double requires sign-extension across the
                   4769: most significant cell. This can be achieved using @code{s>d}. The moral
                   4770: of the story is that you cannot convert a number without knowing whether
                   4771: it represents an unsigned or a signed number.
1.21      crook    4772: 
1.67      anton    4773: These words are all defined for signed operands, but some of them also
                   4774: work for unsigned numbers: @code{d+}, @code{d-}.
1.44      crook    4775: 
1.21      crook    4776: doc-s>d
1.67      anton    4777: doc-d>s
1.21      crook    4778: doc-d+
                   4779: doc-d-
                   4780: doc-dnegate
                   4781: doc-dabs
                   4782: doc-dmin
                   4783: doc-dmax
                   4784: 
1.44      crook    4785: 
1.67      anton    4786: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
                   4787: @subsection Bitwise operations
                   4788: @cindex bitwise operation words
                   4789: 
                   4790: 
                   4791: doc-and
                   4792: doc-or
                   4793: doc-xor
                   4794: doc-invert
                   4795: doc-lshift
                   4796: doc-rshift
                   4797: doc-2*
                   4798: doc-d2*
                   4799: doc-2/
                   4800: doc-d2/
                   4801: 
                   4802: 
                   4803: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21      crook    4804: @subsection Numeric comparison
                   4805: @cindex numeric comparison words
                   4806: 
1.67      anton    4807: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
                   4808: d0= d0<>}) work for for both signed and unsigned numbers.
1.44      crook    4809: 
1.28      crook    4810: doc-<
                   4811: doc-<=
                   4812: doc-<>
                   4813: doc-=
                   4814: doc->
                   4815: doc->=
                   4816: 
1.21      crook    4817: doc-0<
1.23      crook    4818: doc-0<=
1.21      crook    4819: doc-0<>
                   4820: doc-0=
1.23      crook    4821: doc-0>
                   4822: doc-0>=
1.28      crook    4823: 
                   4824: doc-u<
                   4825: doc-u<=
1.44      crook    4826: @c u<> and u= exist but are the same as <> and =
1.31      anton    4827: @c doc-u<>
                   4828: @c doc-u=
1.28      crook    4829: doc-u>
                   4830: doc-u>=
                   4831: 
                   4832: doc-within
                   4833: 
                   4834: doc-d<
                   4835: doc-d<=
                   4836: doc-d<>
                   4837: doc-d=
                   4838: doc-d>
                   4839: doc-d>=
1.23      crook    4840: 
1.21      crook    4841: doc-d0<
1.23      crook    4842: doc-d0<=
                   4843: doc-d0<>
1.21      crook    4844: doc-d0=
1.23      crook    4845: doc-d0>
                   4846: doc-d0>=
                   4847: 
1.21      crook    4848: doc-du<
1.28      crook    4849: doc-du<=
1.44      crook    4850: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4851: @c doc-du<>
                   4852: @c doc-du=
1.28      crook    4853: doc-du>
                   4854: doc-du>=
1.1       anton    4855: 
1.44      crook    4856: 
1.21      crook    4857: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4858: @subsection Mixed precision
                   4859: @cindex mixed precision arithmetic words
                   4860: 
1.44      crook    4861: 
1.1       anton    4862: doc-m+
                   4863: doc-*/
                   4864: doc-*/mod
                   4865: doc-m*
                   4866: doc-um*
                   4867: doc-m*/
                   4868: doc-um/mod
                   4869: doc-fm/mod
                   4870: doc-sm/rem
                   4871: 
1.44      crook    4872: 
1.21      crook    4873: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4874: @subsection Floating Point
                   4875: @cindex floating point arithmetic words
                   4876: 
1.49      anton    4877: For the rules used by the text interpreter for
                   4878: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4879: 
1.67      anton    4880: Gforth has a separate floating point stack, but the documentation uses
                   4881: the unified notation.@footnote{It's easy to generate the separate
                   4882: notation from that by just separating the floating-point numbers out:
                   4883: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
                   4884: r3 )}.}
1.1       anton    4885: 
                   4886: @cindex floating-point arithmetic, pitfalls
                   4887: Floating point numbers have a number of unpleasant surprises for the
                   4888: unwary (e.g., floating point addition is not associative) and even a few
                   4889: for the wary. You should not use them unless you know what you are doing
                   4890: or you don't care that the results you get are totally bogus. If you
                   4891: want to learn about the problems of floating point numbers (and how to
1.66      anton    4892: avoid them), you might start with @cite{David Goldberg,
                   4893: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
                   4894: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
                   4895: Surveys 23(1):5@minus{}48, March 1991}.
1.1       anton    4896: 
1.44      crook    4897: 
1.21      crook    4898: doc-d>f
                   4899: doc-f>d
1.1       anton    4900: doc-f+
                   4901: doc-f-
                   4902: doc-f*
                   4903: doc-f/
                   4904: doc-fnegate
                   4905: doc-fabs
                   4906: doc-fmax
                   4907: doc-fmin
                   4908: doc-floor
                   4909: doc-fround
                   4910: doc-f**
                   4911: doc-fsqrt
                   4912: doc-fexp
                   4913: doc-fexpm1
                   4914: doc-fln
                   4915: doc-flnp1
                   4916: doc-flog
                   4917: doc-falog
1.32      anton    4918: doc-f2*
                   4919: doc-f2/
                   4920: doc-1/f
                   4921: doc-precision
                   4922: doc-set-precision
                   4923: 
                   4924: @cindex angles in trigonometric operations
                   4925: @cindex trigonometric operations
                   4926: Angles in floating point operations are given in radians (a full circle
                   4927: has 2 pi radians).
                   4928: 
1.1       anton    4929: doc-fsin
                   4930: doc-fcos
                   4931: doc-fsincos
                   4932: doc-ftan
                   4933: doc-fasin
                   4934: doc-facos
                   4935: doc-fatan
                   4936: doc-fatan2
                   4937: doc-fsinh
                   4938: doc-fcosh
                   4939: doc-ftanh
                   4940: doc-fasinh
                   4941: doc-facosh
                   4942: doc-fatanh
1.21      crook    4943: doc-pi
1.28      crook    4944: 
1.32      anton    4945: @cindex equality of floats
                   4946: @cindex floating-point comparisons
1.31      anton    4947: One particular problem with floating-point arithmetic is that comparison
                   4948: for equality often fails when you would expect it to succeed.  For this
                   4949: reason approximate equality is often preferred (but you still have to
1.67      anton    4950: know what you are doing).  Also note that IEEE NaNs may compare
1.68      anton    4951: differently from what you might expect.  The comparison words are:
1.31      anton    4952: 
                   4953: doc-f~rel
                   4954: doc-f~abs
1.68      anton    4955: doc-f~
1.31      anton    4956: doc-f=
                   4957: doc-f<>
                   4958: 
                   4959: doc-f<
                   4960: doc-f<=
                   4961: doc-f>
                   4962: doc-f>=
                   4963: 
1.21      crook    4964: doc-f0<
1.28      crook    4965: doc-f0<=
                   4966: doc-f0<>
1.21      crook    4967: doc-f0=
1.28      crook    4968: doc-f0>
                   4969: doc-f0>=
                   4970: 
1.1       anton    4971: 
                   4972: @node Stack Manipulation, Memory, Arithmetic, Words
                   4973: @section Stack Manipulation
                   4974: @cindex stack manipulation words
                   4975: 
                   4976: @cindex floating-point stack in the standard
1.21      crook    4977: Gforth maintains a number of separate stacks:
                   4978: 
1.29      crook    4979: @cindex data stack
                   4980: @cindex parameter stack
1.21      crook    4981: @itemize @bullet
                   4982: @item
1.29      crook    4983: A data stack (also known as the @dfn{parameter stack}) -- for
                   4984: characters, cells, addresses, and double cells.
1.21      crook    4985: 
1.29      crook    4986: @cindex floating-point stack
1.21      crook    4987: @item
1.44      crook    4988: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4989: 
1.29      crook    4990: @cindex return stack
1.21      crook    4991: @item
1.44      crook    4992: A return stack -- for holding the return addresses of colon
1.32      anton    4993: definitions and other (non-FP) data.
1.21      crook    4994: 
1.29      crook    4995: @cindex locals stack
1.21      crook    4996: @item
1.44      crook    4997: A locals stack -- for holding local variables.
1.21      crook    4998: @end itemize
                   4999: 
1.1       anton    5000: @menu
                   5001: * Data stack::                  
                   5002: * Floating point stack::        
                   5003: * Return stack::                
                   5004: * Locals stack::                
                   5005: * Stack pointer manipulation::  
                   5006: @end menu
                   5007: 
                   5008: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   5009: @subsection Data stack
                   5010: @cindex data stack manipulation words
                   5011: @cindex stack manipulations words, data stack
                   5012: 
1.44      crook    5013: 
1.1       anton    5014: doc-drop
                   5015: doc-nip
                   5016: doc-dup
                   5017: doc-over
                   5018: doc-tuck
                   5019: doc-swap
1.21      crook    5020: doc-pick
1.1       anton    5021: doc-rot
                   5022: doc--rot
                   5023: doc-?dup
                   5024: doc-roll
                   5025: doc-2drop
                   5026: doc-2nip
                   5027: doc-2dup
                   5028: doc-2over
                   5029: doc-2tuck
                   5030: doc-2swap
                   5031: doc-2rot
                   5032: 
1.44      crook    5033: 
1.1       anton    5034: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   5035: @subsection Floating point stack
                   5036: @cindex floating-point stack manipulation words
                   5037: @cindex stack manipulation words, floating-point stack
                   5038: 
1.32      anton    5039: Whilst every sane Forth has a separate floating-point stack, it is not
                   5040: strictly required; an ANS Forth system could theoretically keep
                   5041: floating-point numbers on the data stack. As an additional difficulty,
                   5042: you don't know how many cells a floating-point number takes. It is
                   5043: reportedly possible to write words in a way that they work also for a
                   5044: unified stack model, but we do not recommend trying it. Instead, just
                   5045: say that your program has an environmental dependency on a separate
                   5046: floating-point stack.
                   5047: 
                   5048: doc-floating-stack
                   5049: 
1.1       anton    5050: doc-fdrop
                   5051: doc-fnip
                   5052: doc-fdup
                   5053: doc-fover
                   5054: doc-ftuck
                   5055: doc-fswap
1.21      crook    5056: doc-fpick
1.1       anton    5057: doc-frot
                   5058: 
1.44      crook    5059: 
1.1       anton    5060: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   5061: @subsection Return stack
                   5062: @cindex return stack manipulation words
                   5063: @cindex stack manipulation words, return stack
                   5064: 
1.32      anton    5065: @cindex return stack and locals
                   5066: @cindex locals and return stack
                   5067: A Forth system is allowed to keep local variables on the
                   5068: return stack. This is reasonable, as local variables usually eliminate
                   5069: the need to use the return stack explicitly. So, if you want to produce
                   5070: a standard compliant program and you are using local variables in a
                   5071: word, forget about return stack manipulations in that word (refer to the
                   5072: standard document for the exact rules).
                   5073: 
1.1       anton    5074: doc->r
                   5075: doc-r>
                   5076: doc-r@
                   5077: doc-rdrop
                   5078: doc-2>r
                   5079: doc-2r>
                   5080: doc-2r@
                   5081: doc-2rdrop
                   5082: 
1.44      crook    5083: 
1.1       anton    5084: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   5085: @subsection Locals stack
                   5086: 
1.78      anton    5087: Gforth uses an extra locals stack.  It is described, along with the
                   5088: reasons for its existence, in @ref{Locals implementation}.
1.21      crook    5089: 
1.1       anton    5090: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   5091: @subsection Stack pointer manipulation
                   5092: @cindex stack pointer manipulation words
                   5093: 
1.44      crook    5094: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    5095: doc-sp0
1.1       anton    5096: doc-sp@
                   5097: doc-sp!
1.21      crook    5098: doc-fp0
1.1       anton    5099: doc-fp@
                   5100: doc-fp!
1.21      crook    5101: doc-rp0
1.1       anton    5102: doc-rp@
                   5103: doc-rp!
1.21      crook    5104: doc-lp0
1.1       anton    5105: doc-lp@
                   5106: doc-lp!
                   5107: 
1.44      crook    5108: 
1.1       anton    5109: @node Memory, Control Structures, Stack Manipulation, Words
                   5110: @section Memory
1.26      crook    5111: @cindex memory words
1.1       anton    5112: 
1.32      anton    5113: @menu
                   5114: * Memory model::                
                   5115: * Dictionary allocation::       
                   5116: * Heap Allocation::             
                   5117: * Memory Access::               
                   5118: * Address arithmetic::          
                   5119: * Memory Blocks::               
                   5120: @end menu
                   5121: 
1.67      anton    5122: In addition to the standard Forth memory allocation words, there is also
                   5123: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   5124: garbage collector}.
                   5125: 
1.32      anton    5126: @node Memory model, Dictionary allocation, Memory, Memory
                   5127: @subsection ANS Forth and Gforth memory models
                   5128: 
                   5129: @c The ANS Forth description is a mess (e.g., is the heap part of
                   5130: @c the dictionary?), so let's not stick to closely with it.
                   5131: 
1.67      anton    5132: ANS Forth considers a Forth system as consisting of several address
                   5133: spaces, of which only @dfn{data space} is managed and accessible with
                   5134: the memory words.  Memory not necessarily in data space includes the
                   5135: stacks, the code (called code space) and the headers (called name
                   5136: space). In Gforth everything is in data space, but the code for the
                   5137: primitives is usually read-only.
1.32      anton    5138: 
                   5139: Data space is divided into a number of areas: The (data space portion of
                   5140: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   5141: refer to the search data structure embodied in word lists and headers,
                   5142: because it is used for looking up names, just as you would in a
                   5143: conventional dictionary.}, the heap, and a number of system-allocated
                   5144: buffers.
                   5145: 
1.68      anton    5146: @cindex address arithmetic restrictions, ANS vs. Gforth
                   5147: @cindex contiguous regions, ANS vs. Gforth
1.32      anton    5148: In ANS Forth data space is also divided into contiguous regions.  You
                   5149: can only use address arithmetic within a contiguous region, not between
                   5150: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    5151: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    5152: allocation}).
                   5153: 
                   5154: Gforth provides one big address space, and address arithmetic can be
                   5155: performed between any addresses. However, in the dictionary headers or
                   5156: code are interleaved with data, so almost the only contiguous data space
                   5157: regions there are those described by ANS Forth as contiguous; but you
                   5158: can be sure that the dictionary is allocated towards increasing
                   5159: addresses even between contiguous regions.  The memory order of
                   5160: allocations in the heap is platform-dependent (and possibly different
                   5161: from one run to the next).
                   5162: 
1.27      crook    5163: 
1.32      anton    5164: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   5165: @subsection Dictionary allocation
1.27      crook    5166: @cindex reserving data space
                   5167: @cindex data space - reserving some
                   5168: 
1.32      anton    5169: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   5170: you want to deallocate X, you also deallocate everything
                   5171: allocated after X.
                   5172: 
1.68      anton    5173: @cindex contiguous regions in dictionary allocation
1.32      anton    5174: The allocations using the words below are contiguous and grow the region
                   5175: towards increasing addresses.  Other words that allocate dictionary
                   5176: memory of any kind (i.e., defining words including @code{:noname}) end
                   5177: the contiguous region and start a new one.
                   5178: 
                   5179: In ANS Forth only @code{create}d words are guaranteed to produce an
                   5180: address that is the start of the following contiguous region.  In
                   5181: particular, the cell allocated by @code{variable} is not guaranteed to
                   5182: be contiguous with following @code{allot}ed memory.
                   5183: 
                   5184: You can deallocate memory by using @code{allot} with a negative argument
                   5185: (with some restrictions, see @code{allot}). For larger deallocations use
                   5186: @code{marker}.
1.27      crook    5187: 
1.29      crook    5188: 
1.27      crook    5189: doc-here
                   5190: doc-unused
                   5191: doc-allot
                   5192: doc-c,
1.29      crook    5193: doc-f,
1.27      crook    5194: doc-,
                   5195: doc-2,
                   5196: 
1.32      anton    5197: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   5198: course you should allocate memory in an aligned way, too. I.e., before
                   5199: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   5200: The words below align @code{here} if it is not already.  Basically it is
                   5201: only already aligned for a type, if the last allocation was a multiple
                   5202: of the size of this type and if @code{here} was aligned for this type
                   5203: before.
                   5204: 
                   5205: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   5206: ANS Forth (@code{maxalign}ed in Gforth).
                   5207: 
                   5208: doc-align
                   5209: doc-falign
                   5210: doc-sfalign
                   5211: doc-dfalign
                   5212: doc-maxalign
                   5213: doc-cfalign
                   5214: 
                   5215: 
                   5216: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   5217: @subsection Heap allocation
                   5218: @cindex heap allocation
                   5219: @cindex dynamic allocation of memory
                   5220: @cindex memory-allocation word set
                   5221: 
1.68      anton    5222: @cindex contiguous regions and heap allocation
1.32      anton    5223: Heap allocation supports deallocation of allocated memory in any
                   5224: order. Dictionary allocation is not affected by it (i.e., it does not
                   5225: end a contiguous region). In Gforth, these words are implemented using
                   5226: the standard C library calls malloc(), free() and resize().
                   5227: 
1.68      anton    5228: The memory region produced by one invocation of @code{allocate} or
                   5229: @code{resize} is internally contiguous.  There is no contiguity between
                   5230: such a region and any other region (including others allocated from the
                   5231: heap).
                   5232: 
1.32      anton    5233: doc-allocate
                   5234: doc-free
                   5235: doc-resize
                   5236: 
1.27      crook    5237: 
1.32      anton    5238: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    5239: @subsection Memory Access
                   5240: @cindex memory access words
                   5241: 
                   5242: doc-@
                   5243: doc-!
                   5244: doc-+!
                   5245: doc-c@
                   5246: doc-c!
                   5247: doc-2@
                   5248: doc-2!
                   5249: doc-f@
                   5250: doc-f!
                   5251: doc-sf@
                   5252: doc-sf!
                   5253: doc-df@
                   5254: doc-df!
                   5255: 
1.68      anton    5256: 
1.32      anton    5257: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   5258: @subsection Address arithmetic
1.1       anton    5259: @cindex address arithmetic words
                   5260: 
1.67      anton    5261: Address arithmetic is the foundation on which you can build data
                   5262: structures like arrays, records (@pxref{Structures}) and objects
                   5263: (@pxref{Object-oriented Forth}).
1.32      anton    5264: 
1.68      anton    5265: @cindex address unit
                   5266: @cindex au (address unit)
1.1       anton    5267: ANS Forth does not specify the sizes of the data types. Instead, it
                   5268: offers a number of words for computing sizes and doing address
1.29      crook    5269: arithmetic. Address arithmetic is performed in terms of address units
                   5270: (aus); on most systems the address unit is one byte. Note that a
                   5271: character may have more than one au, so @code{chars} is no noop (on
1.68      anton    5272: platforms where it is a noop, it compiles to nothing).
1.1       anton    5273: 
1.67      anton    5274: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
                   5275: you have the address of a cell, perform @code{1 cells +}, and you will
                   5276: have the address of the next cell.
                   5277: 
1.68      anton    5278: @cindex contiguous regions and address arithmetic
1.67      anton    5279: In ANS Forth you can perform address arithmetic only within a contiguous
                   5280: region, i.e., if you have an address into one region, you can only add
                   5281: and subtract such that the result is still within the region; you can
                   5282: only subtract or compare addresses from within the same contiguous
                   5283: region.  Reasons: several contiguous regions can be arranged in memory
                   5284: in any way; on segmented systems addresses may have unusual
                   5285: representations, such that address arithmetic only works within a
                   5286: region.  Gforth provides a few more guarantees (linear address space,
                   5287: dictionary grows upwards), but in general I have found it easy to stay
                   5288: within contiguous regions (exception: computing and comparing to the
                   5289: address just beyond the end of an array).
                   5290: 
1.1       anton    5291: @cindex alignment of addresses for types
                   5292: ANS Forth also defines words for aligning addresses for specific
                   5293: types. Many computers require that accesses to specific data types
                   5294: must only occur at specific addresses; e.g., that cells may only be
                   5295: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5296: accesses, it can usually perform aligned accesses faster. 
                   5297: 
                   5298: For the performance-conscious: alignment operations are usually only
                   5299: necessary during the definition of a data structure, not during the
                   5300: (more frequent) accesses to it.
                   5301: 
                   5302: ANS Forth defines no words for character-aligning addresses. This is not
                   5303: an oversight, but reflects the fact that addresses that are not
                   5304: char-aligned have no use in the standard and therefore will not be
                   5305: created.
                   5306: 
                   5307: @cindex @code{CREATE} and alignment
1.29      crook    5308: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5309: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5310: are aligned for all purposes.
                   5311: 
1.26      crook    5312: Note that the ANS Forth word @code{char} has nothing to do with address
                   5313: arithmetic.
1.1       anton    5314: 
1.44      crook    5315: 
1.1       anton    5316: doc-chars
                   5317: doc-char+
                   5318: doc-cells
                   5319: doc-cell+
                   5320: doc-cell
                   5321: doc-aligned
                   5322: doc-floats
                   5323: doc-float+
                   5324: doc-float
                   5325: doc-faligned
                   5326: doc-sfloats
                   5327: doc-sfloat+
                   5328: doc-sfaligned
                   5329: doc-dfloats
                   5330: doc-dfloat+
                   5331: doc-dfaligned
                   5332: doc-maxaligned
                   5333: doc-cfaligned
                   5334: doc-address-unit-bits
                   5335: 
1.44      crook    5336: 
1.32      anton    5337: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5338: @subsection Memory Blocks
                   5339: @cindex memory block words
1.27      crook    5340: @cindex character strings - moving and copying
                   5341: 
1.49      anton    5342: Memory blocks often represent character strings; For ways of storing
                   5343: character strings in memory see @ref{String Formats}.  For other
                   5344: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5345: 
1.67      anton    5346: A few of these words work on address unit blocks.  In that case, you
                   5347: usually have to insert @code{CHARS} before the word when working on
                   5348: character strings.  Most words work on character blocks, and expect a
                   5349: char-aligned address.
                   5350: 
                   5351: When copying characters between overlapping memory regions, use
                   5352: @code{chars move} or choose carefully between @code{cmove} and
                   5353: @code{cmove>}.
1.44      crook    5354: 
1.1       anton    5355: doc-move
                   5356: doc-erase
                   5357: doc-cmove
                   5358: doc-cmove>
                   5359: doc-fill
                   5360: doc-blank
1.21      crook    5361: doc-compare
                   5362: doc-search
1.27      crook    5363: doc--trailing
                   5364: doc-/string
1.82      anton    5365: doc-bounds
1.44      crook    5366: 
1.27      crook    5367: @comment TODO examples
                   5368: 
1.1       anton    5369: 
1.26      crook    5370: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5371: @section Control Structures
                   5372: @cindex control structures
                   5373: 
1.33      anton    5374: Control structures in Forth cannot be used interpretively, only in a
                   5375: colon definition@footnote{To be precise, they have no interpretation
                   5376: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5377: not like this limitation, but have not seen a satisfying way around it
                   5378: yet, although many schemes have been proposed.
1.1       anton    5379: 
                   5380: @menu
1.33      anton    5381: * Selection::                   IF ... ELSE ... ENDIF
                   5382: * Simple Loops::                BEGIN ...
1.29      crook    5383: * Counted Loops::               DO
1.67      anton    5384: * Arbitrary control structures::  
                   5385: * Calls and returns::           
1.1       anton    5386: * Exception Handling::          
                   5387: @end menu
                   5388: 
                   5389: @node Selection, Simple Loops, Control Structures, Control Structures
                   5390: @subsection Selection
                   5391: @cindex selection control structures
                   5392: @cindex control structures for selection
                   5393: 
                   5394: @cindex @code{IF} control structure
                   5395: @example
1.29      crook    5396: @i{flag}
1.1       anton    5397: IF
1.29      crook    5398:   @i{code}
1.1       anton    5399: ENDIF
                   5400: @end example
1.21      crook    5401: @noindent
1.33      anton    5402: 
1.44      crook    5403: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5404: with any bit set represents truth) @i{code} is executed.
1.33      anton    5405: 
1.1       anton    5406: @example
1.29      crook    5407: @i{flag}
1.1       anton    5408: IF
1.29      crook    5409:   @i{code1}
1.1       anton    5410: ELSE
1.29      crook    5411:   @i{code2}
1.1       anton    5412: ENDIF
                   5413: @end example
                   5414: 
1.44      crook    5415: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5416: executed.
1.33      anton    5417: 
1.1       anton    5418: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5419: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5420: recommend using @code{ENDIF}, because it is less confusing for people
                   5421: who also know other languages (and is not prone to reinforcing negative
                   5422: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5423: system that only supplies @code{THEN} is simple:
                   5424: @example
1.82      anton    5425: : ENDIF   POSTPONE then ; immediate
1.1       anton    5426: @end example
                   5427: 
                   5428: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5429: (adv.)}  has the following meanings:
                   5430: @quotation
                   5431: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5432: (if you were there, then you saw them).
                   5433: @end quotation
                   5434: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5435: and many other programming languages has the meaning 3d.]
                   5436: 
1.21      crook    5437: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5438: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5439: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5440: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5441: @file{compat/control.fs}.
                   5442: 
                   5443: @cindex @code{CASE} control structure
                   5444: @example
1.29      crook    5445: @i{n}
1.1       anton    5446: CASE
1.29      crook    5447:   @i{n1} OF @i{code1} ENDOF
                   5448:   @i{n2} OF @i{code2} ENDOF
1.1       anton    5449:   @dots{}
1.68      anton    5450:   ( n ) @i{default-code} ( n )
1.1       anton    5451: ENDCASE
                   5452: @end example
                   5453: 
1.68      anton    5454: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If no
                   5455: @i{ni} matches, the optional @i{default-code} is executed. The optional
                   5456: default case can be added by simply writing the code after the last
                   5457: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
                   5458: not consume it.
1.1       anton    5459: 
1.69      anton    5460: @progstyle
                   5461: To keep the code understandable, you should ensure that on all paths
                   5462: through a selection construct the stack is changed in the same way
                   5463: (wrt. number and types of stack items consumed and pushed).
                   5464: 
1.1       anton    5465: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5466: @subsection Simple Loops
                   5467: @cindex simple loops
                   5468: @cindex loops without count 
                   5469: 
                   5470: @cindex @code{WHILE} loop
                   5471: @example
                   5472: BEGIN
1.29      crook    5473:   @i{code1}
                   5474:   @i{flag}
1.1       anton    5475: WHILE
1.29      crook    5476:   @i{code2}
1.1       anton    5477: REPEAT
                   5478: @end example
                   5479: 
1.29      crook    5480: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5481: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5482: false, execution continues after the @code{REPEAT}.
                   5483: 
                   5484: @cindex @code{UNTIL} loop
                   5485: @example
                   5486: BEGIN
1.29      crook    5487:   @i{code}
                   5488:   @i{flag}
1.1       anton    5489: UNTIL
                   5490: @end example
                   5491: 
1.29      crook    5492: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5493: 
1.69      anton    5494: @progstyle
                   5495: To keep the code understandable, a complete iteration of the loop should
                   5496: not change the number and types of the items on the stacks.
                   5497: 
1.1       anton    5498: @cindex endless loop
                   5499: @cindex loops, endless
                   5500: @example
                   5501: BEGIN
1.29      crook    5502:   @i{code}
1.1       anton    5503: AGAIN
                   5504: @end example
                   5505: 
                   5506: This is an endless loop.
                   5507: 
                   5508: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5509: @subsection Counted Loops
                   5510: @cindex counted loops
                   5511: @cindex loops, counted
                   5512: @cindex @code{DO} loops
                   5513: 
                   5514: The basic counted loop is:
                   5515: @example
1.29      crook    5516: @i{limit} @i{start}
1.1       anton    5517: ?DO
1.29      crook    5518:   @i{body}
1.1       anton    5519: LOOP
                   5520: @end example
                   5521: 
1.29      crook    5522: This performs one iteration for every integer, starting from @i{start}
                   5523: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5524: accessed with @code{i}. For example, the loop:
1.1       anton    5525: @example
                   5526: 10 0 ?DO
                   5527:   i .
                   5528: LOOP
                   5529: @end example
1.21      crook    5530: @noindent
                   5531: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5532: 
1.1       anton    5533: The index of the innermost loop can be accessed with @code{i}, the index
                   5534: of the next loop with @code{j}, and the index of the third loop with
                   5535: @code{k}.
                   5536: 
1.44      crook    5537: 
1.1       anton    5538: doc-i
                   5539: doc-j
                   5540: doc-k
                   5541: 
1.44      crook    5542: 
1.1       anton    5543: The loop control data are kept on the return stack, so there are some
1.21      crook    5544: restrictions on mixing return stack accesses and counted loop words. In
                   5545: particuler, if you put values on the return stack outside the loop, you
                   5546: cannot read them inside the loop@footnote{well, not in a way that is
                   5547: portable.}. If you put values on the return stack within a loop, you
                   5548: have to remove them before the end of the loop and before accessing the
                   5549: index of the loop.
1.1       anton    5550: 
                   5551: There are several variations on the counted loop:
                   5552: 
1.21      crook    5553: @itemize @bullet
                   5554: @item
                   5555: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5556: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5557: 
                   5558: @example
                   5559: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5560: @end example
                   5561: prints @code{0 1 2 3}
                   5562: 
1.1       anton    5563: 
1.21      crook    5564: @item
                   5565: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5566: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5567: return stack so @code{EXIT} can get to its return address. For example:
                   5568: 
                   5569: @example
                   5570: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5571: @end example
                   5572: prints @code{0 1 2 3}
                   5573: 
                   5574: 
                   5575: @item
1.29      crook    5576: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5577: (and @code{LOOP} iterates until they become equal by wrap-around
                   5578: arithmetic). This behaviour is usually not what you want. Therefore,
                   5579: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5580: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5581: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5582: unsigned loop parameters.
                   5583: 
1.21      crook    5584: @item
                   5585: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5586: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5587: if you know that the loop is entered in any case. Such knowledge tends
                   5588: to become invalid during maintenance of a program, and then the
                   5589: @code{DO} will make trouble.
                   5590: 
                   5591: @item
1.29      crook    5592: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5593: index by @i{n} instead of by 1. The loop is terminated when the border
                   5594: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5595: 
1.21      crook    5596: @example
                   5597: 4 0 +DO  i .  2 +LOOP
                   5598: @end example
                   5599: @noindent
                   5600: prints @code{0 2}
                   5601: 
                   5602: @example
                   5603: 4 1 +DO  i .  2 +LOOP
                   5604: @end example
                   5605: @noindent
                   5606: prints @code{1 3}
1.1       anton    5607: 
1.68      anton    5608: @item
1.1       anton    5609: @cindex negative increment for counted loops
                   5610: @cindex counted loops with negative increment
1.29      crook    5611: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5612: 
1.21      crook    5613: @example
                   5614: -1 0 ?DO  i .  -1 +LOOP
                   5615: @end example
                   5616: @noindent
                   5617: prints @code{0 -1}
1.1       anton    5618: 
1.21      crook    5619: @example
                   5620: 0 0 ?DO  i .  -1 +LOOP
                   5621: @end example
                   5622: prints nothing.
1.1       anton    5623: 
1.29      crook    5624: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5625: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5626: index by @i{u} each iteration. The loop is terminated when the border
                   5627: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5628: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5629: 
1.21      crook    5630: @example
                   5631: -2 0 -DO  i .  1 -LOOP
                   5632: @end example
                   5633: @noindent
                   5634: prints @code{0 -1}
1.1       anton    5635: 
1.21      crook    5636: @example
                   5637: -1 0 -DO  i .  1 -LOOP
                   5638: @end example
                   5639: @noindent
                   5640: prints @code{0}
                   5641: 
                   5642: @example
                   5643: 0 0 -DO  i .  1 -LOOP
                   5644: @end example
                   5645: @noindent
                   5646: prints nothing.
1.1       anton    5647: 
1.21      crook    5648: @end itemize
1.1       anton    5649: 
                   5650: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5651: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5652: for these words that uses only standard words is provided in
                   5653: @file{compat/loops.fs}.
1.1       anton    5654: 
                   5655: 
                   5656: @cindex @code{FOR} loops
1.26      crook    5657: Another counted loop is:
1.1       anton    5658: @example
1.29      crook    5659: @i{n}
1.1       anton    5660: FOR
1.29      crook    5661:   @i{body}
1.1       anton    5662: NEXT
                   5663: @end example
                   5664: This is the preferred loop of native code compiler writers who are too
1.26      crook    5665: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5666: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5667: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5668: Forth systems may behave differently, even if they support @code{FOR}
                   5669: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5670: 
                   5671: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5672: @subsection Arbitrary control structures
                   5673: @cindex control structures, user-defined
                   5674: 
                   5675: @cindex control-flow stack
                   5676: ANS Forth permits and supports using control structures in a non-nested
                   5677: way. Information about incomplete control structures is stored on the
                   5678: control-flow stack. This stack may be implemented on the Forth data
                   5679: stack, and this is what we have done in Gforth.
                   5680: 
                   5681: @cindex @code{orig}, control-flow stack item
                   5682: @cindex @code{dest}, control-flow stack item
                   5683: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5684: entry represents a backward branch target. A few words are the basis for
                   5685: building any control structure possible (except control structures that
                   5686: need storage, like calls, coroutines, and backtracking).
                   5687: 
1.44      crook    5688: 
1.1       anton    5689: doc-if
                   5690: doc-ahead
                   5691: doc-then
                   5692: doc-begin
                   5693: doc-until
                   5694: doc-again
                   5695: doc-cs-pick
                   5696: doc-cs-roll
                   5697: 
1.44      crook    5698: 
1.21      crook    5699: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5700: manipulate the control-flow stack in a portable way. Without them, you
                   5701: would need to know how many stack items are occupied by a control-flow
                   5702: entry (many systems use one cell. In Gforth they currently take three,
                   5703: but this may change in the future).
                   5704: 
1.1       anton    5705: Some standard control structure words are built from these words:
                   5706: 
1.44      crook    5707: 
1.1       anton    5708: doc-else
                   5709: doc-while
                   5710: doc-repeat
                   5711: 
1.44      crook    5712: 
                   5713: @noindent
1.1       anton    5714: Gforth adds some more control-structure words:
                   5715: 
1.44      crook    5716: 
1.1       anton    5717: doc-endif
                   5718: doc-?dup-if
                   5719: doc-?dup-0=-if
                   5720: 
1.44      crook    5721: 
                   5722: @noindent
1.1       anton    5723: Counted loop words constitute a separate group of words:
                   5724: 
1.44      crook    5725: 
1.1       anton    5726: doc-?do
                   5727: doc-+do
                   5728: doc-u+do
                   5729: doc--do
                   5730: doc-u-do
                   5731: doc-do
                   5732: doc-for
                   5733: doc-loop
                   5734: doc-+loop
                   5735: doc--loop
                   5736: doc-next
                   5737: doc-leave
                   5738: doc-?leave
                   5739: doc-unloop
                   5740: doc-done
                   5741: 
1.44      crook    5742: 
1.21      crook    5743: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5744: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5745: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5746: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5747: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5748: resolved (by using one of the loop-ending words or @code{DONE}).
                   5749: 
1.44      crook    5750: @noindent
1.26      crook    5751: Another group of control structure words are:
1.1       anton    5752: 
1.44      crook    5753: 
1.1       anton    5754: doc-case
                   5755: doc-endcase
                   5756: doc-of
                   5757: doc-endof
                   5758: 
1.44      crook    5759: 
1.21      crook    5760: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5761: @code{CS-ROLL}.
1.1       anton    5762: 
                   5763: @subsubsection Programming Style
1.47      crook    5764: @cindex control structures programming style
                   5765: @cindex programming style, arbitrary control structures
1.1       anton    5766: 
                   5767: In order to ensure readability we recommend that you do not create
                   5768: arbitrary control structures directly, but define new control structure
                   5769: words for the control structure you want and use these words in your
1.26      crook    5770: program. For example, instead of writing:
1.1       anton    5771: 
                   5772: @example
1.26      crook    5773: BEGIN
1.1       anton    5774:   ...
1.26      crook    5775: IF [ 1 CS-ROLL ]
1.1       anton    5776:   ...
1.26      crook    5777: AGAIN THEN
1.1       anton    5778: @end example
                   5779: 
1.21      crook    5780: @noindent
1.1       anton    5781: we recommend defining control structure words, e.g.,
                   5782: 
                   5783: @example
1.26      crook    5784: : WHILE ( DEST -- ORIG DEST )
                   5785:  POSTPONE IF
                   5786:  1 CS-ROLL ; immediate
                   5787: 
                   5788: : REPEAT ( orig dest -- )
                   5789:  POSTPONE AGAIN
                   5790:  POSTPONE THEN ; immediate
1.1       anton    5791: @end example
                   5792: 
1.21      crook    5793: @noindent
1.1       anton    5794: and then using these to create the control structure:
                   5795: 
                   5796: @example
1.26      crook    5797: BEGIN
1.1       anton    5798:   ...
1.26      crook    5799: WHILE
1.1       anton    5800:   ...
1.26      crook    5801: REPEAT
1.1       anton    5802: @end example
                   5803: 
                   5804: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5805: @code{WHILE} are predefined, so in this example it would not be
                   5806: necessary to define them.
                   5807: 
                   5808: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5809: @subsection Calls and returns
                   5810: @cindex calling a definition
                   5811: @cindex returning from a definition
                   5812: 
1.3       anton    5813: @cindex recursive definitions
                   5814: A definition can be called simply be writing the name of the definition
1.26      crook    5815: to be called. Normally a definition is invisible during its own
1.3       anton    5816: definition. If you want to write a directly recursive definition, you
1.26      crook    5817: can use @code{recursive} to make the current definition visible, or
                   5818: @code{recurse} to call the current definition directly.
1.3       anton    5819: 
1.44      crook    5820: 
1.3       anton    5821: doc-recursive
                   5822: doc-recurse
                   5823: 
1.44      crook    5824: 
1.21      crook    5825: @comment TODO add example of the two recursion methods
1.12      anton    5826: @quotation
                   5827: @progstyle
                   5828: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5829: definition by name is more descriptive (if the name is well-chosen) than
                   5830: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5831: implementation, it is much better to read (and think) ``now sort the
                   5832: partitions'' than to read ``now do a recursive call''.
                   5833: @end quotation
1.3       anton    5834: 
1.29      crook    5835: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5836: 
                   5837: @example
1.28      crook    5838: Defer foo
1.3       anton    5839: 
                   5840: : bar ( ... -- ... )
                   5841:  ... foo ... ;
                   5842: 
                   5843: :noname ( ... -- ... )
                   5844:  ... bar ... ;
                   5845: IS foo
                   5846: @end example
                   5847: 
1.44      crook    5848: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33      anton    5849: 
1.26      crook    5850: The current definition returns control to the calling definition when
1.33      anton    5851: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5852: 
                   5853: doc-exit
                   5854: doc-;s
                   5855: 
1.44      crook    5856: 
1.1       anton    5857: @node Exception Handling,  , Calls and returns, Control Structures
                   5858: @subsection Exception Handling
1.26      crook    5859: @cindex exceptions
1.1       anton    5860: 
1.68      anton    5861: @c quit is a very bad idea for error handling, 
                   5862: @c because it does not translate into a THROW
                   5863: @c it also does not belong into this chapter
                   5864: 
                   5865: If a word detects an error condition that it cannot handle, it can
                   5866: @code{throw} an exception.  In the simplest case, this will terminate
                   5867: your program, and report an appropriate error.
1.21      crook    5868: 
1.68      anton    5869: doc-throw
1.1       anton    5870: 
1.69      anton    5871: @code{Throw} consumes a cell-sized error number on the stack. There are
                   5872: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
                   5873: Gforth (and most other systems) you can use the iors produced by various
                   5874: words as error numbers (e.g., a typical use of @code{allocate} is
                   5875: @code{allocate throw}).  Gforth also provides the word @code{exception}
                   5876: to define your own error numbers (with decent error reporting); an ANS
                   5877: Forth version of this word (but without the error messages) is available
                   5878: in @code{compat/except.fs}.  And finally, you can use your own error
1.68      anton    5879: numbers (anything outside the range -4095..0), but won't get nice error
                   5880: messages, only numbers.  For example, try:
                   5881: 
                   5882: @example
1.69      anton    5883: -10 throw                    \ ANS defined
                   5884: -267 throw                   \ system defined
                   5885: s" my error" exception throw \ user defined
                   5886: 7 throw                      \ arbitrary number
1.68      anton    5887: @end example
                   5888: 
                   5889: doc---exception-exception
1.1       anton    5890: 
1.69      anton    5891: A common idiom to @code{THROW} a specific error if a flag is true is
                   5892: this:
                   5893: 
                   5894: @example
                   5895: @code{( flag ) 0<> @i{errno} and throw}
                   5896: @end example
                   5897: 
                   5898: Your program can provide exception handlers to catch exceptions.  An
                   5899: exception handler can be used to correct the problem, or to clean up
                   5900: some data structures and just throw the exception to the next exception
                   5901: handler.  Note that @code{throw} jumps to the dynamically innermost
                   5902: exception handler.  The system's exception handler is outermost, and just
                   5903: prints an error and restarts command-line interpretation (or, in batch
                   5904: mode (i.e., while processing the shell command line), leaves Gforth).
1.1       anton    5905: 
1.68      anton    5906: The ANS Forth way to catch exceptions is @code{catch}:
1.1       anton    5907: 
1.68      anton    5908: doc-catch
                   5909: 
                   5910: The most common use of exception handlers is to clean up the state when
                   5911: an error happens.  E.g.,
1.1       anton    5912: 
1.26      crook    5913: @example
1.68      anton    5914: base @ >r hex \ actually the hex should be inside foo, or we h
                   5915: ['] foo catch ( nerror|0 )
                   5916: r> base !
1.69      anton    5917: ( nerror|0 ) throw \ pass it on
1.26      crook    5918: @end example
1.1       anton    5919: 
1.69      anton    5920: A use of @code{catch} for handling the error @code{myerror} might look
                   5921: like this:
1.44      crook    5922: 
1.68      anton    5923: @example
1.69      anton    5924: ['] foo catch
                   5925: CASE
                   5926:   myerror OF ... ( do something about it ) ENDOF
                   5927:   dup throw \ default: pass other errors on, do nothing on non-errors
                   5928: ENDCASE
1.68      anton    5929: @end example
1.44      crook    5930: 
1.68      anton    5931: Having to wrap the code into a separate word is often cumbersome,
                   5932: therefore Gforth provides an alternative syntax:
1.1       anton    5933: 
                   5934: @example
1.69      anton    5935: TRY
1.68      anton    5936:   @i{code1}
1.69      anton    5937: RECOVER     \ optional
1.68      anton    5938:   @i{code2} \ optional
1.69      anton    5939: ENDTRY
1.1       anton    5940: @end example
                   5941: 
1.68      anton    5942: This performs @i{Code1}.  If @i{code1} completes normally, execution
                   5943: continues after the @code{endtry}.  If @i{Code1} throws, the stacks are
                   5944: reset to the state during @code{try}, the throw value is pushed on the
                   5945: data stack, and execution constinues at @i{code2}, and finally falls
1.92      anton    5946: through the @code{endtry} into the following code.
1.26      crook    5947: 
1.68      anton    5948: doc-try
                   5949: doc-recover
                   5950: doc-endtry
1.26      crook    5951: 
1.69      anton    5952: The cleanup example from above in this syntax:
1.26      crook    5953: 
1.68      anton    5954: @example
1.69      anton    5955: base @ >r TRY
1.68      anton    5956:   hex foo \ now the hex is placed correctly
1.69      anton    5957:   0       \ value for throw
1.92      anton    5958: RECOVER ENDTRY
1.68      anton    5959: r> base ! throw
1.1       anton    5960: @end example
                   5961: 
1.69      anton    5962: And here's the error handling example:
1.1       anton    5963: 
1.68      anton    5964: @example
1.69      anton    5965: TRY
1.68      anton    5966:   foo
1.69      anton    5967: RECOVER
                   5968:   CASE
                   5969:     myerror OF ... ( do something about it ) ENDOF
                   5970:     throw \ pass other errors on
                   5971:   ENDCASE
                   5972: ENDTRY
1.68      anton    5973: @end example
1.1       anton    5974: 
1.69      anton    5975: @progstyle
                   5976: As usual, you should ensure that the stack depth is statically known at
                   5977: the end: either after the @code{throw} for passing on errors, or after
                   5978: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
                   5979: selection construct for handling the error).
                   5980: 
1.68      anton    5981: There are two alternatives to @code{throw}: @code{Abort"} is conditional
                   5982: and you can provide an error message.  @code{Abort} just produces an
                   5983: ``Aborted'' error.
1.1       anton    5984: 
1.68      anton    5985: The problem with these words is that exception handlers cannot
                   5986: differentiate between different @code{abort"}s; they just look like
                   5987: @code{-2 throw} to them (the error message cannot be accessed by
                   5988: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
                   5989: exception handlers.
1.44      crook    5990: 
1.68      anton    5991: doc-abort"
1.26      crook    5992: doc-abort
1.29      crook    5993: 
                   5994: 
1.44      crook    5995: 
1.29      crook    5996: @c -------------------------------------------------------------
1.47      crook    5997: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    5998: @section Defining Words
                   5999: @cindex defining words
                   6000: 
1.47      crook    6001: Defining words are used to extend Forth by creating new entries in the dictionary.
                   6002: 
1.29      crook    6003: @menu
1.67      anton    6004: * CREATE::                      
1.44      crook    6005: * Variables::                   Variables and user variables
1.67      anton    6006: * Constants::                   
1.44      crook    6007: * Values::                      Initialised variables
1.67      anton    6008: * Colon Definitions::           
1.44      crook    6009: * Anonymous Definitions::       Definitions without names
1.69      anton    6010: * Supplying names::             Passing definition names as strings
1.67      anton    6011: * User-defined Defining Words::  
1.44      crook    6012: * Deferred words::              Allow forward references
1.67      anton    6013: * Aliases::                     
1.29      crook    6014: @end menu
                   6015: 
1.44      crook    6016: @node CREATE, Variables, Defining Words, Defining Words
                   6017: @subsection @code{CREATE}
1.29      crook    6018: @cindex simple defining words
                   6019: @cindex defining words, simple
                   6020: 
                   6021: Defining words are used to create new entries in the dictionary. The
                   6022: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   6023: this:
                   6024: 
                   6025: @example
                   6026: CREATE new-word1
                   6027: @end example
                   6028: 
1.69      anton    6029: @code{CREATE} is a parsing word, i.e., it takes an argument from the
                   6030: input stream (@code{new-word1} in our example).  It generates a
                   6031: dictionary entry for @code{new-word1}. When @code{new-word1} is
                   6032: executed, all that it does is leave an address on the stack. The address
                   6033: represents the value of the data space pointer (@code{HERE}) at the time
                   6034: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
                   6035: associating a name with the address of a region of memory.
1.29      crook    6036: 
1.34      anton    6037: doc-create
                   6038: 
1.69      anton    6039: Note that in ANS Forth guarantees only for @code{create} that its body
                   6040: is in dictionary data space (i.e., where @code{here}, @code{allot}
                   6041: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
                   6042: @code{create}d words can be modified with @code{does>}
                   6043: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
                   6044: can only be applied to @code{create}d words.
                   6045: 
1.29      crook    6046: By extending this example to reserve some memory in data space, we end
1.69      anton    6047: up with something like a @i{variable}. Here are two different ways to do
                   6048: it:
1.29      crook    6049: 
                   6050: @example
                   6051: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   6052: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   6053: @end example
                   6054: 
                   6055: The variable can be examined and modified using @code{@@} (``fetch'') and
                   6056: @code{!} (``store'') like this:
                   6057: 
                   6058: @example
                   6059: new-word2 @@ .      \ get address, fetch from it and display
                   6060: 1234 new-word2 !   \ new value, get address, store to it
                   6061: @end example
                   6062: 
1.44      crook    6063: @cindex arrays
                   6064: A similar mechanism can be used to create arrays. For example, an
                   6065: 80-character text input buffer:
1.29      crook    6066: 
                   6067: @example
1.44      crook    6068: CREATE text-buf 80 chars allot
                   6069: 
                   6070: text-buf 0 chars c@@ \ the 1st character (offset 0)
                   6071: text-buf 3 chars c@@ \ the 4th character (offset 3)
                   6072: @end example
1.29      crook    6073: 
1.44      crook    6074: You can build arbitrarily complex data structures by allocating
1.49      anton    6075: appropriate areas of memory. For further discussions of this, and to
1.66      anton    6076: learn about some Gforth tools that make it easier,
1.49      anton    6077: @xref{Structures}.
1.44      crook    6078: 
                   6079: 
                   6080: @node Variables, Constants, CREATE, Defining Words
                   6081: @subsection Variables
                   6082: @cindex variables
                   6083: 
                   6084: The previous section showed how a sequence of commands could be used to
                   6085: generate a variable.  As a final refinement, the whole code sequence can
                   6086: be wrapped up in a defining word (pre-empting the subject of the next
                   6087: section), making it easier to create new variables:
                   6088: 
                   6089: @example
                   6090: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   6091: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   6092: 
                   6093: myvariableX foo \ variable foo starts off with an unknown value
                   6094: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    6095: 
                   6096: 45 3 * foo !   \ set foo to 135
                   6097: 1234 joe !     \ set joe to 1234
                   6098: 3 joe +!       \ increment joe by 3.. to 1237
                   6099: @end example
                   6100: 
                   6101: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    6102: Forth already has a definition @code{Variable}. ANS Forth does not
1.69      anton    6103: guarantee that a @code{Variable} is initialised when it is created
                   6104: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
                   6105: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
                   6106: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    6107: @code{fvariable} for double and floating-point variables, respectively
1.69      anton    6108: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47      crook    6109: store a boolean, you can use @code{on} and @code{off} to toggle its
                   6110: state.
1.29      crook    6111: 
1.34      anton    6112: doc-variable
                   6113: doc-2variable
                   6114: doc-fvariable
                   6115: 
1.29      crook    6116: @cindex user variables
                   6117: @cindex user space
                   6118: The defining word @code{User} behaves in the same way as @code{Variable}.
                   6119: The difference is that it reserves space in @i{user (data) space} rather
                   6120: than normal data space. In a Forth system that has a multi-tasker, each
                   6121: task has its own set of user variables.
                   6122: 
1.34      anton    6123: doc-user
1.67      anton    6124: @c doc-udp
                   6125: @c doc-uallot
1.34      anton    6126: 
1.29      crook    6127: @comment TODO is that stuff about user variables strictly correct? Is it
                   6128: @comment just terminal tasks that have user variables?
                   6129: @comment should document tasker.fs (with some examples) elsewhere
                   6130: @comment in this manual, then expand on user space and user variables.
                   6131: 
1.44      crook    6132: @node Constants, Values, Variables, Defining Words
                   6133: @subsection Constants
                   6134: @cindex constants
                   6135: 
                   6136: @code{Constant} allows you to declare a fixed value and refer to it by
                   6137: name. For example:
1.29      crook    6138: 
                   6139: @example
                   6140: 12 Constant INCHES-PER-FOOT
                   6141: 3E+08 fconstant SPEED-O-LIGHT
                   6142: @end example
                   6143: 
                   6144: A @code{Variable} can be both read and written, so its run-time
                   6145: behaviour is to supply an address through which its current value can be
                   6146: manipulated. In contrast, the value of a @code{Constant} cannot be
                   6147: changed once it has been declared@footnote{Well, often it can be -- but
                   6148: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   6149: on).} so it's not necessary to supply the address -- it is more
                   6150: efficient to return the value of the constant directly. That's exactly
                   6151: what happens; the run-time effect of a constant is to put its value on
1.49      anton    6152: the top of the stack (You can find one
                   6153: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    6154: 
1.69      anton    6155: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29      crook    6156: double and floating-point constants, respectively.
                   6157: 
1.34      anton    6158: doc-constant
                   6159: doc-2constant
                   6160: doc-fconstant
                   6161: 
                   6162: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    6163: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   6164: @c constant, use it and then delete the definition of the constant..
1.69      anton    6165: 
                   6166: @c anton->An ANS Forth system can compile a constant to a literal; On
                   6167: @c decompilation you would see only the number, just as if it had been used
                   6168: @c in the first place.  The word will stay, of course, but it will only be
                   6169: @c used by the text interpreter (no run-time duties, except when it is 
                   6170: @c POSTPONEd or somesuch).
                   6171: 
                   6172: @c nac:
1.44      crook    6173: @c I agree that it's rather deep, but IMO it is an important difference
                   6174: @c relative to other programming languages.. often it's annoying: it
                   6175: @c certainly changes my programming style relative to C.
                   6176: 
1.69      anton    6177: @c anton: In what way?
                   6178: 
1.29      crook    6179: Constants in Forth behave differently from their equivalents in other
                   6180: programming languages. In other languages, a constant (such as an EQU in
                   6181: assembler or a #define in C) only exists at compile-time; in the
                   6182: executable program the constant has been translated into an absolute
                   6183: number and, unless you are using a symbolic debugger, it's impossible to
                   6184: know what abstract thing that number represents. In Forth a constant has
1.44      crook    6185: an entry in the header space and remains there after the code that uses
                   6186: it has been defined. In fact, it must remain in the dictionary since it
                   6187: has run-time duties to perform. For example:
1.29      crook    6188: 
                   6189: @example
                   6190: 12 Constant INCHES-PER-FOOT
                   6191: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   6192: @end example
                   6193: 
                   6194: @cindex in-lining of constants
                   6195: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   6196: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   6197: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   6198: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   6199: attempt to optimise constants by in-lining them where they are used. You
                   6200: can force Gforth to in-line a constant like this:
                   6201: 
                   6202: @example
                   6203: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   6204: @end example
                   6205: 
                   6206: If you use @code{see} to decompile @i{this} version of
                   6207: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    6208: longer present. To understand how this works, read
                   6209: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    6210: 
                   6211: In-lining constants in this way might improve execution time
                   6212: fractionally, and can ensure that a constant is now only referenced at
                   6213: compile-time. However, the definition of the constant still remains in
                   6214: the dictionary. Some Forth compilers provide a mechanism for controlling
                   6215: a second dictionary for holding transient words such that this second
                   6216: dictionary can be deleted later in order to recover memory
                   6217: space. However, there is no standard way of doing this.
                   6218: 
                   6219: 
1.44      crook    6220: @node Values, Colon Definitions, Constants, Defining Words
                   6221: @subsection Values
                   6222: @cindex values
1.34      anton    6223: 
1.69      anton    6224: A @code{Value} behaves like a @code{Constant}, but it can be changed.
                   6225: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
                   6226: (not in ANS Forth) you can access (and change) a @code{value} also with
                   6227: @code{>body}.
                   6228: 
                   6229: Here are some
                   6230: examples:
1.29      crook    6231: 
                   6232: @example
1.69      anton    6233: 12 Value APPLES     \ Define APPLES with an initial value of 12
                   6234: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
                   6235: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
                   6236: APPLES              \ puts 35 on the top of the stack.
1.29      crook    6237: @end example
                   6238: 
1.44      crook    6239: doc-value
                   6240: doc-to
1.29      crook    6241: 
1.35      anton    6242: 
1.69      anton    6243: 
1.44      crook    6244: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   6245: @subsection Colon Definitions
                   6246: @cindex colon definitions
1.35      anton    6247: 
                   6248: @example
1.44      crook    6249: : name ( ... -- ... )
                   6250:     word1 word2 word3 ;
1.29      crook    6251: @end example
                   6252: 
1.44      crook    6253: @noindent
                   6254: Creates a word called @code{name} that, upon execution, executes
                   6255: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    6256: 
1.49      anton    6257: The explanation above is somewhat superficial. For simple examples of
                   6258: colon definitions see @ref{Your first definition}.  For an in-depth
1.66      anton    6259: discussion of some of the issues involved, @xref{Interpretation and
1.49      anton    6260: Compilation Semantics}.
1.29      crook    6261: 
1.44      crook    6262: doc-:
                   6263: doc-;
1.1       anton    6264: 
1.34      anton    6265: 
1.69      anton    6266: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44      crook    6267: @subsection Anonymous Definitions
                   6268: @cindex colon definitions
                   6269: @cindex defining words without name
1.34      anton    6270: 
1.44      crook    6271: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   6272: name. You can do this with:
1.1       anton    6273: 
1.44      crook    6274: doc-:noname
1.1       anton    6275: 
1.44      crook    6276: This leaves the execution token for the word on the stack after the
                   6277: closing @code{;}. Here's an example in which a deferred word is
                   6278: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6279: 
1.29      crook    6280: @example
1.44      crook    6281: Defer deferred
                   6282: :noname ( ... -- ... )
                   6283:   ... ;
                   6284: IS deferred
1.29      crook    6285: @end example
1.26      crook    6286: 
1.44      crook    6287: @noindent
                   6288: Gforth provides an alternative way of doing this, using two separate
                   6289: words:
1.27      crook    6290: 
1.44      crook    6291: doc-noname
                   6292: @cindex execution token of last defined word
                   6293: doc-lastxt
1.1       anton    6294: 
1.44      crook    6295: @noindent
                   6296: The previous example can be rewritten using @code{noname} and
                   6297: @code{lastxt}:
1.1       anton    6298: 
1.26      crook    6299: @example
1.44      crook    6300: Defer deferred
                   6301: noname : ( ... -- ... )
                   6302:   ... ;
                   6303: lastxt IS deferred
1.26      crook    6304: @end example
1.1       anton    6305: 
1.29      crook    6306: @noindent
1.44      crook    6307: @code{noname} works with any defining word, not just @code{:}.
                   6308: 
                   6309: @code{lastxt} also works when the last word was not defined as
1.71      anton    6310: @code{noname}.  It does not work for combined words, though.  It also has
                   6311: the useful property that is is valid as soon as the header for a
                   6312: definition has been built. Thus:
1.44      crook    6313: 
                   6314: @example
                   6315: lastxt . : foo [ lastxt . ] ; ' foo .
                   6316: @end example
1.1       anton    6317: 
1.44      crook    6318: @noindent
                   6319: prints 3 numbers; the last two are the same.
1.26      crook    6320: 
1.69      anton    6321: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
                   6322: @subsection Supplying the name of a defined word
                   6323: @cindex names for defined words
                   6324: @cindex defining words, name given in a string
                   6325: 
                   6326: By default, a defining word takes the name for the defined word from the
                   6327: input stream. Sometimes you want to supply the name from a string. You
                   6328: can do this with:
                   6329: 
                   6330: doc-nextname
                   6331: 
                   6332: For example:
                   6333: 
                   6334: @example
                   6335: s" foo" nextname create
                   6336: @end example
                   6337: 
                   6338: @noindent
                   6339: is equivalent to:
                   6340: 
                   6341: @example
                   6342: create foo
                   6343: @end example
                   6344: 
                   6345: @noindent
                   6346: @code{nextname} works with any defining word.
                   6347: 
1.1       anton    6348: 
1.69      anton    6349: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26      crook    6350: @subsection User-defined Defining Words
                   6351: @cindex user-defined defining words
                   6352: @cindex defining words, user-defined
1.1       anton    6353: 
1.29      crook    6354: You can create a new defining word by wrapping defining-time code around
                   6355: an existing defining word and putting the sequence in a colon
1.69      anton    6356: definition. 
                   6357: 
                   6358: @c anton: This example is very complex and leads in a quite different
                   6359: @c direction from the CREATE-DOES> stuff that follows.  It should probably
                   6360: @c be done elsewhere, or as a subsubsection of this subsection (or as a
                   6361: @c subsection of Defining Words)
                   6362: 
                   6363: For example, suppose that you have a word @code{stats} that
1.29      crook    6364: gathers statistics about colon definitions given the @i{xt} of the
                   6365: definition, and you want every colon definition in your application to
                   6366: make a call to @code{stats}. You can define and use a new version of
                   6367: @code{:} like this:
                   6368: 
                   6369: @example
                   6370: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6371:   ... ;  \ other code
                   6372: 
                   6373: : my: : lastxt postpone literal ['] stats compile, ;
                   6374: 
                   6375: my: foo + - ;
                   6376: @end example
                   6377: 
                   6378: When @code{foo} is defined using @code{my:} these steps occur:
                   6379: 
                   6380: @itemize @bullet
                   6381: @item
                   6382: @code{my:} is executed.
                   6383: @item
                   6384: The @code{:} within the definition (the one between @code{my:} and
                   6385: @code{lastxt}) is executed, and does just what it always does; it parses
                   6386: the input stream for a name, builds a dictionary header for the name
                   6387: @code{foo} and switches @code{state} from interpret to compile.
                   6388: @item
                   6389: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
                   6390: being defined -- @code{foo} -- onto the stack.
                   6391: @item
                   6392: The code that was produced by @code{postpone literal} is executed; this
                   6393: causes the value on the stack to be compiled as a literal in the code
                   6394: area of @code{foo}.
                   6395: @item
                   6396: The code @code{['] stats} compiles a literal into the definition of
                   6397: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6398: execution token for @code{stats} -- is layed down in the code area of
                   6399: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6400: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6401: in the code area is implementation-dependent. A threaded implementation
                   6402: might spit out the execution token directly whilst another
                   6403: implementation might spit out a native code sequence.}.
                   6404: @item
                   6405: At this point, the execution of @code{my:} is complete, and control
                   6406: returns to the text interpreter. The text interpreter is in compile
                   6407: state, so subsequent text @code{+ -} is compiled into the definition of
                   6408: @code{foo} and the @code{;} terminates the definition as always.
                   6409: @end itemize
                   6410: 
                   6411: You can use @code{see} to decompile a word that was defined using
                   6412: @code{my:} and see how it is different from a normal @code{:}
                   6413: definition. For example:
                   6414: 
                   6415: @example
                   6416: : bar + - ;  \ like foo but using : rather than my:
                   6417: see bar
                   6418: : bar
                   6419:   + - ;
                   6420: see foo
                   6421: : foo
                   6422:   107645672 stats + - ;
                   6423: 
                   6424: \ use ' stats . to show that 107645672 is the xt for stats
                   6425: @end example
                   6426: 
                   6427: You can use techniques like this to make new defining words in terms of
                   6428: @i{any} existing defining word.
1.1       anton    6429: 
                   6430: 
1.29      crook    6431: @cindex defining defining words
1.26      crook    6432: @cindex @code{CREATE} ... @code{DOES>}
                   6433: If you want the words defined with your defining words to behave
                   6434: differently from words defined with standard defining words, you can
                   6435: write your defining word like this:
1.1       anton    6436: 
                   6437: @example
1.26      crook    6438: : def-word ( "name" -- )
1.29      crook    6439:     CREATE @i{code1}
1.26      crook    6440: DOES> ( ... -- ... )
1.29      crook    6441:     @i{code2} ;
1.26      crook    6442: 
                   6443: def-word name
1.1       anton    6444: @end example
                   6445: 
1.29      crook    6446: @cindex child words
                   6447: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6448: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6449: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6450: is not executed at this time. The word @code{name} is sometimes called a
                   6451: @dfn{child} of @code{def-word}.
                   6452: 
                   6453: When you execute @code{name}, the address of the body of @code{name} is
                   6454: put on the data stack and @i{code2} is executed (the address of the body
                   6455: of @code{name} is the address @code{HERE} returns immediately after the
1.69      anton    6456: @code{CREATE}, i.e., the address a @code{create}d word returns by
                   6457: default).
                   6458: 
                   6459: @c anton:
                   6460: @c www.dictionary.com says:
                   6461: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
                   6462: @c several generations of absence, usually caused by the chance
                   6463: @c recombination of genes.  2.An individual or a part that exhibits
                   6464: @c atavism. Also called throwback.  3.The return of a trait or recurrence
                   6465: @c of previous behavior after a period of absence.
                   6466: @c
                   6467: @c Doesn't seem to fit.
1.29      crook    6468: 
1.69      anton    6469: @c @cindex atavism in child words
1.33      anton    6470: You can use @code{def-word} to define a set of child words that behave
1.69      anton    6471: similarly; they all have a common run-time behaviour determined by
                   6472: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
                   6473: body of the child word. The structure of the data is common to all
                   6474: children of @code{def-word}, but the data values are specific -- and
                   6475: private -- to each child word. When a child word is executed, the
                   6476: address of its private data area is passed as a parameter on TOS to be
                   6477: used and manipulated@footnote{It is legitimate both to read and write to
                   6478: this data area.} by @i{code2}.
1.29      crook    6479: 
                   6480: The two fragments of code that make up the defining words act (are
                   6481: executed) at two completely separate times:
1.1       anton    6482: 
1.29      crook    6483: @itemize @bullet
                   6484: @item
                   6485: At @i{define time}, the defining word executes @i{code1} to generate a
                   6486: child word
                   6487: @item
                   6488: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6489: is executed, using parameters (data) that are private and specific to
                   6490: the child word.
                   6491: @end itemize
                   6492: 
1.44      crook    6493: Another way of understanding the behaviour of @code{def-word} and
                   6494: @code{name} is to say that, if you make the following definitions:
1.33      anton    6495: @example
                   6496: : def-word1 ( "name" -- )
                   6497:     CREATE @i{code1} ;
                   6498: 
                   6499: : action1 ( ... -- ... )
                   6500:     @i{code2} ;
                   6501: 
                   6502: def-word1 name1
                   6503: @end example
                   6504: 
1.44      crook    6505: @noindent
                   6506: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6507: 
1.29      crook    6508: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6509: 
1.1       anton    6510: @example
1.29      crook    6511: : CONSTANT ( w "name" -- )
                   6512:     CREATE ,
1.26      crook    6513: DOES> ( -- w )
                   6514:     @@ ;
1.1       anton    6515: @end example
                   6516: 
1.29      crook    6517: @comment There is a beautiful description of how this works and what
                   6518: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6519: @comment commentary on the Counting Fruits problem.
                   6520: 
                   6521: When you create a constant with @code{5 CONSTANT five}, a set of
                   6522: define-time actions take place; first a new word @code{five} is created,
                   6523: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6524: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6525: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6526: no code of its own; it simply contains a data field and a pointer to the
                   6527: code that follows @code{DOES>} in its defining word. That makes words
                   6528: created in this way very compact.
                   6529: 
                   6530: The final example in this section is intended to remind you that space
                   6531: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6532: both read and written by a Standard program@footnote{Exercise: use this
                   6533: example as a starting point for your own implementation of @code{Value}
                   6534: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6535: @code{[']}.}:
                   6536: 
                   6537: @example
                   6538: : foo ( "name" -- )
                   6539:     CREATE -1 ,
                   6540: DOES> ( -- )
1.33      anton    6541:     @@ . ;
1.29      crook    6542: 
                   6543: foo first-word
                   6544: foo second-word
                   6545: 
                   6546: 123 ' first-word >BODY !
                   6547: @end example
                   6548: 
                   6549: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6550: have executed it to get the address of its data field. However, since it
                   6551: was defined to have @code{DOES>} actions, its execution semantics are to
                   6552: perform those @code{DOES>} actions. To get the address of its data field
                   6553: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6554: translate the xt into the address of the data field.  When you execute
                   6555: @code{first-word}, it will display @code{123}. When you execute
                   6556: @code{second-word} it will display @code{-1}.
1.26      crook    6557: 
                   6558: @cindex stack effect of @code{DOES>}-parts
                   6559: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6560: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6561: the stack effect of the defined words, not the stack effect of the
                   6562: following code (the following code expects the address of the body on
                   6563: the top of stack, which is not reflected in the stack comment). This is
                   6564: the convention that I use and recommend (it clashes a bit with using
                   6565: locals declarations for stack effect specification, though).
1.1       anton    6566: 
1.53      anton    6567: @menu
                   6568: * CREATE..DOES> applications::  
                   6569: * CREATE..DOES> details::       
1.63      anton    6570: * Advanced does> usage example::  
1.91      anton    6571: * @code{Const-does>}::          
1.53      anton    6572: @end menu
                   6573: 
                   6574: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26      crook    6575: @subsubsection Applications of @code{CREATE..DOES>}
                   6576: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6577: 
1.26      crook    6578: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6579: 
1.26      crook    6580: @cindex factoring similar colon definitions
                   6581: When you see a sequence of code occurring several times, and you can
                   6582: identify a meaning, you will factor it out as a colon definition. When
                   6583: you see similar colon definitions, you can factor them using
                   6584: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6585: that look very similar:
1.1       anton    6586: @example
1.26      crook    6587: : ori, ( reg-target reg-source n -- )
                   6588:     0 asm-reg-reg-imm ;
                   6589: : andi, ( reg-target reg-source n -- )
                   6590:     1 asm-reg-reg-imm ;
1.1       anton    6591: @end example
                   6592: 
1.26      crook    6593: @noindent
                   6594: This could be factored with:
                   6595: @example
                   6596: : reg-reg-imm ( op-code -- )
                   6597:     CREATE ,
                   6598: DOES> ( reg-target reg-source n -- )
                   6599:     @@ asm-reg-reg-imm ;
                   6600: 
                   6601: 0 reg-reg-imm ori,
                   6602: 1 reg-reg-imm andi,
                   6603: @end example
1.1       anton    6604: 
1.26      crook    6605: @cindex currying
                   6606: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6607: supply a part of the parameters for a word (known as @dfn{currying} in
                   6608: the functional language community). E.g., @code{+} needs two
                   6609: parameters. Creating versions of @code{+} with one parameter fixed can
                   6610: be done like this:
1.82      anton    6611: 
1.1       anton    6612: @example
1.82      anton    6613: : curry+ ( n1 "name" -- )
1.26      crook    6614:     CREATE ,
                   6615: DOES> ( n2 -- n1+n2 )
                   6616:     @@ + ;
                   6617: 
                   6618:  3 curry+ 3+
                   6619: -2 curry+ 2-
1.1       anton    6620: @end example
                   6621: 
1.91      anton    6622: 
1.63      anton    6623: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6624: @subsubsection The gory details of @code{CREATE..DOES>}
                   6625: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6626: 
1.26      crook    6627: doc-does>
1.1       anton    6628: 
1.26      crook    6629: @cindex @code{DOES>} in a separate definition
                   6630: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6631: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6632: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6633: @example
                   6634: : does1 
                   6635: DOES> ( ... -- ... )
1.44      crook    6636:     ... ;
                   6637: 
                   6638: : does2
                   6639: DOES> ( ... -- ... )
                   6640:     ... ;
                   6641: 
                   6642: : def-word ( ... -- ... )
                   6643:     create ...
                   6644:     IF
                   6645:        does1
                   6646:     ELSE
                   6647:        does2
                   6648:     ENDIF ;
                   6649: @end example
                   6650: 
                   6651: In this example, the selection of whether to use @code{does1} or
1.69      anton    6652: @code{does2} is made at definition-time; at the time that the child word is
1.44      crook    6653: @code{CREATE}d.
                   6654: 
                   6655: @cindex @code{DOES>} in interpretation state
                   6656: In a standard program you can apply a @code{DOES>}-part only if the last
                   6657: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6658: will override the behaviour of the last word defined in any case. In a
                   6659: standard program, you can use @code{DOES>} only in a colon
                   6660: definition. In Gforth, you can also use it in interpretation state, in a
                   6661: kind of one-shot mode; for example:
                   6662: @example
                   6663: CREATE name ( ... -- ... )
                   6664:   @i{initialization}
                   6665: DOES>
                   6666:   @i{code} ;
                   6667: @end example
                   6668: 
                   6669: @noindent
                   6670: is equivalent to the standard:
                   6671: @example
                   6672: :noname
                   6673: DOES>
                   6674:     @i{code} ;
                   6675: CREATE name EXECUTE ( ... -- ... )
                   6676:     @i{initialization}
                   6677: @end example
                   6678: 
1.53      anton    6679: doc->body
                   6680: 
1.91      anton    6681: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
1.63      anton    6682: @subsubsection Advanced does> usage example
                   6683: 
                   6684: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
                   6685: for disassembling instructions, that follow a very repetetive scheme:
                   6686: 
                   6687: @example
                   6688: :noname @var{disasm-operands} s" @var{inst-name}" type ;
                   6689: @var{entry-num} cells @var{table} + !
                   6690: @end example
                   6691: 
                   6692: Of course, this inspires the idea to factor out the commonalities to
                   6693: allow a definition like
                   6694: 
                   6695: @example
                   6696: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
                   6697: @end example
                   6698: 
                   6699: The parameters @var{disasm-operands} and @var{table} are usually
1.69      anton    6700: correlated.  Moreover, before I wrote the disassembler, there already
                   6701: existed code that defines instructions like this:
1.63      anton    6702: 
                   6703: @example
                   6704: @var{entry-num} @var{inst-format} @var{inst-name}
                   6705: @end example
                   6706: 
                   6707: This code comes from the assembler and resides in
                   6708: @file{arch/mips/insts.fs}.
                   6709: 
                   6710: So I had to define the @var{inst-format} words that performed the scheme
                   6711: above when executed.  At first I chose to use run-time code-generation:
                   6712: 
                   6713: @example
                   6714: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
                   6715:   :noname Postpone @var{disasm-operands}
                   6716:   name Postpone sliteral Postpone type Postpone ;
                   6717:   swap cells @var{table} + ! ;
                   6718: @end example
                   6719: 
                   6720: Note that this supplies the other two parameters of the scheme above.
1.44      crook    6721: 
1.63      anton    6722: An alternative would have been to write this using
                   6723: @code{create}/@code{does>}:
                   6724: 
                   6725: @example
                   6726: : @var{inst-format} ( entry-num "name" -- )
                   6727:   here name string, ( entry-num c-addr ) \ parse and save "name"
                   6728:   noname create , ( entry-num )
                   6729:   lastxt swap cells @var{table} + !
                   6730: does> ( addr w -- )
                   6731:   \ disassemble instruction w at addr
                   6732:   @@ >r 
                   6733:   @var{disasm-operands}
                   6734:   r> count type ;
                   6735: @end example
                   6736: 
                   6737: Somehow the first solution is simpler, mainly because it's simpler to
                   6738: shift a string from definition-time to use-time with @code{sliteral}
                   6739: than with @code{string,} and friends.
                   6740: 
                   6741: I wrote a lot of words following this scheme and soon thought about
                   6742: factoring out the commonalities among them.  Note that this uses a
                   6743: two-level defining word, i.e., a word that defines ordinary defining
                   6744: words.
                   6745: 
                   6746: This time a solution involving @code{postpone} and friends seemed more
                   6747: difficult (try it as an exercise), so I decided to use a
                   6748: @code{create}/@code{does>} word; since I was already at it, I also used
                   6749: @code{create}/@code{does>} for the lower level (try using
                   6750: @code{postpone} etc. as an exercise), resulting in the following
                   6751: definition:
                   6752: 
                   6753: @example
                   6754: : define-format ( disasm-xt table-xt -- )
                   6755:     \ define an instruction format that uses disasm-xt for
                   6756:     \ disassembling and enters the defined instructions into table
                   6757:     \ table-xt
                   6758:     create 2,
                   6759: does> ( u "inst" -- )
                   6760:     \ defines an anonymous word for disassembling instruction inst,
                   6761:     \ and enters it as u-th entry into table-xt
                   6762:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
                   6763:     noname create 2,      \ define anonymous word
                   6764:     execute lastxt swap ! \ enter xt of defined word into table-xt
                   6765: does> ( addr w -- )
                   6766:     \ disassemble instruction w at addr
                   6767:     2@@ >r ( addr w disasm-xt R: c-addr )
                   6768:     execute ( R: c-addr ) \ disassemble operands
                   6769:     r> count type ; \ print name 
                   6770: @end example
                   6771: 
                   6772: Note that the tables here (in contrast to above) do the @code{cells +}
                   6773: by themselves (that's why you have to pass an xt).  This word is used in
                   6774: the following way:
                   6775: 
                   6776: @example
                   6777: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
                   6778: @end example
                   6779: 
1.71      anton    6780: As shown above, the defined instruction format is then used like this:
                   6781: 
                   6782: @example
                   6783: @var{entry-num} @var{inst-format} @var{inst-name}
                   6784: @end example
                   6785: 
1.63      anton    6786: In terms of currying, this kind of two-level defining word provides the
                   6787: parameters in three stages: first @var{disasm-operands} and @var{table},
                   6788: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
                   6789: the instruction to be disassembled.  
                   6790: 
                   6791: Of course this did not quite fit all the instruction format names used
                   6792: in @file{insts.fs}, so I had to define a few wrappers that conditioned
                   6793: the parameters into the right form.
                   6794: 
                   6795: If you have trouble following this section, don't worry.  First, this is
                   6796: involved and takes time (and probably some playing around) to
                   6797: understand; second, this is the first two-level
                   6798: @code{create}/@code{does>} word I have written in seventeen years of
                   6799: Forth; and if I did not have @file{insts.fs} to start with, I may well
                   6800: have elected to use just a one-level defining word (with some repeating
                   6801: of parameters when using the defining word). So it is not necessary to
                   6802: understand this, but it may improve your understanding of Forth.
1.44      crook    6803: 
                   6804: 
1.91      anton    6805: @node @code{Const-does>},  , Advanced does> usage example, User-defined Defining Words
                   6806: @subsubsection @code{Const-does>}
                   6807: 
                   6808: A frequent use of @code{create}...@code{does>} is for transferring some
                   6809: values from definition-time to run-time.  Gforth supports this use with
                   6810: 
                   6811: doc-const-does>
                   6812: 
                   6813: A typical use of this word is:
                   6814: 
                   6815: @example
                   6816: : curry+ ( n1 "name" -- )
                   6817: 1 0 CONST-DOES> ( n2 -- n1+n2 )
                   6818:     + ;
                   6819: 
                   6820: 3 curry+ 3+
                   6821: @end example
                   6822: 
                   6823: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
                   6824: definition to run-time.
                   6825: 
                   6826: The advantages of using @code{const-does>} are:
                   6827: 
                   6828: @itemize
                   6829: 
                   6830: @item
                   6831: You don't have to deal with storing and retrieving the values, i.e.,
                   6832: your program becomes more writable and readable.
                   6833: 
                   6834: @item
                   6835: When using @code{does>}, you have to introduce a @code{@@} that cannot
                   6836: be optimized away (because you could change the data using
                   6837: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
                   6838: 
                   6839: @end itemize
                   6840: 
                   6841: An ANS Forth implementation of @code{const-does>} is available in
                   6842: @file{compat/const-does.fs}.
                   6843: 
                   6844: 
1.44      crook    6845: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
                   6846: @subsection Deferred words
                   6847: @cindex deferred words
                   6848: 
                   6849: The defining word @code{Defer} allows you to define a word by name
                   6850: without defining its behaviour; the definition of its behaviour is
                   6851: deferred. Here are two situation where this can be useful:
                   6852: 
                   6853: @itemize @bullet
                   6854: @item
                   6855: Where you want to allow the behaviour of a word to be altered later, and
                   6856: for all precompiled references to the word to change when its behaviour
                   6857: is changed.
                   6858: @item
                   6859: For mutual recursion; @xref{Calls and returns}.
                   6860: @end itemize
                   6861: 
                   6862: In the following example, @code{foo} always invokes the version of
                   6863: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6864: always invokes the version that prints ``@code{Hello}''. There is no way
                   6865: of getting @code{foo} to use the later version without re-ordering the
                   6866: source code and recompiling it.
                   6867: 
                   6868: @example
                   6869: : greet ." Good morning" ;
                   6870: : foo ... greet ... ;
                   6871: : greet ." Hello" ;
                   6872: : bar ... greet ... ;
                   6873: @end example
                   6874: 
                   6875: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6876: word. The behaviour of a @code{Defer}red word can be defined and
                   6877: redefined at any time by using @code{IS} to associate the xt of a
                   6878: previously-defined word with it. The previous example becomes:
                   6879: 
                   6880: @example
1.69      anton    6881: Defer greet ( -- )
1.44      crook    6882: : foo ... greet ... ;
                   6883: : bar ... greet ... ;
1.69      anton    6884: : greet1 ( -- ) ." Good morning" ;
                   6885: : greet2 ( -- ) ." Hello" ;
1.44      crook    6886: ' greet2 <IS> greet  \ make greet behave like greet2
                   6887: @end example
                   6888: 
1.69      anton    6889: @progstyle
                   6890: You should write a stack comment for every deferred word, and put only
                   6891: XTs into deferred words that conform to this stack effect.  Otherwise
                   6892: it's too difficult to use the deferred word.
                   6893: 
1.44      crook    6894: A deferred word can be used to improve the statistics-gathering example
                   6895: from @ref{User-defined Defining Words}; rather than edit the
                   6896: application's source code to change every @code{:} to a @code{my:}, do
                   6897: this:
                   6898: 
                   6899: @example
                   6900: : real: : ;     \ retain access to the original
                   6901: defer :         \ redefine as a deferred word
1.69      anton    6902: ' my: <IS> :      \ use special version of :
1.44      crook    6903: \
                   6904: \ load application here
                   6905: \
1.69      anton    6906: ' real: <IS> :    \ go back to the original
1.44      crook    6907: @end example
                   6908: 
                   6909: 
                   6910: One thing to note is that @code{<IS>} consumes its name when it is
                   6911: executed.  If you want to specify the name at compile time, use
                   6912: @code{[IS]}:
                   6913: 
                   6914: @example
                   6915: : set-greet ( xt -- )
                   6916:   [IS] greet ;
                   6917: 
                   6918: ' greet1 set-greet
                   6919: @end example
                   6920: 
1.69      anton    6921: A deferred word can only inherit execution semantics from the xt
                   6922: (because that is all that an xt can represent -- for more discussion of
                   6923: this @pxref{Tokens for Words}); by default it will have default
                   6924: interpretation and compilation semantics deriving from this execution
                   6925: semantics.  However, you can change the interpretation and compilation
                   6926: semantics of the deferred word in the usual ways:
1.44      crook    6927: 
                   6928: @example
                   6929: : bar .... ; compile-only
                   6930: Defer fred immediate
                   6931: Defer jim
                   6932: 
                   6933: ' bar <IS> jim  \ jim has default semantics
                   6934: ' bar <IS> fred \ fred is immediate
                   6935: @end example
                   6936: 
                   6937: doc-defer
                   6938: doc-<is>
                   6939: doc-[is]
                   6940: doc-is
                   6941: @comment TODO document these: what's defers [is]
                   6942: doc-what's
                   6943: doc-defers
                   6944: 
                   6945: @c Use @code{words-deferred} to see a list of deferred words.
                   6946: 
                   6947: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
                   6948: are provided in @file{compat/defer.fs}.
                   6949: 
                   6950: 
1.69      anton    6951: @node Aliases,  , Deferred words, Defining Words
1.44      crook    6952: @subsection Aliases
                   6953: @cindex aliases
1.1       anton    6954: 
1.44      crook    6955: The defining word @code{Alias} allows you to define a word by name that
                   6956: has the same behaviour as some other word. Here are two situation where
                   6957: this can be useful:
1.1       anton    6958: 
1.44      crook    6959: @itemize @bullet
                   6960: @item
                   6961: When you want access to a word's definition from a different word list
                   6962: (for an example of this, see the definition of the @code{Root} word list
                   6963: in the Gforth source).
                   6964: @item
                   6965: When you want to create a synonym; a definition that can be known by
                   6966: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   6967: aliases).
                   6968: @end itemize
1.1       anton    6969: 
1.69      anton    6970: Like deferred words, an alias has default compilation and interpretation
                   6971: semantics at the beginning (not the modifications of the other word),
                   6972: but you can change them in the usual ways (@code{immediate},
                   6973: @code{compile-only}). For example:
1.1       anton    6974: 
                   6975: @example
1.44      crook    6976: : foo ... ; immediate
                   6977: 
                   6978: ' foo Alias bar \ bar is not an immediate word
                   6979: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    6980: @end example
                   6981: 
1.44      crook    6982: Words that are aliases have the same xt, different headers in the
                   6983: dictionary, and consequently different name tokens (@pxref{Tokens for
                   6984: Words}) and possibly different immediate flags.  An alias can only have
                   6985: default or immediate compilation semantics; you can define aliases for
                   6986: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    6987: 
1.44      crook    6988: doc-alias
1.1       anton    6989: 
                   6990: 
1.47      crook    6991: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   6992: @section Interpretation and Compilation Semantics
1.26      crook    6993: @cindex semantics, interpretation and compilation
1.1       anton    6994: 
1.71      anton    6995: @c !! state and ' are used without explanation
                   6996: @c example for immediate/compile-only? or is the tutorial enough
                   6997: 
1.26      crook    6998: @cindex interpretation semantics
1.71      anton    6999: The @dfn{interpretation semantics} of a (named) word are what the text
1.26      crook    7000: interpreter does when it encounters the word in interpret state. It also
                   7001: appears in some other contexts, e.g., the execution token returned by
1.71      anton    7002: @code{' @i{word}} identifies the interpretation semantics of @i{word}
                   7003: (in other words, @code{' @i{word} execute} is equivalent to
1.29      crook    7004: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    7005: 
1.26      crook    7006: @cindex compilation semantics
1.71      anton    7007: The @dfn{compilation semantics} of a (named) word are what the text
                   7008: interpreter does when it encounters the word in compile state. It also
                   7009: appears in other contexts, e.g, @code{POSTPONE @i{word}}
                   7010: compiles@footnote{In standard terminology, ``appends to the current
                   7011: definition''.} the compilation semantics of @i{word}.
1.1       anton    7012: 
1.26      crook    7013: @cindex execution semantics
                   7014: The standard also talks about @dfn{execution semantics}. They are used
                   7015: only for defining the interpretation and compilation semantics of many
                   7016: words. By default, the interpretation semantics of a word are to
                   7017: @code{execute} its execution semantics, and the compilation semantics of
                   7018: a word are to @code{compile,} its execution semantics.@footnote{In
                   7019: standard terminology: The default interpretation semantics are its
                   7020: execution semantics; the default compilation semantics are to append its
                   7021: execution semantics to the execution semantics of the current
                   7022: definition.}
                   7023: 
1.71      anton    7024: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
                   7025: the text interpreter, ticked, or @code{postpone}d, so they have no
                   7026: interpretation or compilation semantics.  Their behaviour is represented
                   7027: by their XT (@pxref{Tokens for Words}), and we call it execution
                   7028: semantics, too.
                   7029: 
1.26      crook    7030: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   7031: 
                   7032: @cindex immediate words
                   7033: @cindex compile-only words
                   7034: You can change the semantics of the most-recently defined word:
                   7035: 
1.44      crook    7036: 
1.26      crook    7037: doc-immediate
                   7038: doc-compile-only
                   7039: doc-restrict
                   7040: 
1.82      anton    7041: By convention, words with non-default compilation semantics (e.g.,
                   7042: immediate words) often have names surrounded with brackets (e.g.,
                   7043: @code{[']}, @pxref{Execution token}).
1.44      crook    7044: 
1.26      crook    7045: Note that ticking (@code{'}) a compile-only word gives an error
                   7046: (``Interpreting a compile-only word'').
1.1       anton    7047: 
1.47      crook    7048: @menu
1.67      anton    7049: * Combined words::              
1.47      crook    7050: @end menu
1.44      crook    7051: 
1.71      anton    7052: 
1.48      anton    7053: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    7054: @subsection Combined Words
                   7055: @cindex combined words
                   7056: 
                   7057: Gforth allows you to define @dfn{combined words} -- words that have an
                   7058: arbitrary combination of interpretation and compilation semantics.
                   7059: 
1.26      crook    7060: doc-interpret/compile:
1.1       anton    7061: 
1.26      crook    7062: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   7063: recommend that you do not define such words, as cute as they may be:
                   7064: they make it hard to get at both parts of the word in some contexts.
                   7065: E.g., assume you want to get an execution token for the compilation
                   7066: part. Instead, define two words, one that embodies the interpretation
                   7067: part, and one that embodies the compilation part.  Once you have done
                   7068: that, you can define a combined word with @code{interpret/compile:} for
                   7069: the convenience of your users.
1.1       anton    7070: 
1.26      crook    7071: You might try to use this feature to provide an optimizing
                   7072: implementation of the default compilation semantics of a word. For
                   7073: example, by defining:
1.1       anton    7074: @example
1.26      crook    7075: :noname
                   7076:    foo bar ;
                   7077: :noname
                   7078:    POSTPONE foo POSTPONE bar ;
1.29      crook    7079: interpret/compile: opti-foobar
1.1       anton    7080: @end example
1.26      crook    7081: 
1.23      crook    7082: @noindent
1.26      crook    7083: as an optimizing version of:
                   7084: 
1.1       anton    7085: @example
1.26      crook    7086: : foobar
                   7087:     foo bar ;
1.1       anton    7088: @end example
                   7089: 
1.26      crook    7090: Unfortunately, this does not work correctly with @code{[compile]},
                   7091: because @code{[compile]} assumes that the compilation semantics of all
                   7092: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    7093: opti-foobar} would compile compilation semantics, whereas
                   7094: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    7095: 
1.26      crook    7096: @cindex state-smart words (are a bad idea)
1.82      anton    7097: @anchor{state-smartness}
1.29      crook    7098: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    7099: by @code{interpret/compile:} (words are state-smart if they check
                   7100: @code{STATE} during execution). E.g., they would try to code
                   7101: @code{foobar} like this:
1.1       anton    7102: 
1.26      crook    7103: @example
                   7104: : foobar
                   7105:   STATE @@
                   7106:   IF ( compilation state )
                   7107:     POSTPONE foo POSTPONE bar
                   7108:   ELSE
                   7109:     foo bar
                   7110:   ENDIF ; immediate
                   7111: @end example
1.1       anton    7112: 
1.26      crook    7113: Although this works if @code{foobar} is only processed by the text
                   7114: interpreter, it does not work in other contexts (like @code{'} or
                   7115: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   7116: for a state-smart word, not for the interpretation semantics of the
                   7117: original @code{foobar}; when you execute this execution token (directly
                   7118: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   7119: state, the result will not be what you expected (i.e., it will not
                   7120: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   7121: write them@footnote{For a more detailed discussion of this topic, see
1.66      anton    7122: M. Anton Ertl,
                   7123: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
                   7124: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1       anton    7125: 
1.26      crook    7126: @cindex defining words with arbitrary semantics combinations
                   7127: It is also possible to write defining words that define words with
                   7128: arbitrary combinations of interpretation and compilation semantics. In
                   7129: general, they look like this:
1.1       anton    7130: 
1.26      crook    7131: @example
                   7132: : def-word
                   7133:     create-interpret/compile
1.29      crook    7134:     @i{code1}
1.26      crook    7135: interpretation>
1.29      crook    7136:     @i{code2}
1.26      crook    7137: <interpretation
                   7138: compilation>
1.29      crook    7139:     @i{code3}
1.26      crook    7140: <compilation ;
                   7141: @end example
1.1       anton    7142: 
1.29      crook    7143: For a @i{word} defined with @code{def-word}, the interpretation
                   7144: semantics are to push the address of the body of @i{word} and perform
                   7145: @i{code2}, and the compilation semantics are to push the address of
                   7146: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    7147: can also be defined like this (except that the defined constants don't
                   7148: behave correctly when @code{[compile]}d):
1.1       anton    7149: 
1.26      crook    7150: @example
                   7151: : constant ( n "name" -- )
                   7152:     create-interpret/compile
                   7153:     ,
                   7154: interpretation> ( -- n )
                   7155:     @@
                   7156: <interpretation
                   7157: compilation> ( compilation. -- ; run-time. -- n )
                   7158:     @@ postpone literal
                   7159: <compilation ;
                   7160: @end example
1.1       anton    7161: 
1.44      crook    7162: 
1.26      crook    7163: doc-create-interpret/compile
                   7164: doc-interpretation>
                   7165: doc-<interpretation
                   7166: doc-compilation>
                   7167: doc-<compilation
1.1       anton    7168: 
1.44      crook    7169: 
1.29      crook    7170: Words defined with @code{interpret/compile:} and
1.26      crook    7171: @code{create-interpret/compile} have an extended header structure that
                   7172: differs from other words; however, unless you try to access them with
                   7173: plain address arithmetic, you should not notice this. Words for
                   7174: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    7175: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   7176: with @code{create-interpret/compile}.
1.1       anton    7177: 
1.44      crook    7178: 
1.47      crook    7179: @c -------------------------------------------------------------
1.81      anton    7180: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47      crook    7181: @section Tokens for Words
                   7182: @cindex tokens for words
                   7183: 
                   7184: This section describes the creation and use of tokens that represent
                   7185: words.
                   7186: 
1.71      anton    7187: @menu
                   7188: * Execution token::             represents execution/interpretation semantics
                   7189: * Compilation token::           represents compilation semantics
                   7190: * Name token::                  represents named words
                   7191: @end menu
1.47      crook    7192: 
1.71      anton    7193: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
                   7194: @subsection Execution token
1.47      crook    7195: 
                   7196: @cindex xt
                   7197: @cindex execution token
1.71      anton    7198: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
                   7199: You can use @code{execute} to invoke this behaviour.
1.47      crook    7200: 
1.71      anton    7201: @cindex tick (')
                   7202: You can use @code{'} to get an execution token that represents the
                   7203: interpretation semantics of a named word:
1.47      crook    7204: 
                   7205: @example
1.71      anton    7206: 5 ' .
                   7207: execute
                   7208: @end example
1.47      crook    7209: 
1.71      anton    7210: doc-'
                   7211: 
                   7212: @code{'} parses at run-time; there is also a word @code{[']} that parses
                   7213: when it is compiled, and compiles the resulting XT:
                   7214: 
                   7215: @example
                   7216: : foo ['] . execute ;
                   7217: 5 foo
                   7218: : bar ' execute ; \ by contrast,
                   7219: 5 bar .           \ ' parses "." when bar executes
                   7220: @end example
                   7221: 
                   7222: doc-[']
                   7223: 
                   7224: If you want the execution token of @i{word}, write @code{['] @i{word}}
                   7225: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
                   7226: @code{'} and @code{[']} behave somewhat unusually by complaining about
                   7227: compile-only words (because these words have no interpretation
                   7228: semantics).  You might get what you want by using @code{COMP' @i{word}
                   7229: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
                   7230: token}).
                   7231: 
                   7232: Another way to get an XT is @code{:noname} or @code{lastxt}
                   7233: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
                   7234: for the only behaviour the word has (the execution semantics).  For
                   7235: named words, @code{lastxt} produces an XT for the same behaviour it
                   7236: would produce if the word was defined anonymously.
                   7237: 
                   7238: @example
                   7239: :noname ." hello" ;
                   7240: execute
1.47      crook    7241: @end example
                   7242: 
1.71      anton    7243: An XT occupies one cell and can be manipulated like any other cell.
                   7244: 
1.47      crook    7245: @cindex code field address
                   7246: @cindex CFA
1.71      anton    7247: In ANS Forth the XT is just an abstract data type (i.e., defined by the
                   7248: operations that produce or consume it).  For old hands: In Gforth, the
                   7249: XT is implemented as a code field address (CFA).
                   7250: 
                   7251: doc-execute
                   7252: doc-perform
                   7253: 
                   7254: @node Compilation token, Name token, Execution token, Tokens for Words
                   7255: @subsection Compilation token
1.47      crook    7256: 
                   7257: @cindex compilation token
1.71      anton    7258: @cindex CT (compilation token)
                   7259: Gforth represents the compilation semantics of a named word by a
1.47      crook    7260: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   7261: @i{xt} is an execution token. The compilation semantics represented by
                   7262: the compilation token can be performed with @code{execute}, which
                   7263: consumes the whole compilation token, with an additional stack effect
                   7264: determined by the represented compilation semantics.
                   7265: 
                   7266: At present, the @i{w} part of a compilation token is an execution token,
                   7267: and the @i{xt} part represents either @code{execute} or
                   7268: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   7269: word. If the word has default compilation semantics, the @i{xt} will
                   7270: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   7271: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   7272: knowledge, unless necessary; future versions of Gforth may introduce
                   7273: unusual compilation tokens (e.g., a compilation token that represents
                   7274: the compilation semantics of a literal).
                   7275: 
1.71      anton    7276: You can perform the compilation semantics represented by the compilation
                   7277: token with @code{execute}.  You can compile the compilation semantics
                   7278: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
                   7279: equivalent to @code{postpone @i{word}}.
                   7280: 
                   7281: doc-[comp']
                   7282: doc-comp'
                   7283: doc-postpone,
                   7284: 
                   7285: @node Name token,  , Compilation token, Tokens for Words
                   7286: @subsection Name token
1.47      crook    7287: 
                   7288: @cindex name token
                   7289: @cindex name field address
                   7290: @cindex NFA
1.71      anton    7291: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
1.47      crook    7292: Gforth, the abstract data type @emph{name token} is implemented as a
                   7293: name field address (NFA).
                   7294: 
                   7295: doc-find-name
                   7296: doc-name>int
                   7297: doc-name?int
                   7298: doc-name>comp
                   7299: doc-name>string
                   7300: 
1.81      anton    7301: @c ----------------------------------------------------------
                   7302: @node Compiling words, The Text Interpreter, Tokens for Words, Words
                   7303: @section Compiling words
                   7304: @cindex compiling words
                   7305: @cindex macros
                   7306: 
                   7307: In contrast to most other languages, Forth has no strict boundary
1.82      anton    7308: between compilation and run-time.  E.g., you can run arbitrary code
                   7309: between defining words (or for computing data used by defining words
                   7310: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
                   7311: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
                   7312: running arbitrary code while compiling a colon definition (exception:
                   7313: you must not allot dictionary space).
                   7314: 
                   7315: @menu
                   7316: * Literals::                    Compiling data values
                   7317: * Macros::                      Compiling words
                   7318: @end menu
                   7319: 
                   7320: @node Literals, Macros, Compiling words, Compiling words
                   7321: @subsection Literals
                   7322: @cindex Literals
                   7323: 
                   7324: The simplest and most frequent example is to compute a literal during
                   7325: compilation.  E.g., the following definition prints an array of strings,
                   7326: one string per line:
                   7327: 
                   7328: @example
                   7329: : .strings ( addr u -- ) \ gforth
                   7330:     2* cells bounds U+DO
                   7331:        cr i 2@@ type
                   7332:     2 cells +LOOP ;  
                   7333: @end example
1.81      anton    7334: 
1.82      anton    7335: With a simple-minded compiler like Gforth's, this computes @code{2
                   7336: cells} on every loop iteration.  You can compute this value once and for
                   7337: all at compile time and compile it into the definition like this:
                   7338: 
                   7339: @example
                   7340: : .strings ( addr u -- ) \ gforth
                   7341:     2* cells bounds U+DO
                   7342:        cr i 2@@ type
                   7343:     [ 2 cells ] literal +LOOP ;  
                   7344: @end example
                   7345: 
                   7346: @code{[} switches the text interpreter to interpret state (you will get
                   7347: an @code{ok} prompt if you type this example interactively and insert a
                   7348: newline between @code{[} and @code{]}), so it performs the
                   7349: interpretation semantics of @code{2 cells}; this computes a number.
                   7350: @code{]} switches the text interpreter back into compile state.  It then
                   7351: performs @code{Literal}'s compilation semantics, which are to compile
                   7352: this number into the current word.  You can decompile the word with
                   7353: @code{see .strings} to see the effect on the compiled code.
1.81      anton    7354: 
1.82      anton    7355: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
                   7356: *} in this way.
1.81      anton    7357: 
1.82      anton    7358: doc-[
                   7359: doc-]
1.81      anton    7360: doc-literal
                   7361: doc-]L
1.82      anton    7362: 
                   7363: There are also words for compiling other data types than single cells as
                   7364: literals:
                   7365: 
1.81      anton    7366: doc-2literal
                   7367: doc-fliteral
1.82      anton    7368: doc-sliteral
                   7369: 
                   7370: @cindex colon-sys, passing data across @code{:}
                   7371: @cindex @code{:}, passing data across
                   7372: You might be tempted to pass data from outside a colon definition to the
                   7373: inside on the data stack.  This does not work, because @code{:} puhes a
                   7374: colon-sys, making stuff below unaccessible.  E.g., this does not work:
                   7375: 
                   7376: @example
                   7377: 5 : foo literal ; \ error: "unstructured"
                   7378: @end example
                   7379: 
                   7380: Instead, you have to pass the value in some other way, e.g., through a
                   7381: variable:
                   7382: 
                   7383: @example
                   7384: variable temp
                   7385: 5 temp !
                   7386: : foo [ temp @@ ] literal ;
                   7387: @end example
                   7388: 
                   7389: 
                   7390: @node Macros,  , Literals, Compiling words
                   7391: @subsection Macros
                   7392: @cindex Macros
                   7393: @cindex compiling compilation semantics
                   7394: 
                   7395: @code{Literal} and friends compile data values into the current
                   7396: definition.  You can also write words that compile other words into the
                   7397: current definition.  E.g.,
                   7398: 
                   7399: @example
                   7400: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
                   7401:   POSTPONE + ;
                   7402: 
                   7403: : foo ( n1 n2 -- n )
                   7404:   [ compile-+ ] ;
                   7405: 1 2 foo .
                   7406: @end example
                   7407: 
                   7408: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
                   7409: What happens in this example?  @code{Postpone} compiles the compilation
                   7410: semantics of @code{+} into @code{compile-+}; later the text interpreter
                   7411: executes @code{compile-+} and thus the compilation semantics of +, which
                   7412: compile (the execution semantics of) @code{+} into
                   7413: @code{foo}.@footnote{A recent RFI answer requires that compiling words
                   7414: should only be executed in compile state, so this example is not
                   7415: guaranteed to work on all standard systems, but on any decent system it
                   7416: will work.}
                   7417: 
                   7418: doc-postpone
                   7419: doc-[compile]
                   7420: 
                   7421: Compiling words like @code{compile-+} are usually immediate (or similar)
                   7422: so you do not have to switch to interpret state to execute them;
                   7423: mopifying the last example accordingly produces:
                   7424: 
                   7425: @example
                   7426: : [compile-+] ( compilation: --; interpretation: -- )
                   7427:   \ compiled code: ( n1 n2 -- n )
                   7428:   POSTPONE + ; immediate
                   7429: 
                   7430: : foo ( n1 n2 -- n )
                   7431:   [compile-+] ;
                   7432: 1 2 foo .
                   7433: @end example
                   7434: 
                   7435: Immediate compiling words are similar to macros in other languages (in
                   7436: particular, Lisp).  The important differences to macros in, e.g., C are:
                   7437: 
                   7438: @itemize @bullet
                   7439: 
                   7440: @item
                   7441: You use the same language for defining and processing macros, not a
                   7442: separate preprocessing language and processor.
                   7443: 
                   7444: @item
                   7445: Consequently, the full power of Forth is available in macro definitions.
                   7446: E.g., you can perform arbitrarily complex computations, or generate
                   7447: different code conditionally or in a loop (e.g., @pxref{Advanced macros
                   7448: Tutorial}).  This power is very useful when writing a parser generators
                   7449: or other code-generating software.
                   7450: 
                   7451: @item
                   7452: Macros defined using @code{postpone} etc. deal with the language at a
                   7453: higher level than strings; name binding happens at macro definition
                   7454: time, so you can avoid the pitfalls of name collisions that can happen
                   7455: in C macros.  Of course, Forth is a liberal language and also allows to
                   7456: shoot yourself in the foot with text-interpreted macros like
                   7457: 
                   7458: @example
                   7459: : [compile-+] s" +" evaluate ; immediate
                   7460: @end example
                   7461: 
                   7462: Apart from binding the name at macro use time, using @code{evaluate}
                   7463: also makes your definition @code{state}-smart (@pxref{state-smartness}).
                   7464: @end itemize
                   7465: 
                   7466: You may want the macro to compile a number into a word.  The word to do
                   7467: it is @code{literal}, but you have to @code{postpone} it, so its
                   7468: compilation semantics take effect when the macro is executed, not when
                   7469: it is compiled:
                   7470: 
                   7471: @example
                   7472: : [compile-5] ( -- ) \ compiled code: ( -- n )
                   7473:   5 POSTPONE literal ; immediate
                   7474: 
                   7475: : foo [compile-5] ;
                   7476: foo .
                   7477: @end example
                   7478: 
                   7479: You may want to pass parameters to a macro, that the macro should
                   7480: compile into the current definition.  If the parameter is a number, then
                   7481: you can use @code{postpone literal} (similar for other values).
                   7482: 
                   7483: If you want to pass a word that is to be compiled, the usual way is to
                   7484: pass an execution token and @code{compile,} it:
                   7485: 
                   7486: @example
                   7487: : twice1 ( xt -- ) \ compiled code: ... -- ...
                   7488:   dup compile, compile, ;
                   7489: 
                   7490: : 2+ ( n1 -- n2 )
                   7491:   [ ' 1+ twice1 ] ;
                   7492: @end example
                   7493: 
                   7494: doc-compile,
                   7495: 
                   7496: An alternative available in Gforth, that allows you to pass compile-only
                   7497: words as parameters is to use the compilation token (@pxref{Compilation
                   7498: token}).  The same example in this technique:
                   7499: 
                   7500: @example
                   7501: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
                   7502:   2dup 2>r execute 2r> execute ;
                   7503: 
                   7504: : 2+ ( n1 -- n2 )
                   7505:   [ comp' 1+ twice ] ;
                   7506: @end example
                   7507: 
                   7508: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
                   7509: works even if the executed compilation semantics has an effect on the
                   7510: data stack.
                   7511: 
                   7512: You can also define complete definitions with these words; this provides
                   7513: an alternative to using @code{does>} (@pxref{User-defined Defining
                   7514: Words}).  E.g., instead of
                   7515: 
                   7516: @example
                   7517: : curry+ ( n1 "name" -- )
                   7518:     CREATE ,
                   7519: DOES> ( n2 -- n1+n2 )
                   7520:     @@ + ;
                   7521: @end example
                   7522: 
                   7523: you could define
                   7524: 
                   7525: @example
                   7526: : curry+ ( n1 "name" -- )
                   7527:   \ name execution: ( n2 -- n1+n2 )
                   7528:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81      anton    7529: 
1.82      anton    7530: -3 curry+ 3-
                   7531: see 3-
                   7532: @end example
1.81      anton    7533: 
1.82      anton    7534: The sequence @code{>r : r>} is necessary, because @code{:} puts a
                   7535: colon-sys on the data stack that makes everything below it unaccessible.
1.81      anton    7536: 
1.82      anton    7537: This way of writing defining words is sometimes more, sometimes less
                   7538: convenient than using @code{does>} (@pxref{Advanced does> usage
                   7539: example}).  One advantage of this method is that it can be optimized
                   7540: better, because the compiler knows that the value compiled with
                   7541: @code{literal} is fixed, whereas the data associated with a
                   7542: @code{create}d word can be changed.
1.47      crook    7543: 
1.26      crook    7544: @c ----------------------------------------------------------
1.81      anton    7545: @node The Text Interpreter, Word Lists, Compiling words, Words
1.26      crook    7546: @section  The Text Interpreter
                   7547: @cindex interpreter - outer
                   7548: @cindex text interpreter
                   7549: @cindex outer interpreter
1.1       anton    7550: 
1.34      anton    7551: @c Should we really describe all these ugly details?  IMO the text
                   7552: @c interpreter should be much cleaner, but that may not be possible within
                   7553: @c ANS Forth. - anton
1.44      crook    7554: @c nac-> I wanted to explain how it works to show how you can exploit
                   7555: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   7556: @c some of these gory details was very helpful to me. None of the textbooks
                   7557: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   7558: @c seems to positively avoid going into too much detail for some of
                   7559: @c the internals.
1.34      anton    7560: 
1.71      anton    7561: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
                   7562: @c it is; for the ugly details, I would prefer another place.  I wonder
                   7563: @c whether we should have a chapter before "Words" that describes some
                   7564: @c basic concepts referred to in words, and a chapter after "Words" that
                   7565: @c describes implementation details.
                   7566: 
1.29      crook    7567: The text interpreter@footnote{This is an expanded version of the
                   7568: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    7569: that processes input from the current input device. It is also called
                   7570: the outer interpreter, in contrast to the inner interpreter
                   7571: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   7572: implementations.
1.27      crook    7573: 
1.29      crook    7574: @cindex interpret state
                   7575: @cindex compile state
                   7576: The text interpreter operates in one of two states: @dfn{interpret
                   7577: state} and @dfn{compile state}. The current state is defined by the
1.71      anton    7578: aptly-named variable @code{state}.
1.29      crook    7579: 
                   7580: This section starts by describing how the text interpreter behaves when
                   7581: it is in interpret state, processing input from the user input device --
                   7582: the keyboard. This is the mode that a Forth system is in after it starts
                   7583: up.
                   7584: 
                   7585: @cindex input buffer
                   7586: @cindex terminal input buffer
                   7587: The text interpreter works from an area of memory called the @dfn{input
                   7588: buffer}@footnote{When the text interpreter is processing input from the
                   7589: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   7590: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   7591: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    7592: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    7593: leading spaces (called @dfn{delimiters}) then parses a string (a
                   7594: sequence of non-space characters) until it reaches either a space
                   7595: character or the end of the buffer. Having parsed a string, it makes two
                   7596: attempts to process it:
1.27      crook    7597: 
1.29      crook    7598: @cindex dictionary
1.27      crook    7599: @itemize @bullet
                   7600: @item
1.29      crook    7601: It looks for the string in a @dfn{dictionary} of definitions. If the
                   7602: string is found, the string names a @dfn{definition} (also known as a
                   7603: @dfn{word}) and the dictionary search returns information that allows
                   7604: the text interpreter to perform the word's @dfn{interpretation
                   7605: semantics}. In most cases, this simply means that the word will be
                   7606: executed.
1.27      crook    7607: @item
                   7608: If the string is not found in the dictionary, the text interpreter
1.29      crook    7609: attempts to treat it as a number, using the rules described in
                   7610: @ref{Number Conversion}. If the string represents a legal number in the
                   7611: current radix, the number is pushed onto a parameter stack (the data
                   7612: stack for integers, the floating-point stack for floating-point
                   7613: numbers).
                   7614: @end itemize
                   7615: 
                   7616: If both attempts fail, or if the word is found in the dictionary but has
                   7617: no interpretation semantics@footnote{This happens if the word was
                   7618: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   7619: remainder of the input buffer, issues an error message and waits for
                   7620: more input. If one of the attempts succeeds, the text interpreter
                   7621: repeats the parsing process until the whole of the input buffer has been
                   7622: processed, at which point it prints the status message ``@code{ ok}''
                   7623: and waits for more input.
                   7624: 
1.71      anton    7625: @c anton: this should be in the input stream subsection (or below it)
                   7626: 
1.29      crook    7627: @cindex parse area
                   7628: The text interpreter keeps track of its position in the input buffer by
                   7629: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   7630: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   7631: of the input buffer. The region from offset @code{>IN @@} to the end of
                   7632: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   7633: the text interpreter processes the contents of the input buffer by
                   7634: parsing strings from the parse area until the parse area is empty.}.
                   7635: This example shows how @code{>IN} changes as the text interpreter parses
                   7636: the input buffer:
                   7637: 
                   7638: @example
                   7639: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   7640:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   7641: 
                   7642: 1 2 3 remaining + remaining . 
                   7643: 
                   7644: : foo 1 2 3 remaining SWAP remaining ;
                   7645: @end example
                   7646: 
                   7647: @noindent
                   7648: The result is:
                   7649: 
                   7650: @example
                   7651: ->+ remaining .<-
                   7652: ->.<-5  ok
                   7653: 
                   7654: ->SWAP remaining ;-<
                   7655: ->;<-  ok
                   7656: @end example
                   7657: 
                   7658: @cindex parsing words
                   7659: The value of @code{>IN} can also be modified by a word in the input
                   7660: buffer that is executed by the text interpreter.  This means that a word
                   7661: can ``trick'' the text interpreter into either skipping a section of the
                   7662: input buffer@footnote{This is how parsing words work.} or into parsing a
                   7663: section twice. For example:
1.27      crook    7664: 
1.29      crook    7665: @example
1.71      anton    7666: : lat ." <<foo>>" ;
                   7667: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29      crook    7668: @end example
                   7669: 
                   7670: @noindent
                   7671: When @code{flat} is executed, this output is produced@footnote{Exercise
                   7672: for the reader: what would happen if the @code{3} were replaced with
                   7673: @code{4}?}:
                   7674: 
                   7675: @example
1.71      anton    7676: <<bar>><<foo>>
1.29      crook    7677: @end example
                   7678: 
1.71      anton    7679: This technique can be used to work around some of the interoperability
                   7680: problems of parsing words.  Of course, it's better to avoid parsing
                   7681: words where possible.
                   7682: 
1.29      crook    7683: @noindent
                   7684: Two important notes about the behaviour of the text interpreter:
1.27      crook    7685: 
                   7686: @itemize @bullet
                   7687: @item
                   7688: It processes each input string to completion before parsing additional
1.29      crook    7689: characters from the input buffer.
                   7690: @item
                   7691: It treats the input buffer as a read-only region (and so must your code).
                   7692: @end itemize
                   7693: 
                   7694: @noindent
                   7695: When the text interpreter is in compile state, its behaviour changes in
                   7696: these ways:
                   7697: 
                   7698: @itemize @bullet
                   7699: @item
                   7700: If a parsed string is found in the dictionary, the text interpreter will
                   7701: perform the word's @dfn{compilation semantics}. In most cases, this
                   7702: simply means that the execution semantics of the word will be appended
                   7703: to the current definition.
1.27      crook    7704: @item
1.29      crook    7705: When a number is encountered, it is compiled into the current definition
                   7706: (as a literal) rather than being pushed onto a parameter stack.
                   7707: @item
                   7708: If an error occurs, @code{state} is modified to put the text interpreter
                   7709: back into interpret state.
                   7710: @item
                   7711: Each time a line is entered from the keyboard, Gforth prints
                   7712: ``@code{ compiled}'' rather than `` @code{ok}''.
                   7713: @end itemize
                   7714: 
                   7715: @cindex text interpreter - input sources
                   7716: When the text interpreter is using an input device other than the
                   7717: keyboard, its behaviour changes in these ways:
                   7718: 
                   7719: @itemize @bullet
                   7720: @item
                   7721: When the parse area is empty, the text interpreter attempts to refill
                   7722: the input buffer from the input source. When the input source is
1.71      anton    7723: exhausted, the input source is set back to the previous input source.
1.29      crook    7724: @item
                   7725: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7726: time the parse area is emptied.
                   7727: @item
                   7728: If an error occurs, the input source is set back to the user input
                   7729: device.
1.27      crook    7730: @end itemize
1.21      crook    7731: 
1.49      anton    7732: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7733: 
1.26      crook    7734: doc->in
1.27      crook    7735: doc-source
                   7736: 
1.26      crook    7737: doc-tib
                   7738: doc-#tib
1.1       anton    7739: 
1.44      crook    7740: 
1.26      crook    7741: @menu
1.67      anton    7742: * Input Sources::               
                   7743: * Number Conversion::           
                   7744: * Interpret/Compile states::    
                   7745: * Interpreter Directives::      
1.26      crook    7746: @end menu
1.1       anton    7747: 
1.29      crook    7748: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7749: @subsection Input Sources
                   7750: @cindex input sources
                   7751: @cindex text interpreter - input sources
                   7752: 
1.44      crook    7753: By default, the text interpreter processes input from the user input
1.29      crook    7754: device (the keyboard) when Forth starts up. The text interpreter can
                   7755: process input from any of these sources:
                   7756: 
                   7757: @itemize @bullet
                   7758: @item
                   7759: The user input device -- the keyboard.
                   7760: @item
                   7761: A file, using the words described in @ref{Forth source files}.
                   7762: @item
                   7763: A block, using the words described in @ref{Blocks}.
                   7764: @item
                   7765: A text string, using @code{evaluate}.
                   7766: @end itemize
                   7767: 
                   7768: A program can identify the current input device from the values of
                   7769: @code{source-id} and @code{blk}.
                   7770: 
1.44      crook    7771: 
1.29      crook    7772: doc-source-id
                   7773: doc-blk
                   7774: 
                   7775: doc-save-input
                   7776: doc-restore-input
                   7777: 
                   7778: doc-evaluate
1.1       anton    7779: 
1.29      crook    7780: 
1.44      crook    7781: 
1.29      crook    7782: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7783: @subsection Number Conversion
                   7784: @cindex number conversion
                   7785: @cindex double-cell numbers, input format
                   7786: @cindex input format for double-cell numbers
                   7787: @cindex single-cell numbers, input format
                   7788: @cindex input format for single-cell numbers
                   7789: @cindex floating-point numbers, input format
                   7790: @cindex input format for floating-point numbers
1.1       anton    7791: 
1.29      crook    7792: This section describes the rules that the text interpreter uses when it
                   7793: tries to convert a string into a number.
1.1       anton    7794: 
1.26      crook    7795: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7796: number base@footnote{For example, 0-9 when the number base is decimal or
                   7797: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7798: 
1.26      crook    7799: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7800: 
1.29      crook    7801: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7802: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7803: 
1.26      crook    7804: Let * represent any number of instances of the previous character
                   7805: (including none).
1.1       anton    7806: 
1.26      crook    7807: Let any other character represent itself.
1.1       anton    7808: 
1.29      crook    7809: @noindent
1.26      crook    7810: Now, the conversion rules are:
1.21      crook    7811: 
1.26      crook    7812: @itemize @bullet
                   7813: @item
                   7814: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7815: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7816: @item
                   7817: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7818: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7819: arithmetic. Examples are -45 -5681 -0
                   7820: @item
                   7821: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7822: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7823: (all three of these represent the same number).
1.26      crook    7824: @item
                   7825: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7826: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7827: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7828: -34.65 (all three of these represent the same number).
1.26      crook    7829: @item
1.29      crook    7830: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7831: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7832: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7833: number) +12.E-4
1.26      crook    7834: @end itemize
1.1       anton    7835: 
1.26      crook    7836: By default, the number base used for integer number conversion is given
1.35      anton    7837: by the contents of the variable @code{base}.  Note that a lot of
                   7838: confusion can result from unexpected values of @code{base}.  If you
                   7839: change @code{base} anywhere, make sure to save the old value and restore
                   7840: it afterwards.  In general I recommend keeping @code{base} decimal, and
                   7841: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7842: 
1.29      crook    7843: doc-dpl
1.26      crook    7844: doc-base
                   7845: doc-hex
                   7846: doc-decimal
1.1       anton    7847: 
1.44      crook    7848: 
1.26      crook    7849: @cindex '-prefix for character strings
                   7850: @cindex &-prefix for decimal numbers
                   7851: @cindex %-prefix for binary numbers
                   7852: @cindex $-prefix for hexadecimal numbers
1.35      anton    7853: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7854: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7855: implementing @code{$} etc. as parsing words that process the subsequent
                   7856: number in the input stream and push it onto the stack. For example, see
                   7857: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7858: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7859: is required between the prefix and the number.} before the first digit
                   7860: of an (integer) number. Four prefixes are supported:
1.1       anton    7861: 
1.26      crook    7862: @itemize @bullet
                   7863: @item
1.35      anton    7864: @code{&} -- decimal
1.26      crook    7865: @item
1.35      anton    7866: @code{%} -- binary
1.26      crook    7867: @item
1.35      anton    7868: @code{$} -- hexadecimal
1.26      crook    7869: @item
1.35      anton    7870: @code{'} -- base @code{max-char+1}
1.26      crook    7871: @end itemize
1.1       anton    7872: 
1.26      crook    7873: Here are some examples, with the equivalent decimal number shown after
                   7874: in braces:
1.1       anton    7875: 
1.26      crook    7876: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
                   7877: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
                   7878: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
                   7879: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    7880: 
1.26      crook    7881: @cindex number conversion - traps for the unwary
1.29      crook    7882: @noindent
1.26      crook    7883: Number conversion has a number of traps for the unwary:
1.1       anton    7884: 
1.26      crook    7885: @itemize @bullet
                   7886: @item
                   7887: You cannot determine the current number base using the code sequence
1.35      anton    7888: @code{base @@ .} -- the number base is always 10 in the current number
                   7889: base. Instead, use something like @code{base @@ dec.}
1.26      crook    7890: @item
                   7891: If the number base is set to a value greater than 14 (for example,
                   7892: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   7893: it to be intepreted as either a single-precision integer or a
                   7894: floating-point number (Gforth treats it as an integer). The ambiguity
                   7895: can be resolved by explicitly stating the sign of the mantissa and/or
                   7896: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   7897: ambiguity arises; either representation will be treated as a
                   7898: floating-point number.
                   7899: @item
1.29      crook    7900: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    7901: It is used to specify file types.
                   7902: @item
1.72      anton    7903: ANS Forth requires the @code{.} of a double-precision number to be the
                   7904: final character in the string.  Gforth allows the @code{.} to be
                   7905: anywhere after the first digit.
1.26      crook    7906: @item
                   7907: The number conversion process does not check for overflow.
                   7908: @item
1.72      anton    7909: In an ANS Forth program @code{base} is required to be decimal when
                   7910: converting floating-point numbers.  In Gforth, number conversion to
                   7911: floating-point numbers always uses base &10, irrespective of the value
                   7912: of @code{base}.
1.26      crook    7913: @end itemize
1.1       anton    7914: 
1.49      anton    7915: You can read numbers into your programs with the words described in
                   7916: @ref{Input}.
1.1       anton    7917: 
1.82      anton    7918: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26      crook    7919: @subsection Interpret/Compile states
                   7920: @cindex Interpret/Compile states
1.1       anton    7921: 
1.29      crook    7922: A standard program is not permitted to change @code{state}
                   7923: explicitly. However, it can change @code{state} implicitly, using the
                   7924: words @code{[} and @code{]}. When @code{[} is executed it switches
                   7925: @code{state} to interpret state, and therefore the text interpreter
                   7926: starts interpreting. When @code{]} is executed it switches @code{state}
                   7927: to compile state and therefore the text interpreter starts
1.44      crook    7928: compiling. The most common usage for these words is for switching into
                   7929: interpret state and back from within a colon definition; this technique
1.49      anton    7930: can be used to compile a literal (for an example, @pxref{Literals}) or
                   7931: for conditional compilation (for an example, @pxref{Interpreter
                   7932: Directives}).
1.44      crook    7933: 
1.35      anton    7934: 
                   7935: @c This is a bad example: It's non-standard, and it's not necessary.
                   7936: @c However, I can't think of a good example for switching into compile
                   7937: @c state when there is no current word (@code{state}-smart words are not a
                   7938: @c good reason).  So maybe we should use an example for switching into
                   7939: @c interpret @code{state} in a colon def. - anton
1.44      crook    7940: @c nac-> I agree. I started out by putting in the example, then realised
                   7941: @c that it was non-ANS, so wrote more words around it. I hope this
                   7942: @c re-written version is acceptable to you. I do want to keep the example
                   7943: @c as it is helpful for showing what is and what is not portable, particularly
                   7944: @c where it outlaws a style in common use.
                   7945: 
1.72      anton    7946: @c anton: it's more important to show what's portable.  After we have done
1.83      anton    7947: @c that, we can also show what's not.  In any case, I have written a
                   7948: @c section Compiling Words which also deals with [ ].
1.35      anton    7949: 
1.44      crook    7950: @code{[} and @code{]} also give you the ability to switch into compile
                   7951: state and back, but we cannot think of any useful Standard application
                   7952: for this ability. Pre-ANS Forth textbooks have examples like this:
1.29      crook    7953: 
                   7954: @example
                   7955: : AA ." this is A" ;
                   7956: : BB ." this is B" ;
                   7957: : CC ." this is C" ;
                   7958: 
1.44      crook    7959: create table ] aa bb cc [
                   7960: 
1.29      crook    7961: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   7962:   cells table + @ execute ;
                   7963: @end example
                   7964: 
1.44      crook    7965: This example builds a jump table; @code{0 go} will display ``@code{this
                   7966: is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   7967: defining @code{table} like this:
1.29      crook    7968: 
                   7969: @example
1.44      crook    7970: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
1.29      crook    7971: @end example
                   7972: 
1.44      crook    7973: The problem with this code is that the definition of @code{table} is not
                   7974: portable -- it @i{compile}s execution tokens into code space. Whilst it
                   7975: @i{may} work on systems where code space and data space co-incide, the
1.29      crook    7976: Standard only allows data space to be assigned for a @code{CREATE}d
                   7977: word. In addition, the Standard only allows @code{@@} to access data
                   7978: space, whilst this example is using it to access code space. The only
                   7979: portable, Standard way to build this table is to build it in data space,
                   7980: like this:
                   7981: 
                   7982: @example
                   7983: create table ' aa , ' bb , ' cc ,
                   7984: @end example
                   7985: 
1.26      crook    7986: doc-state
1.44      crook    7987: 
1.29      crook    7988: 
1.82      anton    7989: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
1.26      crook    7990: @subsection Interpreter Directives
                   7991: @cindex interpreter directives
1.72      anton    7992: @cindex conditional compilation
1.1       anton    7993: 
1.29      crook    7994: These words are usually used in interpret state; typically to control
                   7995: which parts of a source file are processed by the text
1.26      crook    7996: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   7997: supplements these with a rich set of immediate control structure words
                   7998: to compensate for the fact that the non-immediate versions can only be
1.29      crook    7999: used in compile state (@pxref{Control Structures}). Typical usages:
                   8000: 
                   8001: @example
1.72      anton    8002: FALSE Constant HAVE-ASSEMBLER
1.29      crook    8003: .
                   8004: .
1.72      anton    8005: HAVE-ASSEMBLER [IF]
1.29      crook    8006: : ASSEMBLER-FEATURE
                   8007:   ...
                   8008: ;
                   8009: [ENDIF]
                   8010: .
                   8011: .
                   8012: : SEE
                   8013:   ... \ general-purpose SEE code
1.72      anton    8014:   [ HAVE-ASSEMBLER [IF] ]
1.29      crook    8015:   ... \ assembler-specific SEE code
                   8016:   [ [ENDIF] ]
                   8017: ;
                   8018: @end example
1.1       anton    8019: 
1.44      crook    8020: 
1.26      crook    8021: doc-[IF]
                   8022: doc-[ELSE]
                   8023: doc-[THEN]
                   8024: doc-[ENDIF]
1.1       anton    8025: 
1.26      crook    8026: doc-[IFDEF]
                   8027: doc-[IFUNDEF]
1.1       anton    8028: 
1.26      crook    8029: doc-[?DO]
                   8030: doc-[DO]
                   8031: doc-[FOR]
                   8032: doc-[LOOP]
                   8033: doc-[+LOOP]
                   8034: doc-[NEXT]
1.1       anton    8035: 
1.26      crook    8036: doc-[BEGIN]
                   8037: doc-[UNTIL]
                   8038: doc-[AGAIN]
                   8039: doc-[WHILE]
                   8040: doc-[REPEAT]
1.1       anton    8041: 
1.27      crook    8042: 
1.26      crook    8043: @c -------------------------------------------------------------
1.47      crook    8044: @node Word Lists, Environmental Queries, The Text Interpreter, Words
1.26      crook    8045: @section Word Lists
                   8046: @cindex word lists
1.32      anton    8047: @cindex header space
1.1       anton    8048: 
1.36      anton    8049: A wordlist is a list of named words; you can add new words and look up
                   8050: words by name (and you can remove words in a restricted way with
                   8051: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   8052: 
                   8053: @cindex search order stack
                   8054: The text interpreter searches the wordlists present in the search order
                   8055: (a stack of wordlists), from the top to the bottom.  Within each
                   8056: wordlist, the search starts conceptually at the newest word; i.e., if
                   8057: two words in a wordlist have the same name, the newer word is found.
1.1       anton    8058: 
1.26      crook    8059: @cindex compilation word list
1.36      anton    8060: New words are added to the @dfn{compilation wordlist} (aka current
                   8061: wordlist).
1.1       anton    8062: 
1.36      anton    8063: @cindex wid
                   8064: A word list is identified by a cell-sized word list identifier (@i{wid})
                   8065: in much the same way as a file is identified by a file handle. The
                   8066: numerical value of the wid has no (portable) meaning, and might change
                   8067: from session to session.
1.1       anton    8068: 
1.29      crook    8069: The ANS Forth ``Search order'' word set is intended to provide a set of
                   8070: low-level tools that allow various different schemes to be
1.74      anton    8071: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26      crook    8072: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    8073: Forth.
1.1       anton    8074: 
1.27      crook    8075: @comment TODO: locals section refers to here, saying that every word list (aka
                   8076: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78      anton    8077: @c anton: but better in a separate subsection on wordlist internals
1.1       anton    8078: 
1.45      crook    8079: @comment TODO: document markers, reveal, tables, mappedwordlist
                   8080: 
                   8081: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    8082: @comment word from the source files, rather than some alias.
1.44      crook    8083: 
1.26      crook    8084: doc-forth-wordlist
                   8085: doc-definitions
                   8086: doc-get-current
                   8087: doc-set-current
                   8088: doc-get-order
1.45      crook    8089: doc---gforthman-set-order
1.26      crook    8090: doc-wordlist
1.30      anton    8091: doc-table
1.79      anton    8092: doc->order
1.36      anton    8093: doc-previous
1.26      crook    8094: doc-also
1.45      crook    8095: doc---gforthman-forth
1.26      crook    8096: doc-only
1.45      crook    8097: doc---gforthman-order
1.15      anton    8098: 
1.26      crook    8099: doc-find
                   8100: doc-search-wordlist
1.15      anton    8101: 
1.26      crook    8102: doc-words
                   8103: doc-vlist
1.44      crook    8104: @c doc-words-deferred
1.1       anton    8105: 
1.74      anton    8106: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26      crook    8107: doc-root
                   8108: doc-vocabulary
                   8109: doc-seal
                   8110: doc-vocs
                   8111: doc-current
                   8112: doc-context
1.1       anton    8113: 
1.44      crook    8114: 
1.26      crook    8115: @menu
1.75      anton    8116: * Vocabularies::                
1.67      anton    8117: * Why use word lists?::         
1.75      anton    8118: * Word list example::           
1.26      crook    8119: @end menu
                   8120: 
1.75      anton    8121: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
                   8122: @subsection Vocabularies
                   8123: @cindex Vocabularies, detailed explanation
                   8124: 
                   8125: Here is an example of creating and using a new wordlist using ANS
                   8126: Forth words:
                   8127: 
                   8128: @example
                   8129: wordlist constant my-new-words-wordlist
                   8130: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
                   8131: 
                   8132: \ add it to the search order
                   8133: also my-new-words
                   8134: 
                   8135: \ alternatively, add it to the search order and make it
                   8136: \ the compilation word list
                   8137: also my-new-words definitions
                   8138: \ type "order" to see the problem
                   8139: @end example
                   8140: 
                   8141: The problem with this example is that @code{order} has no way to
                   8142: associate the name @code{my-new-words} with the wid of the word list (in
                   8143: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   8144: that has no associated name). There is no Standard way of associating a
                   8145: name with a wid.
                   8146: 
                   8147: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   8148: associates a name with a wid:
                   8149: 
                   8150: @example
                   8151: vocabulary my-new-words
                   8152: 
                   8153: \ add it to the search order
                   8154: also my-new-words
                   8155: 
                   8156: \ alternatively, add it to the search order and make it
                   8157: \ the compilation word list
                   8158: my-new-words definitions
                   8159: \ type "order" to see that the problem is solved
                   8160: @end example
                   8161: 
                   8162: 
                   8163: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26      crook    8164: @subsection Why use word lists?
                   8165: @cindex word lists - why use them?
                   8166: 
1.74      anton    8167: Here are some reasons why people use wordlists:
1.26      crook    8168: 
                   8169: @itemize @bullet
1.74      anton    8170: 
                   8171: @c anton: Gforth's hashing implementation makes the search speed
                   8172: @c independent from the number of words.  But it is linear with the number
                   8173: @c of wordlists that have to be searched, so in effect using more wordlists
                   8174: @c actually slows down compilation.
                   8175: 
                   8176: @c @item
                   8177: @c To improve compilation speed by reducing the number of header space
                   8178: @c entries that must be searched. This is achieved by creating a new
                   8179: @c word list that contains all of the definitions that are used in the
                   8180: @c definition of a Forth system but which would not usually be used by
                   8181: @c programs running on that system. That word list would be on the search
                   8182: @c list when the Forth system was compiled but would be removed from the
                   8183: @c search list for normal operation. This can be a useful technique for
                   8184: @c low-performance systems (for example, 8-bit processors in embedded
                   8185: @c systems) but is unlikely to be necessary in high-performance desktop
                   8186: @c systems.
                   8187: 
1.26      crook    8188: @item
                   8189: To prevent a set of words from being used outside the context in which
                   8190: they are valid. Two classic examples of this are an integrated editor
                   8191: (all of the edit commands are defined in a separate word list; the
                   8192: search order is set to the editor word list when the editor is invoked;
                   8193: the old search order is restored when the editor is terminated) and an
                   8194: integrated assembler (the op-codes for the machine are defined in a
                   8195: separate word list which is used when a @code{CODE} word is defined).
1.74      anton    8196: 
                   8197: @item
                   8198: To organize the words of an application or library into a user-visible
                   8199: set (in @code{forth-wordlist} or some other common wordlist) and a set
                   8200: of helper words used just for the implementation (hidden in a separate
1.75      anton    8201: wordlist).  This keeps @code{words}' output smaller, separates
                   8202: implementation and interface, and reduces the chance of name conflicts
                   8203: within the common wordlist.
1.74      anton    8204: 
1.26      crook    8205: @item
                   8206: To prevent a name-space clash between multiple definitions with the same
                   8207: name. For example, when building a cross-compiler you might have a word
                   8208: @code{IF} that generates conditional code for your target system. By
                   8209: placing this definition in a different word list you can control whether
                   8210: the host system's @code{IF} or the target system's @code{IF} get used in
                   8211: any particular context by controlling the order of the word lists on the
                   8212: search order stack.
1.74      anton    8213: 
1.26      crook    8214: @end itemize
1.1       anton    8215: 
1.74      anton    8216: The downsides of using wordlists are:
                   8217: 
                   8218: @itemize
                   8219: 
                   8220: @item
                   8221: Debugging becomes more cumbersome.
                   8222: 
                   8223: @item
                   8224: Name conflicts worked around with wordlists are still there, and you
                   8225: have to arrange the search order carefully to get the desired results;
                   8226: if you forget to do that, you get hard-to-find errors (as in any case
                   8227: where you read the code differently from the compiler; @code{see} can
1.75      anton    8228: help seeing which of several possible words the name resolves to in such
                   8229: cases).  @code{See} displays just the name of the words, not what
                   8230: wordlist they belong to, so it might be misleading.  Using unique names
                   8231: is a better approach to avoid name conflicts.
1.74      anton    8232: 
                   8233: @item
                   8234: You have to explicitly undo any changes to the search order.  In many
                   8235: cases it would be more convenient if this happened implicitly.  Gforth
                   8236: currently does not provide such a feature, but it may do so in the
                   8237: future.
                   8238: @end itemize
                   8239: 
                   8240: 
1.75      anton    8241: @node Word list example,  , Why use word lists?, Word Lists
                   8242: @subsection Word list example
                   8243: @cindex word lists - example
1.1       anton    8244: 
1.74      anton    8245: The following example is from the
                   8246: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   8247: garbage collector} and uses wordlists to separate public words from
                   8248: helper words:
                   8249: 
                   8250: @example
                   8251: get-current ( wid )
                   8252: vocabulary garbage-collector also garbage-collector definitions
                   8253: ... \ define helper words
                   8254: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
                   8255: ... \ define the public (i.e., API) words
                   8256:     \ they can refer to the helper words
                   8257: previous \ restore original search order (helper words become invisible)
                   8258: @end example
                   8259: 
1.26      crook    8260: @c -------------------------------------------------------------
                   8261: @node Environmental Queries, Files, Word Lists, Words
                   8262: @section Environmental Queries
                   8263: @cindex environmental queries
1.21      crook    8264: 
1.26      crook    8265: ANS Forth introduced the idea of ``environmental queries'' as a way
                   8266: for a program running on a system to determine certain characteristics of the system.
                   8267: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    8268: 
1.32      anton    8269: The Standard requires that the header space used for environmental queries
                   8270: be distinct from the header space used for definitions.
1.21      crook    8271: 
1.26      crook    8272: Typically, environmental queries are supported by creating a set of
1.29      crook    8273: definitions in a word list that is @i{only} used during environmental
1.26      crook    8274: queries; that is what Gforth does. There is no Standard way of adding
                   8275: definitions to the set of recognised environmental queries, but any
                   8276: implementation that supports the loading of optional word sets must have
                   8277: some mechanism for doing this (after loading the word set, the
                   8278: associated environmental query string must return @code{true}). In
                   8279: Gforth, the word list used to honour environmental queries can be
                   8280: manipulated just like any other word list.
1.21      crook    8281: 
1.44      crook    8282: 
1.26      crook    8283: doc-environment?
                   8284: doc-environment-wordlist
1.21      crook    8285: 
1.26      crook    8286: doc-gforth
                   8287: doc-os-class
1.21      crook    8288: 
1.44      crook    8289: 
1.26      crook    8290: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   8291: returning two items on the stack, querying it using @code{environment?}
                   8292: will return an additional item; the @code{true} flag that shows that the
                   8293: string was recognised.
1.21      crook    8294: 
1.26      crook    8295: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    8296: 
1.26      crook    8297: Here are some examples of using environmental queries:
1.21      crook    8298: 
1.26      crook    8299: @example
                   8300: s" address-unit-bits" environment? 0=
                   8301: [IF]
                   8302:      cr .( environmental attribute address-units-bits unknown... ) cr
1.75      anton    8303: [ELSE]
                   8304:      drop \ ensure balanced stack effect
1.26      crook    8305: [THEN]
1.21      crook    8306: 
1.75      anton    8307: \ this might occur in the prelude of a standard program that uses THROW
                   8308: s" exception" environment? [IF]
                   8309:    0= [IF]
                   8310:       : throw abort" exception thrown" ;
                   8311:    [THEN]
                   8312: [ELSE] \ we don't know, so make sure
                   8313:    : throw abort" exception thrown" ;
                   8314: [THEN]
1.21      crook    8315: 
1.26      crook    8316: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   8317:                         [ELSE] .( Not Gforth..) [THEN]
1.75      anton    8318: 
                   8319: \ a program using v*
                   8320: s" gforth" environment? [IF]
                   8321:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
                   8322:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8323:      >r swap 2swap swap 0e r> 0 ?DO
                   8324:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
                   8325:      LOOP
                   8326:      2drop 2drop ; 
                   8327:   [THEN]
                   8328: [ELSE] \ 
                   8329:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8330:   ...
                   8331: [THEN]
1.26      crook    8332: @end example
1.21      crook    8333: 
1.26      crook    8334: Here is an example of adding a definition to the environment word list:
1.21      crook    8335: 
1.26      crook    8336: @example
                   8337: get-current environment-wordlist set-current
                   8338: true constant block
                   8339: true constant block-ext
                   8340: set-current
                   8341: @end example
1.21      crook    8342: 
1.26      crook    8343: You can see what definitions are in the environment word list like this:
1.21      crook    8344: 
1.26      crook    8345: @example
1.79      anton    8346: environment-wordlist >order words previous
1.26      crook    8347: @end example
1.21      crook    8348: 
                   8349: 
1.26      crook    8350: @c -------------------------------------------------------------
                   8351: @node Files, Blocks, Environmental Queries, Words
                   8352: @section Files
1.28      crook    8353: @cindex files
                   8354: @cindex I/O - file-handling
1.21      crook    8355: 
1.26      crook    8356: Gforth provides facilities for accessing files that are stored in the
                   8357: host operating system's file-system. Files that are processed by Gforth
                   8358: can be divided into two categories:
1.21      crook    8359: 
1.23      crook    8360: @itemize @bullet
                   8361: @item
1.29      crook    8362: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    8363: @item
1.29      crook    8364: Files that are processed by some other program (@dfn{general files}).
1.26      crook    8365: @end itemize
                   8366: 
                   8367: @menu
1.48      anton    8368: * Forth source files::          
                   8369: * General files::               
                   8370: * Search Paths::                
1.26      crook    8371: @end menu
                   8372: 
                   8373: @c -------------------------------------------------------------
                   8374: @node Forth source files, General files, Files, Files
                   8375: @subsection Forth source files
                   8376: @cindex including files
                   8377: @cindex Forth source files
1.21      crook    8378: 
1.26      crook    8379: The simplest way to interpret the contents of a file is to use one of
                   8380: these two formats:
1.21      crook    8381: 
1.26      crook    8382: @example
                   8383: include mysource.fs
                   8384: s" mysource.fs" included
                   8385: @end example
1.21      crook    8386: 
1.75      anton    8387: You usually want to include a file only if it is not included already
1.26      crook    8388: (by, say, another source file). In that case, you can use one of these
1.45      crook    8389: three formats:
1.21      crook    8390: 
1.26      crook    8391: @example
                   8392: require mysource.fs
                   8393: needs mysource.fs
                   8394: s" mysource.fs" required
                   8395: @end example
1.21      crook    8396: 
1.26      crook    8397: @cindex stack effect of included files
                   8398: @cindex including files, stack effect
1.45      crook    8399: It is good practice to write your source files such that interpreting them
                   8400: does not change the stack. Source files designed in this way can be used with
1.26      crook    8401: @code{required} and friends without complications. For example:
1.21      crook    8402: 
1.26      crook    8403: @example
1.75      anton    8404: 1024 require foo.fs drop
1.26      crook    8405: @end example
1.21      crook    8406: 
1.75      anton    8407: Here you want to pass the argument 1024 (e.g., a buffer size) to
                   8408: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
                   8409: ), which allows its use with @code{require}.  Of course with such
                   8410: parameters to required files, you have to ensure that the first
                   8411: @code{require} fits for all uses (i.e., @code{require} it early in the
                   8412: master load file).
1.44      crook    8413: 
1.26      crook    8414: doc-include-file
                   8415: doc-included
1.28      crook    8416: doc-included?
1.26      crook    8417: doc-include
                   8418: doc-required
                   8419: doc-require
                   8420: doc-needs
1.75      anton    8421: @c doc-init-included-files @c internal
                   8422: doc-sourcefilename
                   8423: doc-sourceline#
1.44      crook    8424: 
1.26      crook    8425: A definition in ANS Forth for @code{required} is provided in
                   8426: @file{compat/required.fs}.
1.21      crook    8427: 
1.26      crook    8428: @c -------------------------------------------------------------
                   8429: @node General files, Search Paths, Forth source files, Files
                   8430: @subsection General files
                   8431: @cindex general files
                   8432: @cindex file-handling
1.21      crook    8433: 
1.75      anton    8434: Files are opened/created by name and type. The following file access
                   8435: methods (FAMs) are recognised:
1.44      crook    8436: 
1.75      anton    8437: @cindex fam (file access method)
1.26      crook    8438: doc-r/o
                   8439: doc-r/w
                   8440: doc-w/o
                   8441: doc-bin
1.1       anton    8442: 
1.44      crook    8443: 
1.26      crook    8444: When a file is opened/created, it returns a file identifier,
1.29      crook    8445: @i{wfileid} that is used for all other file commands. All file
                   8446: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    8447: successful operation and an implementation-defined non-zero value in the
                   8448: case of an error.
1.21      crook    8449: 
1.44      crook    8450: 
1.26      crook    8451: doc-open-file
                   8452: doc-create-file
1.21      crook    8453: 
1.26      crook    8454: doc-close-file
                   8455: doc-delete-file
                   8456: doc-rename-file
                   8457: doc-read-file
                   8458: doc-read-line
                   8459: doc-write-file
                   8460: doc-write-line
                   8461: doc-emit-file
                   8462: doc-flush-file
1.21      crook    8463: 
1.26      crook    8464: doc-file-status
                   8465: doc-file-position
                   8466: doc-reposition-file
                   8467: doc-file-size
                   8468: doc-resize-file
1.21      crook    8469: 
1.93      anton    8470: doc-slurp-file
                   8471: doc-slurp-fid
1.44      crook    8472: 
1.26      crook    8473: @c ---------------------------------------------------------
1.48      anton    8474: @node Search Paths,  , General files, Files
1.26      crook    8475: @subsection Search Paths
                   8476: @cindex path for @code{included}
                   8477: @cindex file search path
                   8478: @cindex @code{include} search path
                   8479: @cindex search path for files
1.21      crook    8480: 
1.26      crook    8481: If you specify an absolute filename (i.e., a filename starting with
                   8482: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   8483: @samp{C:...})) for @code{included} and friends, that file is included
                   8484: just as you would expect.
1.21      crook    8485: 
1.75      anton    8486: If the filename starts with @file{./}, this refers to the directory that
                   8487: the present file was @code{included} from.  This allows files to include
                   8488: other files relative to their own position (irrespective of the current
                   8489: working directory or the absolute position).  This feature is essential
                   8490: for libraries consisting of several files, where a file may include
                   8491: other files from the library.  It corresponds to @code{#include "..."}
                   8492: in C. If the current input source is not a file, @file{.} refers to the
                   8493: directory of the innermost file being included, or, if there is no file
                   8494: being included, to the current working directory.
                   8495: 
                   8496: For relative filenames (not starting with @file{./}), Gforth uses a
                   8497: search path similar to Forth's search order (@pxref{Word Lists}). It
                   8498: tries to find the given filename in the directories present in the path,
                   8499: and includes the first one it finds. There are separate search paths for
                   8500: Forth source files and general files.  If the search path contains the
                   8501: directory @file{.}, this refers to the directory of the current file, or
                   8502: the working directory, as if the file had been specified with @file{./}.
1.21      crook    8503: 
1.26      crook    8504: Use @file{~+} to refer to the current working directory (as in the
                   8505: @code{bash}).
1.1       anton    8506: 
1.75      anton    8507: @c anton: fold the following subsubsections into this subsection?
1.1       anton    8508: 
1.48      anton    8509: @menu
1.75      anton    8510: * Source Search Paths::         
1.48      anton    8511: * General Search Paths::        
                   8512: @end menu
                   8513: 
1.26      crook    8514: @c ---------------------------------------------------------
1.75      anton    8515: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
                   8516: @subsubsection Source Search Paths
                   8517: @cindex search path control, source files
1.5       anton    8518: 
1.26      crook    8519: The search path is initialized when you start Gforth (@pxref{Invoking
1.75      anton    8520: Gforth}). You can display it and change it using @code{fpath} in
                   8521: combination with the general path handling words.
1.5       anton    8522: 
1.75      anton    8523: doc-fpath
                   8524: @c the functionality of the following words is easily available through
                   8525: @c   fpath and the general path words.  The may go away.
                   8526: @c doc-.fpath
                   8527: @c doc-fpath+
                   8528: @c doc-fpath=
                   8529: @c doc-open-fpath-file
1.44      crook    8530: 
                   8531: @noindent
1.26      crook    8532: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    8533: 
1.26      crook    8534: @example
1.75      anton    8535: fpath path= /usr/lib/forth/|./
1.26      crook    8536: require timer.fs
                   8537: @end example
1.5       anton    8538: 
1.75      anton    8539: 
1.26      crook    8540: @c ---------------------------------------------------------
1.75      anton    8541: @node General Search Paths,  , Source Search Paths, Search Paths
1.26      crook    8542: @subsubsection General Search Paths
1.75      anton    8543: @cindex search path control, source files
1.5       anton    8544: 
1.26      crook    8545: Your application may need to search files in several directories, like
                   8546: @code{included} does. To facilitate this, Gforth allows you to define
                   8547: and use your own search paths, by providing generic equivalents of the
                   8548: Forth search path words:
1.5       anton    8549: 
1.75      anton    8550: doc-open-path-file
                   8551: doc-path-allot
                   8552: doc-clear-path
                   8553: doc-also-path
1.26      crook    8554: doc-.path
                   8555: doc-path+
                   8556: doc-path=
1.5       anton    8557: 
1.75      anton    8558: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44      crook    8559: 
1.75      anton    8560: Here's an example of creating an empty search path:
                   8561: @c
1.26      crook    8562: @example
1.75      anton    8563: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26      crook    8564: @end example
1.5       anton    8565: 
1.26      crook    8566: @c -------------------------------------------------------------
                   8567: @node Blocks, Other I/O, Files, Words
                   8568: @section Blocks
1.28      crook    8569: @cindex I/O - blocks
                   8570: @cindex blocks
                   8571: 
                   8572: When you run Gforth on a modern desk-top computer, it runs under the
                   8573: control of an operating system which provides certain services.  One of
                   8574: these services is @var{file services}, which allows Forth source code
                   8575: and data to be stored in files and read into Gforth (@pxref{Files}).
                   8576: 
                   8577: Traditionally, Forth has been an important programming language on
                   8578: systems where it has interfaced directly to the underlying hardware with
                   8579: no intervening operating system. Forth provides a mechanism, called
1.29      crook    8580: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    8581: 
                   8582: A block is a 1024-byte data area, which can be used to hold data or
                   8583: Forth source code. No structure is imposed on the contents of the
                   8584: block. A block is identified by its number; blocks are numbered
                   8585: contiguously from 1 to an implementation-defined maximum.
                   8586: 
                   8587: A typical system that used blocks but no operating system might use a
                   8588: single floppy-disk drive for mass storage, with the disks formatted to
                   8589: provide 256-byte sectors. Blocks would be implemented by assigning the
                   8590: first four sectors of the disk to block 1, the second four sectors to
                   8591: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   8592: would not contain any file system information, just the set of blocks.
                   8593: 
1.29      crook    8594: @cindex blocks file
1.28      crook    8595: On systems that do provide file services, blocks are typically
1.29      crook    8596: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    8597: file}.  The size of the blocks file will be an exact multiple of 1024
                   8598: bytes, corresponding to the number of blocks it contains. This is the
                   8599: mechanism that Gforth uses.
                   8600: 
1.29      crook    8601: @cindex @file{blocks.fb}
1.75      anton    8602: Only one blocks file can be open at a time. If you use block words without
1.28      crook    8603: having specified a blocks file, Gforth defaults to the blocks file
                   8604: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75      anton    8605: locate a blocks file (@pxref{Source Search Paths}).
1.28      crook    8606: 
1.29      crook    8607: @cindex block buffers
1.28      crook    8608: When you read and write blocks under program control, Gforth uses a
1.29      crook    8609: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    8610: not used when you use @code{load} to interpret the contents of a block.
                   8611: 
1.75      anton    8612: The behaviour of the block buffers is analagous to that of a cache.
                   8613: Each block buffer has three states:
1.28      crook    8614: 
                   8615: @itemize @bullet
                   8616: @item
                   8617: Unassigned
                   8618: @item
                   8619: Assigned-clean
                   8620: @item
                   8621: Assigned-dirty
                   8622: @end itemize
                   8623: 
1.29      crook    8624: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    8625: block, the block (specified by its block number) must be assigned to a
                   8626: block buffer.
                   8627: 
                   8628: The assignment of a block to a block buffer is performed by @code{block}
                   8629: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   8630: contents of a block. Use @code{buffer} when you don't care about the
                   8631: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    8632: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    8633: with the particular block is already stored in a block buffer due to an
                   8634: earlier @code{block} command, @code{buffer} will return that block
                   8635: buffer and the existing contents of the block will be
                   8636: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    8637: block buffer for the block.}.
1.28      crook    8638: 
1.47      crook    8639: Once a block has been assigned to a block buffer using @code{block} or
1.75      anton    8640: @code{buffer}, that block buffer becomes the @i{current block
                   8641: buffer}. Data may only be manipulated (read or written) within the
                   8642: current block buffer.
1.47      crook    8643: 
                   8644: When the contents of the current block buffer has been modified it is
1.48      anton    8645: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75      anton    8646: either abandon the changes (by doing nothing) or mark the block as
                   8647: changed (assigned-dirty), using @code{update}. Using @code{update} does
                   8648: not change the blocks file; it simply changes a block buffer's state to
                   8649: @i{assigned-dirty}.  The block will be written implicitly when it's
                   8650: buffer is needed for another block, or explicitly by @code{flush} or
                   8651: @code{save-buffers}.
                   8652: 
                   8653: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
                   8654: blocks file on disk. Leaving Gforth with @code{bye} also performs a
                   8655: @code{flush}.
1.28      crook    8656: 
1.29      crook    8657: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    8658: algorithm to assign a block buffer to a block. That means that any
                   8659: particular block can only be assigned to one specific block buffer,
1.29      crook    8660: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    8661: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   8662: the new block immediately. If it is @i{assigned-dirty} its current
                   8663: contents are written back to the blocks file on disk before it is
1.28      crook    8664: allocated to the new block.
                   8665: 
                   8666: Although no structure is imposed on the contents of a block, it is
                   8667: traditional to display the contents as 16 lines each of 64 characters.  A
                   8668: block provides a single, continuous stream of input (for example, it
                   8669: acts as a single parse area) -- there are no end-of-line characters
                   8670: within a block, and no end-of-file character at the end of a
                   8671: block. There are two consequences of this:
1.26      crook    8672: 
1.28      crook    8673: @itemize @bullet
                   8674: @item
                   8675: The last character of one line wraps straight into the first character
                   8676: of the following line
                   8677: @item
                   8678: The word @code{\} -- comment to end of line -- requires special
                   8679: treatment; in the context of a block it causes all characters until the
                   8680: end of the current 64-character ``line'' to be ignored.
                   8681: @end itemize
                   8682: 
                   8683: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    8684: the current blocks file will be extended to the appropriate size and the
1.28      crook    8685: block buffer will be initialised with spaces.
                   8686: 
1.47      crook    8687: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   8688: for details) but doesn't encourage the use of blocks; the mechanism is
                   8689: only provided for backward compatibility -- ANS Forth requires blocks to
                   8690: be available when files are.
1.28      crook    8691: 
                   8692: Common techniques that are used when working with blocks include:
                   8693: 
                   8694: @itemize @bullet
                   8695: @item
                   8696: A screen editor that allows you to edit blocks without leaving the Forth
                   8697: environment.
                   8698: @item
                   8699: Shadow screens; where every code block has an associated block
                   8700: containing comments (for example: code in odd block numbers, comments in
                   8701: even block numbers). Typically, the block editor provides a convenient
                   8702: mechanism to toggle between code and comments.
                   8703: @item
                   8704: Load blocks; a single block (typically block 1) contains a number of
                   8705: @code{thru} commands which @code{load} the whole of the application.
                   8706: @end itemize
1.26      crook    8707: 
1.29      crook    8708: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   8709: integrated into a Forth programming environment.
1.26      crook    8710: 
                   8711: @comment TODO what about errors on open-blocks?
1.44      crook    8712: 
1.26      crook    8713: doc-open-blocks
                   8714: doc-use
1.75      anton    8715: doc-block-offset
1.26      crook    8716: doc-get-block-fid
                   8717: doc-block-position
1.28      crook    8718: 
1.75      anton    8719: doc-list
1.28      crook    8720: doc-scr
                   8721: 
1.45      crook    8722: doc---gforthman-block
1.28      crook    8723: doc-buffer
                   8724: 
1.75      anton    8725: doc-empty-buffers
                   8726: doc-empty-buffer
1.26      crook    8727: doc-update
1.28      crook    8728: doc-updated?
1.26      crook    8729: doc-save-buffers
1.75      anton    8730: doc-save-buffer
1.26      crook    8731: doc-flush
1.28      crook    8732: 
1.26      crook    8733: doc-load
                   8734: doc-thru
                   8735: doc-+load
                   8736: doc-+thru
1.45      crook    8737: doc---gforthman--->
1.26      crook    8738: doc-block-included
                   8739: 
1.44      crook    8740: 
1.26      crook    8741: @c -------------------------------------------------------------
1.78      anton    8742: @node Other I/O, Locals, Blocks, Words
1.26      crook    8743: @section Other I/O
1.28      crook    8744: @cindex I/O - keyboard and display
1.26      crook    8745: 
                   8746: @menu
                   8747: * Simple numeric output::       Predefined formats
                   8748: * Formatted numeric output::    Formatted (pictured) output
                   8749: * String Formats::              How Forth stores strings in memory
1.67      anton    8750: * Displaying characters and strings::  Other stuff
1.26      crook    8751: * Input::                       Input
                   8752: @end menu
                   8753: 
                   8754: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8755: @subsection Simple numeric output
1.28      crook    8756: @cindex numeric output - simple/free-format
1.5       anton    8757: 
1.26      crook    8758: The simplest output functions are those that display numbers from the
                   8759: data or floating-point stacks. Floating-point output is always displayed
                   8760: using base 10. Numbers displayed from the data stack use the value stored
                   8761: in @code{base}.
1.5       anton    8762: 
1.44      crook    8763: 
1.26      crook    8764: doc-.
                   8765: doc-dec.
                   8766: doc-hex.
                   8767: doc-u.
                   8768: doc-.r
                   8769: doc-u.r
                   8770: doc-d.
                   8771: doc-ud.
                   8772: doc-d.r
                   8773: doc-ud.r
                   8774: doc-f.
                   8775: doc-fe.
                   8776: doc-fs.
1.5       anton    8777: 
1.44      crook    8778: 
1.26      crook    8779: Examples of printing the number 1234.5678E23 in the different floating-point output
                   8780: formats are shown below:
1.5       anton    8781: 
                   8782: @example
1.26      crook    8783: f. 123456779999999000000000000.
                   8784: fe. 123.456779999999E24
                   8785: fs. 1.23456779999999E26
1.5       anton    8786: @end example
                   8787: 
                   8788: 
1.26      crook    8789: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   8790: @subsection Formatted numeric output
1.28      crook    8791: @cindex formatted numeric output
1.26      crook    8792: @cindex pictured numeric output
1.28      crook    8793: @cindex numeric output - formatted
1.26      crook    8794: 
1.29      crook    8795: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    8796: output} for formatted printing of integers.  In this technique, digits
                   8797: are extracted from the number (using the current output radix defined by
                   8798: @code{base}), converted to ASCII codes and appended to a string that is
                   8799: built in a scratch-pad area of memory (@pxref{core-idef,
                   8800: Implementation-defined options, Implementation-defined
                   8801: options}). Arbitrary characters can be appended to the string during the
                   8802: extraction process. The completed string is specified by an address
                   8803: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   8804: under program control.
1.5       anton    8805: 
1.75      anton    8806: All of the integer output words described in the previous section
                   8807: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
                   8808: numeric output.
1.5       anton    8809: 
1.47      crook    8810: Three important things to remember about pictured numeric output:
1.5       anton    8811: 
1.26      crook    8812: @itemize @bullet
                   8813: @item
1.28      crook    8814: It always operates on double-precision numbers; to display a
1.49      anton    8815: single-precision number, convert it first (for ways of doing this
                   8816: @pxref{Double precision}).
1.26      crook    8817: @item
1.28      crook    8818: It always treats the double-precision number as though it were
                   8819: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    8820: @item
                   8821: The string is built up from right to left; least significant digit first.
                   8822: @end itemize
1.5       anton    8823: 
1.44      crook    8824: 
1.26      crook    8825: doc-<#
1.47      crook    8826: doc-<<#
1.26      crook    8827: doc-#
                   8828: doc-#s
                   8829: doc-hold
                   8830: doc-sign
                   8831: doc-#>
1.47      crook    8832: doc-#>>
1.5       anton    8833: 
1.26      crook    8834: doc-represent
1.5       anton    8835: 
1.44      crook    8836: 
                   8837: @noindent
1.26      crook    8838: Here are some examples of using pictured numeric output:
1.5       anton    8839: 
                   8840: @example
1.26      crook    8841: : my-u. ( u -- )
                   8842:   \ Simplest use of pns.. behaves like Standard u. 
                   8843:   0              \ convert to unsigned double
1.75      anton    8844:   <<#            \ start conversion
1.26      crook    8845:   #s             \ convert all digits
                   8846:   #>             \ complete conversion
1.75      anton    8847:   TYPE SPACE     \ display, with trailing space
                   8848:   #>> ;          \ release hold area
1.5       anton    8849: 
1.26      crook    8850: : cents-only ( u -- )
                   8851:   0              \ convert to unsigned double
1.75      anton    8852:   <<#            \ start conversion
1.26      crook    8853:   # #            \ convert two least-significant digits
                   8854:   #>             \ complete conversion, discard other digits
1.75      anton    8855:   TYPE SPACE     \ display, with trailing space
                   8856:   #>> ;          \ release hold area
1.5       anton    8857: 
1.26      crook    8858: : dollars-and-cents ( u -- )
                   8859:   0              \ convert to unsigned double
1.75      anton    8860:   <<#            \ start conversion
1.26      crook    8861:   # #            \ convert two least-significant digits
                   8862:   [char] . hold  \ insert decimal point
                   8863:   #s             \ convert remaining digits
                   8864:   [char] $ hold  \ append currency symbol
                   8865:   #>             \ complete conversion
1.75      anton    8866:   TYPE SPACE     \ display, with trailing space
                   8867:   #>> ;          \ release hold area
1.5       anton    8868: 
1.26      crook    8869: : my-. ( n -- )
                   8870:   \ handling negatives.. behaves like Standard .
                   8871:   s>d            \ convert to signed double
                   8872:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8873:   <<#            \ start conversion
1.26      crook    8874:   #s             \ convert all digits
                   8875:   rot sign       \ get at sign byte, append "-" if needed
                   8876:   #>             \ complete conversion
1.75      anton    8877:   TYPE SPACE     \ display, with trailing space
                   8878:   #>> ;          \ release hold area
1.5       anton    8879: 
1.26      crook    8880: : account. ( n -- )
1.75      anton    8881:   \ accountants don't like minus signs, they use parentheses
1.26      crook    8882:   \ for negative numbers
                   8883:   s>d            \ convert to signed double
                   8884:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8885:   <<#            \ start conversion
1.26      crook    8886:   2 pick         \ get copy of sign byte
                   8887:   0< IF [char] ) hold THEN \ right-most character of output
                   8888:   #s             \ convert all digits
                   8889:   rot            \ get at sign byte
                   8890:   0< IF [char] ( hold THEN
                   8891:   #>             \ complete conversion
1.75      anton    8892:   TYPE SPACE     \ display, with trailing space
                   8893:   #>> ;          \ release hold area
                   8894: 
1.5       anton    8895: @end example
                   8896: 
1.26      crook    8897: Here are some examples of using these words:
1.5       anton    8898: 
                   8899: @example
1.26      crook    8900: 1 my-u. 1
                   8901: hex -1 my-u. decimal FFFFFFFF
                   8902: 1 cents-only 01
                   8903: 1234 cents-only 34
                   8904: 2 dollars-and-cents $0.02
                   8905: 1234 dollars-and-cents $12.34
                   8906: 123 my-. 123
                   8907: -123 my. -123
                   8908: 123 account. 123
                   8909: -456 account. (456)
1.5       anton    8910: @end example
                   8911: 
                   8912: 
1.26      crook    8913: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   8914: @subsection String Formats
1.27      crook    8915: @cindex strings - see character strings
                   8916: @cindex character strings - formats
1.28      crook    8917: @cindex I/O - see character strings
1.75      anton    8918: @cindex counted strings
                   8919: 
                   8920: @c anton: this does not really belong here; maybe the memory section,
                   8921: @c  or the principles chapter
1.26      crook    8922: 
1.27      crook    8923: Forth commonly uses two different methods for representing character
                   8924: strings:
1.26      crook    8925: 
                   8926: @itemize @bullet
                   8927: @item
                   8928: @cindex address of counted string
1.45      crook    8929: @cindex counted string
1.29      crook    8930: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   8931: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   8932: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    8933: memory.
                   8934: @item
1.29      crook    8935: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   8936: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    8937: first byte of the string.
                   8938: @end itemize
                   8939: 
                   8940: ANS Forth encourages the use of the second format when representing
1.75      anton    8941: strings.
1.26      crook    8942: 
1.44      crook    8943: 
1.26      crook    8944: doc-count
                   8945: 
1.44      crook    8946: 
1.49      anton    8947: For words that move, copy and search for strings see @ref{Memory
                   8948: Blocks}. For words that display characters and strings see
                   8949: @ref{Displaying characters and strings}.
1.26      crook    8950: 
                   8951: @node Displaying characters and strings, Input, String Formats, Other I/O
                   8952: @subsection Displaying characters and strings
1.27      crook    8953: @cindex characters - compiling and displaying
                   8954: @cindex character strings - compiling and displaying
1.26      crook    8955: 
                   8956: This section starts with a glossary of Forth words and ends with a set
                   8957: of examples.
                   8958: 
1.44      crook    8959: 
1.26      crook    8960: doc-bl
                   8961: doc-space
                   8962: doc-spaces
                   8963: doc-emit
                   8964: doc-toupper
                   8965: doc-."
                   8966: doc-.(
                   8967: doc-type
1.44      crook    8968: doc-typewhite
1.26      crook    8969: doc-cr
1.27      crook    8970: @cindex cursor control
1.26      crook    8971: doc-at-xy
                   8972: doc-page
                   8973: doc-s"
                   8974: doc-c"
                   8975: doc-char
                   8976: doc-[char]
                   8977: 
1.44      crook    8978: 
                   8979: @noindent
1.26      crook    8980: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    8981: 
                   8982: @example
1.26      crook    8983: .( text-1)
                   8984: : my-word
                   8985:   ." text-2" cr
                   8986:   .( text-3)
                   8987: ;
                   8988: 
                   8989: ." text-4"
                   8990: 
                   8991: : my-char
                   8992:   [char] ALPHABET emit
                   8993:   char emit
                   8994: ;
1.5       anton    8995: @end example
                   8996: 
1.26      crook    8997: When you load this code into Gforth, the following output is generated:
1.5       anton    8998: 
1.26      crook    8999: @example
1.30      anton    9000: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    9001: @end example
1.5       anton    9002: 
1.26      crook    9003: @itemize @bullet
                   9004: @item
                   9005: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   9006: is an immediate word; it behaves in the same way whether it is used inside
                   9007: or outside a colon definition.
                   9008: @item
                   9009: Message @code{text-4} is displayed because of Gforth's added interpretation
                   9010: semantics for @code{."}.
                   9011: @item
1.29      crook    9012: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    9013: performs the compilation semantics for @code{."} within the definition of
                   9014: @code{my-word}.
                   9015: @end itemize
1.5       anton    9016: 
1.26      crook    9017: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    9018: 
1.26      crook    9019: @example
1.30      anton    9020: @kbd{my-word @key{RET}} text-2
1.26      crook    9021:  ok
1.30      anton    9022: @kbd{my-char fred @key{RET}} Af ok
                   9023: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    9024: @end example
1.5       anton    9025: 
                   9026: @itemize @bullet
                   9027: @item
1.26      crook    9028: Message @code{text-2} is displayed because of the run-time behaviour of
                   9029: @code{."}.
                   9030: @item
                   9031: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   9032: on the stack at run-time. @code{emit} always displays the character
                   9033: when @code{my-char} is executed.
                   9034: @item
                   9035: @code{char} parses a string at run-time and the second @code{emit} displays
                   9036: the first character of the string.
1.5       anton    9037: @item
1.26      crook    9038: If you type @code{see my-char} you can see that @code{[char]} discarded
                   9039: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   9040: definition of @code{my-char}.
1.5       anton    9041: @end itemize
                   9042: 
                   9043: 
                   9044: 
1.48      anton    9045: @node Input,  , Displaying characters and strings, Other I/O
1.26      crook    9046: @subsection Input
                   9047: @cindex input
1.28      crook    9048: @cindex I/O - see input
                   9049: @cindex parsing a string
1.5       anton    9050: 
1.49      anton    9051: For ways of storing character strings in memory see @ref{String Formats}.
1.5       anton    9052: 
1.27      crook    9053: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29      crook    9054: @comment then index them
1.27      crook    9055: 
1.44      crook    9056: 
1.27      crook    9057: doc-key
                   9058: doc-key?
1.45      crook    9059: doc-ekey
                   9060: doc-ekey?
                   9061: doc-ekey>char
1.26      crook    9062: doc->number
                   9063: doc->float
                   9064: doc-accept
1.27      crook    9065: doc-pad
1.75      anton    9066: @c anton: these belong in the input stream section
1.27      crook    9067: doc-parse
                   9068: doc-word
                   9069: doc-sword
1.75      anton    9070: doc-name
1.27      crook    9071: doc-refill
                   9072: @comment obsolescent words..
                   9073: doc-convert
1.26      crook    9074: doc-query
                   9075: doc-expect
1.27      crook    9076: doc-span
1.5       anton    9077: 
                   9078: 
1.78      anton    9079: @c -------------------------------------------------------------
                   9080: @node Locals, Structures, Other I/O, Words
                   9081: @section Locals
                   9082: @cindex locals
                   9083: 
                   9084: Local variables can make Forth programming more enjoyable and Forth
                   9085: programs easier to read. Unfortunately, the locals of ANS Forth are
                   9086: laden with restrictions. Therefore, we provide not only the ANS Forth
                   9087: locals wordset, but also our own, more powerful locals wordset (we
                   9088: implemented the ANS Forth locals wordset through our locals wordset).
1.44      crook    9089: 
1.78      anton    9090: The ideas in this section have also been published in M. Anton Ertl,
                   9091: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
                   9092: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12      anton    9093: 
                   9094: @menu
1.78      anton    9095: * Gforth locals::               
                   9096: * ANS Forth locals::            
1.5       anton    9097: @end menu
                   9098: 
1.78      anton    9099: @node Gforth locals, ANS Forth locals, Locals, Locals
                   9100: @subsection Gforth locals
                   9101: @cindex Gforth locals
                   9102: @cindex locals, Gforth style
1.5       anton    9103: 
1.78      anton    9104: Locals can be defined with
1.44      crook    9105: 
1.78      anton    9106: @example
                   9107: @{ local1 local2 ... -- comment @}
                   9108: @end example
                   9109: or
                   9110: @example
                   9111: @{ local1 local2 ... @}
                   9112: @end example
1.5       anton    9113: 
1.78      anton    9114: E.g.,
                   9115: @example
                   9116: : max @{ n1 n2 -- n3 @}
                   9117:  n1 n2 > if
                   9118:    n1
                   9119:  else
                   9120:    n2
                   9121:  endif ;
                   9122: @end example
1.44      crook    9123: 
1.78      anton    9124: The similarity of locals definitions with stack comments is intended. A
                   9125: locals definition often replaces the stack comment of a word. The order
                   9126: of the locals corresponds to the order in a stack comment and everything
                   9127: after the @code{--} is really a comment.
1.77      anton    9128: 
1.78      anton    9129: This similarity has one disadvantage: It is too easy to confuse locals
                   9130: declarations with stack comments, causing bugs and making them hard to
                   9131: find. However, this problem can be avoided by appropriate coding
                   9132: conventions: Do not use both notations in the same program. If you do,
                   9133: they should be distinguished using additional means, e.g. by position.
1.77      anton    9134: 
1.78      anton    9135: @cindex types of locals
                   9136: @cindex locals types
                   9137: The name of the local may be preceded by a type specifier, e.g.,
                   9138: @code{F:} for a floating point value:
1.5       anton    9139: 
1.78      anton    9140: @example
                   9141: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   9142: \ complex multiplication
                   9143:  Ar Br f* Ai Bi f* f-
                   9144:  Ar Bi f* Ai Br f* f+ ;
                   9145: @end example
1.44      crook    9146: 
1.78      anton    9147: @cindex flavours of locals
                   9148: @cindex locals flavours
                   9149: @cindex value-flavoured locals
                   9150: @cindex variable-flavoured locals
                   9151: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   9152: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   9153: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   9154: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   9155: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   9156: produces its address (which becomes invalid when the variable's scope is
                   9157: left). E.g., the standard word @code{emit} can be defined in terms of
                   9158: @code{type} like this:
1.5       anton    9159: 
1.78      anton    9160: @example
                   9161: : emit @{ C^ char* -- @}
                   9162:     char* 1 type ;
                   9163: @end example
1.5       anton    9164: 
1.78      anton    9165: @cindex default type of locals
                   9166: @cindex locals, default type
                   9167: A local without type specifier is a @code{W:} local. Both flavours of
                   9168: locals are initialized with values from the data or FP stack.
1.44      crook    9169: 
1.78      anton    9170: Currently there is no way to define locals with user-defined data
                   9171: structures, but we are working on it.
1.5       anton    9172: 
1.78      anton    9173: Gforth allows defining locals everywhere in a colon definition. This
                   9174: poses the following questions:
1.5       anton    9175: 
1.78      anton    9176: @menu
                   9177: * Where are locals visible by name?::  
                   9178: * How long do locals live?::    
                   9179: * Locals programming style::    
                   9180: * Locals implementation::       
                   9181: @end menu
1.44      crook    9182: 
1.78      anton    9183: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   9184: @subsubsection Where are locals visible by name?
                   9185: @cindex locals visibility
                   9186: @cindex visibility of locals
                   9187: @cindex scope of locals
1.5       anton    9188: 
1.78      anton    9189: Basically, the answer is that locals are visible where you would expect
                   9190: it in block-structured languages, and sometimes a little longer. If you
                   9191: want to restrict the scope of a local, enclose its definition in
                   9192: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    9193: 
                   9194: 
1.78      anton    9195: doc-scope
                   9196: doc-endscope
1.5       anton    9197: 
                   9198: 
1.78      anton    9199: These words behave like control structure words, so you can use them
                   9200: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   9201: arbitrary ways.
1.77      anton    9202: 
1.78      anton    9203: If you want a more exact answer to the visibility question, here's the
                   9204: basic principle: A local is visible in all places that can only be
                   9205: reached through the definition of the local@footnote{In compiler
                   9206: construction terminology, all places dominated by the definition of the
                   9207: local.}. In other words, it is not visible in places that can be reached
                   9208: without going through the definition of the local. E.g., locals defined
                   9209: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   9210: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   9211: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77      anton    9212: 
1.78      anton    9213: The reasoning behind this solution is: We want to have the locals
                   9214: visible as long as it is meaningful. The user can always make the
                   9215: visibility shorter by using explicit scoping. In a place that can
                   9216: only be reached through the definition of a local, the meaning of a
                   9217: local name is clear. In other places it is not: How is the local
                   9218: initialized at the control flow path that does not contain the
                   9219: definition? Which local is meant, if the same name is defined twice in
                   9220: two independent control flow paths?
1.77      anton    9221: 
1.78      anton    9222: This should be enough detail for nearly all users, so you can skip the
                   9223: rest of this section. If you really must know all the gory details and
                   9224: options, read on.
1.77      anton    9225: 
1.78      anton    9226: In order to implement this rule, the compiler has to know which places
                   9227: are unreachable. It knows this automatically after @code{AHEAD},
                   9228: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   9229: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   9230: compiler that the control flow never reaches that place. If
                   9231: @code{UNREACHABLE} is not used where it could, the only consequence is
                   9232: that the visibility of some locals is more limited than the rule above
                   9233: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   9234: lie to the compiler), buggy code will be produced.
1.77      anton    9235: 
1.5       anton    9236: 
1.78      anton    9237: doc-unreachable
1.5       anton    9238: 
1.23      crook    9239: 
1.78      anton    9240: Another problem with this rule is that at @code{BEGIN}, the compiler
                   9241: does not know which locals will be visible on the incoming
                   9242: back-edge. All problems discussed in the following are due to this
                   9243: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   9244: loops as examples; the discussion also applies to @code{?DO} and other
                   9245: loops). Perhaps the most insidious example is:
1.26      crook    9246: @example
1.78      anton    9247: AHEAD
                   9248: BEGIN
                   9249:   x
                   9250: [ 1 CS-ROLL ] THEN
                   9251:   @{ x @}
                   9252:   ...
                   9253: UNTIL
1.26      crook    9254: @end example
1.23      crook    9255: 
1.78      anton    9256: This should be legal according to the visibility rule. The use of
                   9257: @code{x} can only be reached through the definition; but that appears
                   9258: textually below the use.
                   9259: 
                   9260: From this example it is clear that the visibility rules cannot be fully
                   9261: implemented without major headaches. Our implementation treats common
                   9262: cases as advertised and the exceptions are treated in a safe way: The
                   9263: compiler makes a reasonable guess about the locals visible after a
                   9264: @code{BEGIN}; if it is too pessimistic, the
                   9265: user will get a spurious error about the local not being defined; if the
                   9266: compiler is too optimistic, it will notice this later and issue a
                   9267: warning. In the case above the compiler would complain about @code{x}
                   9268: being undefined at its use. You can see from the obscure examples in
                   9269: this section that it takes quite unusual control structures to get the
                   9270: compiler into trouble, and even then it will often do fine.
1.23      crook    9271: 
1.78      anton    9272: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   9273: is that all locals visible before the @code{BEGIN} will also be
                   9274: visible after the @code{BEGIN}. This guess is valid for all loops that
                   9275: are entered only through the @code{BEGIN}, in particular, for normal
                   9276: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   9277: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   9278: compiler. When the branch to the @code{BEGIN} is finally generated by
                   9279: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   9280: warns the user if it was too optimistic:
1.26      crook    9281: @example
1.78      anton    9282: IF
                   9283:   @{ x @}
                   9284: BEGIN
                   9285:   \ x ? 
                   9286: [ 1 cs-roll ] THEN
                   9287:   ...
                   9288: UNTIL
1.26      crook    9289: @end example
1.23      crook    9290: 
1.78      anton    9291: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   9292: optimistically assumes that it lives until the @code{THEN}. It notices
                   9293: this difference when it compiles the @code{UNTIL} and issues a
                   9294: warning. The user can avoid the warning, and make sure that @code{x}
                   9295: is not used in the wrong area by using explicit scoping:
                   9296: @example
                   9297: IF
                   9298:   SCOPE
                   9299:   @{ x @}
                   9300:   ENDSCOPE
                   9301: BEGIN
                   9302: [ 1 cs-roll ] THEN
                   9303:   ...
                   9304: UNTIL
                   9305: @end example
1.23      crook    9306: 
1.78      anton    9307: Since the guess is optimistic, there will be no spurious error messages
                   9308: about undefined locals.
1.44      crook    9309: 
1.78      anton    9310: If the @code{BEGIN} is not reachable from above (e.g., after
                   9311: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   9312: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   9313: defined later. Therefore, the compiler assumes that no locals are
                   9314: visible after the @code{BEGIN}. However, the user can use
                   9315: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   9316: visible at the BEGIN as at the point where the top control-flow stack
                   9317: item was created.
1.23      crook    9318: 
1.44      crook    9319: 
1.78      anton    9320: doc-assume-live
1.26      crook    9321: 
1.23      crook    9322: 
1.78      anton    9323: @noindent
                   9324: E.g.,
                   9325: @example
                   9326: @{ x @}
                   9327: AHEAD
                   9328: ASSUME-LIVE
                   9329: BEGIN
                   9330:   x
                   9331: [ 1 CS-ROLL ] THEN
                   9332:   ...
                   9333: UNTIL
                   9334: @end example
1.44      crook    9335: 
1.78      anton    9336: Other cases where the locals are defined before the @code{BEGIN} can be
                   9337: handled by inserting an appropriate @code{CS-ROLL} before the
                   9338: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   9339: behind the @code{ASSUME-LIVE}).
1.23      crook    9340: 
1.78      anton    9341: Cases where locals are defined after the @code{BEGIN} (but should be
                   9342: visible immediately after the @code{BEGIN}) can only be handled by
                   9343: rearranging the loop. E.g., the ``most insidious'' example above can be
                   9344: arranged into:
                   9345: @example
                   9346: BEGIN
                   9347:   @{ x @}
                   9348:   ... 0=
                   9349: WHILE
                   9350:   x
                   9351: REPEAT
                   9352: @end example
1.44      crook    9353: 
1.78      anton    9354: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
                   9355: @subsubsection How long do locals live?
                   9356: @cindex locals lifetime
                   9357: @cindex lifetime of locals
1.23      crook    9358: 
1.78      anton    9359: The right answer for the lifetime question would be: A local lives at
                   9360: least as long as it can be accessed. For a value-flavoured local this
                   9361: means: until the end of its visibility. However, a variable-flavoured
                   9362: local could be accessed through its address far beyond its visibility
                   9363: scope. Ultimately, this would mean that such locals would have to be
                   9364: garbage collected. Since this entails un-Forth-like implementation
                   9365: complexities, I adopted the same cowardly solution as some other
                   9366: languages (e.g., C): The local lives only as long as it is visible;
                   9367: afterwards its address is invalid (and programs that access it
                   9368: afterwards are erroneous).
1.23      crook    9369: 
1.78      anton    9370: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
                   9371: @subsubsection Locals programming style
                   9372: @cindex locals programming style
                   9373: @cindex programming style, locals
1.23      crook    9374: 
1.78      anton    9375: The freedom to define locals anywhere has the potential to change
                   9376: programming styles dramatically. In particular, the need to use the
                   9377: return stack for intermediate storage vanishes. Moreover, all stack
                   9378: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9379: determined arguments) can be eliminated: If the stack items are in the
                   9380: wrong order, just write a locals definition for all of them; then
                   9381: write the items in the order you want.
1.23      crook    9382: 
1.78      anton    9383: This seems a little far-fetched and eliminating stack manipulations is
                   9384: unlikely to become a conscious programming objective. Still, the number
                   9385: of stack manipulations will be reduced dramatically if local variables
                   9386: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
                   9387: a traditional implementation of @code{max}).
1.23      crook    9388: 
1.78      anton    9389: This shows one potential benefit of locals: making Forth programs more
                   9390: readable. Of course, this benefit will only be realized if the
                   9391: programmers continue to honour the principle of factoring instead of
                   9392: using the added latitude to make the words longer.
1.23      crook    9393: 
1.78      anton    9394: @cindex single-assignment style for locals
                   9395: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9396: every value-flavoured local has only a single assignment and many
                   9397: advantages of functional languages apply to Forth. I.e., programs are
                   9398: easier to analyse, to optimize and to read: It is clear from the
                   9399: definition what the local stands for, it does not turn into something
                   9400: different later.
1.23      crook    9401: 
1.78      anton    9402: E.g., a definition using @code{TO} might look like this:
                   9403: @example
                   9404: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9405:  u1 u2 min 0
                   9406:  ?do
                   9407:    addr1 c@@ addr2 c@@ -
                   9408:    ?dup-if
                   9409:      unloop exit
                   9410:    then
                   9411:    addr1 char+ TO addr1
                   9412:    addr2 char+ TO addr2
                   9413:  loop
                   9414:  u1 u2 - ;
1.26      crook    9415: @end example
1.78      anton    9416: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9417: every loop iteration. @code{strcmp} is a typical example of the
                   9418: readability problems of using @code{TO}. When you start reading
                   9419: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9420: string. Only near the end of the loop you realize that it is something
                   9421: else.
1.23      crook    9422: 
1.78      anton    9423: This can be avoided by defining two locals at the start of the loop that
                   9424: are initialized with the right value for the current iteration.
                   9425: @example
                   9426: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9427:  addr1 addr2
                   9428:  u1 u2 min 0 
                   9429:  ?do @{ s1 s2 @}
                   9430:    s1 c@@ s2 c@@ -
                   9431:    ?dup-if
                   9432:      unloop exit
                   9433:    then
                   9434:    s1 char+ s2 char+
                   9435:  loop
                   9436:  2drop
                   9437:  u1 u2 - ;
                   9438: @end example
                   9439: Here it is clear from the start that @code{s1} has a different value
                   9440: in every loop iteration.
1.23      crook    9441: 
1.78      anton    9442: @node Locals implementation,  , Locals programming style, Gforth locals
                   9443: @subsubsection Locals implementation
                   9444: @cindex locals implementation
                   9445: @cindex implementation of locals
1.23      crook    9446: 
1.78      anton    9447: @cindex locals stack
                   9448: Gforth uses an extra locals stack. The most compelling reason for
                   9449: this is that the return stack is not float-aligned; using an extra stack
                   9450: also eliminates the problems and restrictions of using the return stack
                   9451: as locals stack. Like the other stacks, the locals stack grows toward
                   9452: lower addresses. A few primitives allow an efficient implementation:
                   9453: 
                   9454: 
                   9455: doc-@local#
                   9456: doc-f@local#
                   9457: doc-laddr#
                   9458: doc-lp+!#
                   9459: doc-lp!
                   9460: doc->l
                   9461: doc-f>l
                   9462: 
                   9463: 
                   9464: In addition to these primitives, some specializations of these
                   9465: primitives for commonly occurring inline arguments are provided for
                   9466: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9467: @code{@@local#} for the inline argument 0. The following compiling words
                   9468: compile the right specialized version, or the general version, as
                   9469: appropriate:
1.23      crook    9470: 
1.5       anton    9471: 
1.78      anton    9472: doc-compile-@local
                   9473: doc-compile-f@local
                   9474: doc-compile-lp+!
1.5       anton    9475: 
                   9476: 
1.78      anton    9477: Combinations of conditional branches and @code{lp+!#} like
                   9478: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9479: is taken) are provided for efficiency and correctness in loops.
1.5       anton    9480: 
1.78      anton    9481: A special area in the dictionary space is reserved for keeping the
                   9482: local variable names. @code{@{} switches the dictionary pointer to this
                   9483: area and @code{@}} switches it back and generates the locals
                   9484: initializing code. @code{W:} etc.@ are normal defining words. This
                   9485: special area is cleared at the start of every colon definition.
1.5       anton    9486: 
1.78      anton    9487: @cindex word list for defining locals
                   9488: A special feature of Gforth's dictionary is used to implement the
                   9489: definition of locals without type specifiers: every word list (aka
                   9490: vocabulary) has its own methods for searching
                   9491: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   9492: with a special search method: When it is searched for a word, it
                   9493: actually creates that word using @code{W:}. @code{@{} changes the search
                   9494: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   9495: and then the word list for defining locals without type specifiers.
1.5       anton    9496: 
1.78      anton    9497: The lifetime rules support a stack discipline within a colon
                   9498: definition: The lifetime of a local is either nested with other locals
                   9499: lifetimes or it does not overlap them.
1.23      crook    9500: 
1.78      anton    9501: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   9502: pointer manipulation is generated. Between control structure words
                   9503: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   9504: is the simplest of the other three control flow words. It has to
                   9505: restore the locals stack depth of the corresponding @code{BEGIN}
                   9506: before branching. The code looks like this:
                   9507: @format
                   9508: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   9509: @code{branch} <begin>
                   9510: @end format
1.26      crook    9511: 
1.78      anton    9512: @code{UNTIL} is a little more complicated: If it branches back, it
                   9513: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   9514: the locals stack must not be changed. The compiler generates the
                   9515: following code:
                   9516: @format
                   9517: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   9518: @end format
                   9519: The locals stack pointer is only adjusted if the branch is taken.
1.44      crook    9520: 
1.78      anton    9521: @code{THEN} can produce somewhat inefficient code:
                   9522: @format
                   9523: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   9524: <orig target>:
                   9525: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   9526: @end format
                   9527: The second @code{lp+!#} adjusts the locals stack pointer from the
                   9528: level at the @i{orig} point to the level after the @code{THEN}. The
                   9529: first @code{lp+!#} adjusts the locals stack pointer from the current
                   9530: level to the level at the orig point, so the complete effect is an
                   9531: adjustment from the current level to the right level after the
                   9532: @code{THEN}.
1.26      crook    9533: 
1.78      anton    9534: @cindex locals information on the control-flow stack
                   9535: @cindex control-flow stack items, locals information
                   9536: In a conventional Forth implementation a dest control-flow stack entry
                   9537: is just the target address and an orig entry is just the address to be
                   9538: patched. Our locals implementation adds a word list to every orig or dest
                   9539: item. It is the list of locals visible (or assumed visible) at the point
                   9540: described by the entry. Our implementation also adds a tag to identify
                   9541: the kind of entry, in particular to differentiate between live and dead
                   9542: (reachable and unreachable) orig entries.
1.26      crook    9543: 
1.78      anton    9544: A few unusual operations have to be performed on locals word lists:
1.44      crook    9545: 
1.5       anton    9546: 
1.78      anton    9547: doc-common-list
                   9548: doc-sub-list?
                   9549: doc-list-size
1.52      anton    9550: 
                   9551: 
1.78      anton    9552: Several features of our locals word list implementation make these
                   9553: operations easy to implement: The locals word lists are organised as
                   9554: linked lists; the tails of these lists are shared, if the lists
                   9555: contain some of the same locals; and the address of a name is greater
                   9556: than the address of the names behind it in the list.
1.5       anton    9557: 
1.78      anton    9558: Another important implementation detail is the variable
                   9559: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   9560: determine if they can be reached directly or only through the branch
                   9561: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   9562: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   9563: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5       anton    9564: 
1.78      anton    9565: Counted loops are similar to other loops in most respects, but
                   9566: @code{LEAVE} requires special attention: It performs basically the same
                   9567: service as @code{AHEAD}, but it does not create a control-flow stack
                   9568: entry. Therefore the information has to be stored elsewhere;
                   9569: traditionally, the information was stored in the target fields of the
                   9570: branches created by the @code{LEAVE}s, by organizing these fields into a
                   9571: linked list. Unfortunately, this clever trick does not provide enough
                   9572: space for storing our extended control flow information. Therefore, we
                   9573: introduce another stack, the leave stack. It contains the control-flow
                   9574: stack entries for all unresolved @code{LEAVE}s.
1.44      crook    9575: 
1.78      anton    9576: Local names are kept until the end of the colon definition, even if
                   9577: they are no longer visible in any control-flow path. In a few cases
                   9578: this may lead to increased space needs for the locals name area, but
                   9579: usually less than reclaiming this space would cost in code size.
1.5       anton    9580: 
1.44      crook    9581: 
1.78      anton    9582: @node ANS Forth locals,  , Gforth locals, Locals
                   9583: @subsection ANS Forth locals
                   9584: @cindex locals, ANS Forth style
1.5       anton    9585: 
1.78      anton    9586: The ANS Forth locals wordset does not define a syntax for locals, but
                   9587: words that make it possible to define various syntaxes. One of the
                   9588: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   9589: wordset, i.e.:
1.29      crook    9590: 
                   9591: @example
1.78      anton    9592: @{ local1 local2 ... -- comment @}
                   9593: @end example
                   9594: @noindent
                   9595: or
                   9596: @example
                   9597: @{ local1 local2 ... @}
1.29      crook    9598: @end example
                   9599: 
1.78      anton    9600: The order of the locals corresponds to the order in a stack comment. The
                   9601: restrictions are:
1.5       anton    9602: 
1.78      anton    9603: @itemize @bullet
                   9604: @item
                   9605: Locals can only be cell-sized values (no type specifiers are allowed).
                   9606: @item
                   9607: Locals can be defined only outside control structures.
                   9608: @item
                   9609: Locals can interfere with explicit usage of the return stack. For the
                   9610: exact (and long) rules, see the standard. If you don't use return stack
                   9611: accessing words in a definition using locals, you will be all right. The
                   9612: purpose of this rule is to make locals implementation on the return
                   9613: stack easier.
                   9614: @item
                   9615: The whole definition must be in one line.
                   9616: @end itemize
1.5       anton    9617: 
1.78      anton    9618: Locals defined in ANS Forth behave like @code{VALUE}s
                   9619: (@pxref{Values}). I.e., they are initialized from the stack. Using their
                   9620: name produces their value. Their value can be changed using @code{TO}.
1.77      anton    9621: 
1.78      anton    9622: Since the syntax above is supported by Gforth directly, you need not do
                   9623: anything to use it. If you want to port a program using this syntax to
                   9624: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   9625: syntax on the other system.
1.5       anton    9626: 
1.78      anton    9627: Note that a syntax shown in the standard, section A.13 looks
                   9628: similar, but is quite different in having the order of locals
                   9629: reversed. Beware!
1.5       anton    9630: 
1.78      anton    9631: The ANS Forth locals wordset itself consists of one word:
1.5       anton    9632: 
1.78      anton    9633: doc-(local)
1.5       anton    9634: 
1.78      anton    9635: The ANS Forth locals extension wordset defines a syntax using
                   9636: @code{locals|}, but it is so awful that we strongly recommend not to use
                   9637: it. We have implemented this syntax to make porting to Gforth easy, but
                   9638: do not document it here. The problem with this syntax is that the locals
                   9639: are defined in an order reversed with respect to the standard stack
                   9640: comment notation, making programs harder to read, and easier to misread
                   9641: and miswrite. The only merit of this syntax is that it is easy to
                   9642: implement using the ANS Forth locals wordset.
1.53      anton    9643: 
                   9644: 
1.78      anton    9645: @c ----------------------------------------------------------
                   9646: @node Structures, Object-oriented Forth, Locals, Words
                   9647: @section  Structures
                   9648: @cindex structures
                   9649: @cindex records
1.53      anton    9650: 
1.78      anton    9651: This section presents the structure package that comes with Gforth. A
                   9652: version of the package implemented in ANS Forth is available in
                   9653: @file{compat/struct.fs}. This package was inspired by a posting on
                   9654: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   9655: possibly John Hayes). A version of this section has been published in
                   9656: M. Anton Ertl,
                   9657: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
                   9658: Another Forth Structures Package}, Forth Dimensions 19(3), pages
                   9659: 13--16. Marcel Hendrix provided helpful comments.
1.53      anton    9660: 
1.78      anton    9661: @menu
                   9662: * Why explicit structure support?::  
                   9663: * Structure Usage::             
                   9664: * Structure Naming Convention::  
                   9665: * Structure Implementation::    
                   9666: * Structure Glossary::          
                   9667: @end menu
1.55      anton    9668: 
1.78      anton    9669: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   9670: @subsection Why explicit structure support?
1.53      anton    9671: 
1.78      anton    9672: @cindex address arithmetic for structures
                   9673: @cindex structures using address arithmetic
                   9674: If we want to use a structure containing several fields, we could simply
                   9675: reserve memory for it, and access the fields using address arithmetic
                   9676: (@pxref{Address arithmetic}). As an example, consider a structure with
                   9677: the following fields
1.57      anton    9678: 
1.78      anton    9679: @table @code
                   9680: @item a
                   9681: is a float
                   9682: @item b
                   9683: is a cell
                   9684: @item c
                   9685: is a float
                   9686: @end table
1.57      anton    9687: 
1.78      anton    9688: Given the (float-aligned) base address of the structure we get the
                   9689: address of the field
1.52      anton    9690: 
1.78      anton    9691: @table @code
                   9692: @item a
                   9693: without doing anything further.
                   9694: @item b
                   9695: with @code{float+}
                   9696: @item c
                   9697: with @code{float+ cell+ faligned}
                   9698: @end table
1.52      anton    9699: 
1.78      anton    9700: It is easy to see that this can become quite tiring. 
1.52      anton    9701: 
1.78      anton    9702: Moreover, it is not very readable, because seeing a
                   9703: @code{cell+} tells us neither which kind of structure is
                   9704: accessed nor what field is accessed; we have to somehow infer the kind
                   9705: of structure, and then look up in the documentation, which field of
                   9706: that structure corresponds to that offset.
1.53      anton    9707: 
1.78      anton    9708: Finally, this kind of address arithmetic also causes maintenance
                   9709: troubles: If you add or delete a field somewhere in the middle of the
                   9710: structure, you have to find and change all computations for the fields
                   9711: afterwards.
1.52      anton    9712: 
1.78      anton    9713: So, instead of using @code{cell+} and friends directly, how
                   9714: about storing the offsets in constants:
1.52      anton    9715: 
1.78      anton    9716: @example
                   9717: 0 constant a-offset
                   9718: 0 float+ constant b-offset
                   9719: 0 float+ cell+ faligned c-offset
                   9720: @end example
1.64      pazsan   9721: 
1.78      anton    9722: Now we can get the address of field @code{x} with @code{x-offset
                   9723: +}. This is much better in all respects. Of course, you still
                   9724: have to change all later offset definitions if you add a field. You can
                   9725: fix this by declaring the offsets in the following way:
1.57      anton    9726: 
1.78      anton    9727: @example
                   9728: 0 constant a-offset
                   9729: a-offset float+ constant b-offset
                   9730: b-offset cell+ faligned constant c-offset
                   9731: @end example
1.57      anton    9732: 
1.78      anton    9733: Since we always use the offsets with @code{+}, we could use a defining
                   9734: word @code{cfield} that includes the @code{+} in the action of the
                   9735: defined word:
1.64      pazsan   9736: 
1.78      anton    9737: @example
                   9738: : cfield ( n "name" -- )
                   9739:     create ,
                   9740: does> ( name execution: addr1 -- addr2 )
                   9741:     @@ + ;
1.64      pazsan   9742: 
1.78      anton    9743: 0 cfield a
                   9744: 0 a float+ cfield b
                   9745: 0 b cell+ faligned cfield c
                   9746: @end example
1.64      pazsan   9747: 
1.78      anton    9748: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64      pazsan   9749: 
1.78      anton    9750: The structure field words now can be used quite nicely. However,
                   9751: their definition is still a bit cumbersome: We have to repeat the
                   9752: name, the information about size and alignment is distributed before
                   9753: and after the field definitions etc.  The structure package presented
                   9754: here addresses these problems.
1.64      pazsan   9755: 
1.78      anton    9756: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   9757: @subsection Structure Usage
                   9758: @cindex structure usage
1.57      anton    9759: 
1.78      anton    9760: @cindex @code{field} usage
                   9761: @cindex @code{struct} usage
                   9762: @cindex @code{end-struct} usage
                   9763: You can define a structure for a (data-less) linked list with:
1.57      anton    9764: @example
1.78      anton    9765: struct
                   9766:     cell% field list-next
                   9767: end-struct list%
1.57      anton    9768: @end example
                   9769: 
1.78      anton    9770: With the address of the list node on the stack, you can compute the
                   9771: address of the field that contains the address of the next node with
                   9772: @code{list-next}. E.g., you can determine the length of a list
                   9773: with:
1.57      anton    9774: 
                   9775: @example
1.78      anton    9776: : list-length ( list -- n )
                   9777: \ "list" is a pointer to the first element of a linked list
                   9778: \ "n" is the length of the list
                   9779:     0 BEGIN ( list1 n1 )
                   9780:         over
                   9781:     WHILE ( list1 n1 )
                   9782:         1+ swap list-next @@ swap
                   9783:     REPEAT
                   9784:     nip ;
1.57      anton    9785: @end example
                   9786: 
1.78      anton    9787: You can reserve memory for a list node in the dictionary with
                   9788: @code{list% %allot}, which leaves the address of the list node on the
                   9789: stack. For the equivalent allocation on the heap you can use @code{list%
                   9790: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   9791: use @code{list% %allocate}). You can get the the size of a list
                   9792: node with @code{list% %size} and its alignment with @code{list%
                   9793: %alignment}.
                   9794: 
                   9795: Note that in ANS Forth the body of a @code{create}d word is
                   9796: @code{aligned} but not necessarily @code{faligned};
                   9797: therefore, if you do a:
1.57      anton    9798: 
                   9799: @example
1.78      anton    9800: create @emph{name} foo% %allot drop
1.57      anton    9801: @end example
                   9802: 
1.78      anton    9803: @noindent
                   9804: then the memory alloted for @code{foo%} is guaranteed to start at the
                   9805: body of @code{@emph{name}} only if @code{foo%} contains only character,
                   9806: cell and double fields.  Therefore, if your structure contains floats,
                   9807: better use
1.57      anton    9808: 
                   9809: @example
1.78      anton    9810: foo% %allot constant @emph{name}
1.57      anton    9811: @end example
                   9812: 
1.78      anton    9813: @cindex structures containing structures
                   9814: You can include a structure @code{foo%} as a field of
                   9815: another structure, like this:
1.65      anton    9816: @example
1.78      anton    9817: struct
                   9818: ...
                   9819:     foo% field ...
                   9820: ...
                   9821: end-struct ...
1.65      anton    9822: @end example
1.52      anton    9823: 
1.78      anton    9824: @cindex structure extension
                   9825: @cindex extended records
                   9826: Instead of starting with an empty structure, you can extend an
                   9827: existing structure. E.g., a plain linked list without data, as defined
                   9828: above, is hardly useful; You can extend it to a linked list of integers,
                   9829: like this:@footnote{This feature is also known as @emph{extended
                   9830: records}. It is the main innovation in the Oberon language; in other
                   9831: words, adding this feature to Modula-2 led Wirth to create a new
                   9832: language, write a new compiler etc.  Adding this feature to Forth just
                   9833: required a few lines of code.}
1.52      anton    9834: 
1.78      anton    9835: @example
                   9836: list%
                   9837:     cell% field intlist-int
                   9838: end-struct intlist%
                   9839: @end example
1.55      anton    9840: 
1.78      anton    9841: @code{intlist%} is a structure with two fields:
                   9842: @code{list-next} and @code{intlist-int}.
1.55      anton    9843: 
1.78      anton    9844: @cindex structures containing arrays
                   9845: You can specify an array type containing @emph{n} elements of
                   9846: type @code{foo%} like this:
1.55      anton    9847: 
                   9848: @example
1.78      anton    9849: foo% @emph{n} *
1.56      anton    9850: @end example
1.55      anton    9851: 
1.78      anton    9852: You can use this array type in any place where you can use a normal
                   9853: type, e.g., when defining a @code{field}, or with
                   9854: @code{%allot}.
                   9855: 
                   9856: @cindex first field optimization
                   9857: The first field is at the base address of a structure and the word for
                   9858: this field (e.g., @code{list-next}) actually does not change the address
                   9859: on the stack. You may be tempted to leave it away in the interest of
                   9860: run-time and space efficiency. This is not necessary, because the
                   9861: structure package optimizes this case: If you compile a first-field
                   9862: words, no code is generated. So, in the interest of readability and
                   9863: maintainability you should include the word for the field when accessing
                   9864: the field.
1.52      anton    9865: 
                   9866: 
1.78      anton    9867: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   9868: @subsection Structure Naming Convention
                   9869: @cindex structure naming convention
1.52      anton    9870: 
1.78      anton    9871: The field names that come to (my) mind are often quite generic, and,
                   9872: if used, would cause frequent name clashes. E.g., many structures
                   9873: probably contain a @code{counter} field. The structure names
                   9874: that come to (my) mind are often also the logical choice for the names
                   9875: of words that create such a structure.
1.52      anton    9876: 
1.78      anton    9877: Therefore, I have adopted the following naming conventions: 
1.52      anton    9878: 
1.78      anton    9879: @itemize @bullet
                   9880: @cindex field naming convention
                   9881: @item
                   9882: The names of fields are of the form
                   9883: @code{@emph{struct}-@emph{field}}, where
                   9884: @code{@emph{struct}} is the basic name of the structure, and
                   9885: @code{@emph{field}} is the basic name of the field. You can
                   9886: think of field words as converting the (address of the)
                   9887: structure into the (address of the) field.
1.52      anton    9888: 
1.78      anton    9889: @cindex structure naming convention
                   9890: @item
                   9891: The names of structures are of the form
                   9892: @code{@emph{struct}%}, where
                   9893: @code{@emph{struct}} is the basic name of the structure.
                   9894: @end itemize
1.52      anton    9895: 
1.78      anton    9896: This naming convention does not work that well for fields of extended
                   9897: structures; e.g., the integer list structure has a field
                   9898: @code{intlist-int}, but has @code{list-next}, not
                   9899: @code{intlist-next}.
1.53      anton    9900: 
1.78      anton    9901: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   9902: @subsection Structure Implementation
                   9903: @cindex structure implementation
                   9904: @cindex implementation of structures
1.52      anton    9905: 
1.78      anton    9906: The central idea in the implementation is to pass the data about the
                   9907: structure being built on the stack, not in some global
                   9908: variable. Everything else falls into place naturally once this design
                   9909: decision is made.
1.53      anton    9910: 
1.78      anton    9911: The type description on the stack is of the form @emph{align
                   9912: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   9913: very simple.
1.53      anton    9914: 
1.78      anton    9915: @code{field} is a defining word that uses @code{Create}
                   9916: and @code{DOES>}. The body of the field contains the offset
                   9917: of the field, and the normal @code{DOES>} action is simply:
1.53      anton    9918: 
                   9919: @example
1.78      anton    9920: @@ +
1.53      anton    9921: @end example
                   9922: 
1.78      anton    9923: @noindent
                   9924: i.e., add the offset to the address, giving the stack effect
                   9925: @i{addr1 -- addr2} for a field.
                   9926: 
                   9927: @cindex first field optimization, implementation
                   9928: This simple structure is slightly complicated by the optimization
                   9929: for fields with offset 0, which requires a different
                   9930: @code{DOES>}-part (because we cannot rely on there being
                   9931: something on the stack if such a field is invoked during
                   9932: compilation). Therefore, we put the different @code{DOES>}-parts
                   9933: in separate words, and decide which one to invoke based on the
                   9934: offset. For a zero offset, the field is basically a noop; it is
                   9935: immediate, and therefore no code is generated when it is compiled.
1.53      anton    9936: 
1.78      anton    9937: @node Structure Glossary,  , Structure Implementation, Structures
                   9938: @subsection Structure Glossary
                   9939: @cindex structure glossary
1.53      anton    9940: 
1.5       anton    9941: 
1.78      anton    9942: doc-%align
                   9943: doc-%alignment
                   9944: doc-%alloc
                   9945: doc-%allocate
                   9946: doc-%allot
                   9947: doc-cell%
                   9948: doc-char%
                   9949: doc-dfloat%
                   9950: doc-double%
                   9951: doc-end-struct
                   9952: doc-field
                   9953: doc-float%
                   9954: doc-naligned
                   9955: doc-sfloat%
                   9956: doc-%size
                   9957: doc-struct
1.54      anton    9958: 
                   9959: 
1.26      crook    9960: @c -------------------------------------------------------------
1.78      anton    9961: @node Object-oriented Forth, Programming Tools, Structures, Words
                   9962: @section Object-oriented Forth
                   9963: 
                   9964: Gforth comes with three packages for object-oriented programming:
                   9965: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   9966: is preloaded, so you have to @code{include} them before use. The most
                   9967: important differences between these packages (and others) are discussed
                   9968: in @ref{Comparison with other object models}. All packages are written
                   9969: in ANS Forth and can be used with any other ANS Forth.
1.5       anton    9970: 
1.78      anton    9971: @menu
                   9972: * Why object-oriented programming?::  
                   9973: * Object-Oriented Terminology::  
                   9974: * Objects::                     
                   9975: * OOF::                         
                   9976: * Mini-OOF::                    
                   9977: * Comparison with other object models::  
                   9978: @end menu
1.5       anton    9979: 
1.78      anton    9980: @c ----------------------------------------------------------------
                   9981: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   9982: @subsection Why object-oriented programming?
                   9983: @cindex object-oriented programming motivation
                   9984: @cindex motivation for object-oriented programming
1.44      crook    9985: 
1.78      anton    9986: Often we have to deal with several data structures (@emph{objects}),
                   9987: that have to be treated similarly in some respects, but differently in
                   9988: others. Graphical objects are the textbook example: circles, triangles,
                   9989: dinosaurs, icons, and others, and we may want to add more during program
                   9990: development. We want to apply some operations to any graphical object,
                   9991: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   9992: has to do something different for every kind of object.
                   9993: @comment TODO add some other operations eg perimeter, area
                   9994: @comment and tie in to concrete examples later..
1.5       anton    9995: 
1.78      anton    9996: We could implement @code{draw} as a big @code{CASE}
                   9997: control structure that executes the appropriate code depending on the
                   9998: kind of object to be drawn. This would be not be very elegant, and,
                   9999: moreover, we would have to change @code{draw} every time we add
                   10000: a new kind of graphical object (say, a spaceship).
1.44      crook    10001: 
1.78      anton    10002: What we would rather do is: When defining spaceships, we would tell
                   10003: the system: ``Here's how you @code{draw} a spaceship; you figure
                   10004: out the rest''.
1.5       anton    10005: 
1.78      anton    10006: This is the problem that all systems solve that (rightfully) call
                   10007: themselves object-oriented; the object-oriented packages presented here
                   10008: solve this problem (and not much else).
                   10009: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44      crook    10010: 
1.78      anton    10011: @c ------------------------------------------------------------------------
                   10012: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   10013: @subsection Object-Oriented Terminology
                   10014: @cindex object-oriented terminology
                   10015: @cindex terminology for object-oriented programming
1.5       anton    10016: 
1.78      anton    10017: This section is mainly for reference, so you don't have to understand
                   10018: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   10019: short:
1.44      crook    10020: 
1.78      anton    10021: @table @emph
                   10022: @cindex class
                   10023: @item class
                   10024: a data structure definition with some extras.
1.5       anton    10025: 
1.78      anton    10026: @cindex object
                   10027: @item object
                   10028: an instance of the data structure described by the class definition.
1.5       anton    10029: 
1.78      anton    10030: @cindex instance variables
                   10031: @item instance variables
                   10032: fields of the data structure.
1.5       anton    10033: 
1.78      anton    10034: @cindex selector
                   10035: @cindex method selector
                   10036: @cindex virtual function
                   10037: @item selector
                   10038: (or @emph{method selector}) a word (e.g.,
                   10039: @code{draw}) that performs an operation on a variety of data
                   10040: structures (classes). A selector describes @emph{what} operation to
                   10041: perform. In C++ terminology: a (pure) virtual function.
1.5       anton    10042: 
1.78      anton    10043: @cindex method
                   10044: @item method
                   10045: the concrete definition that performs the operation
                   10046: described by the selector for a specific class. A method specifies
                   10047: @emph{how} the operation is performed for a specific class.
1.5       anton    10048: 
1.78      anton    10049: @cindex selector invocation
                   10050: @cindex message send
                   10051: @cindex invoking a selector
                   10052: @item selector invocation
                   10053: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   10054: is used for determining which method is used. In Smalltalk terminology:
                   10055: a message (consisting of the selector and the other arguments) is sent
                   10056: to the object.
1.5       anton    10057: 
1.78      anton    10058: @cindex receiving object
                   10059: @item receiving object
                   10060: the object used for determining the method executed by a selector
                   10061: invocation. In the @file{objects.fs} model, it is the object that is on
                   10062: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   10063: the Smalltalk @emph{message} terminology.)
1.5       anton    10064: 
1.78      anton    10065: @cindex child class
                   10066: @cindex parent class
                   10067: @cindex inheritance
                   10068: @item child class
                   10069: a class that has (@emph{inherits}) all properties (instance variables,
                   10070: selectors, methods) from a @emph{parent class}. In Smalltalk
                   10071: terminology: The subclass inherits from the superclass. In C++
                   10072: terminology: The derived class inherits from the base class.
1.5       anton    10073: 
1.78      anton    10074: @end table
1.5       anton    10075: 
1.78      anton    10076: @c If you wonder about the message sending terminology, it comes from
                   10077: @c a time when each object had it's own task and objects communicated via
                   10078: @c message passing; eventually the Smalltalk developers realized that
                   10079: @c they can do most things through simple (indirect) calls. They kept the
                   10080: @c terminology.
1.5       anton    10081: 
1.78      anton    10082: @c --------------------------------------------------------------
                   10083: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   10084: @subsection The @file{objects.fs} model
                   10085: @cindex objects
                   10086: @cindex object-oriented programming
1.26      crook    10087: 
1.78      anton    10088: @cindex @file{objects.fs}
                   10089: @cindex @file{oof.fs}
1.26      crook    10090: 
1.78      anton    10091: This section describes the @file{objects.fs} package. This material also
                   10092: has been published in M. Anton Ertl,
                   10093: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
                   10094: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
                   10095: 37--43.
                   10096: @c McKewan's and Zsoter's packages
1.26      crook    10097: 
1.78      anton    10098: This section assumes that you have read @ref{Structures}.
1.5       anton    10099: 
1.78      anton    10100: The techniques on which this model is based have been used to implement
                   10101: the parser generator, Gray, and have also been used in Gforth for
                   10102: implementing the various flavours of word lists (hashed or not,
                   10103: case-sensitive or not, special-purpose word lists for locals etc.).
1.5       anton    10104: 
                   10105: 
1.26      crook    10106: @menu
1.78      anton    10107: * Properties of the Objects model::  
                   10108: * Basic Objects Usage::         
                   10109: * The Objects base class::      
                   10110: * Creating objects::            
                   10111: * Object-Oriented Programming Style::  
                   10112: * Class Binding::               
                   10113: * Method conveniences::         
                   10114: * Classes and Scoping::         
                   10115: * Dividing classes::            
                   10116: * Object Interfaces::           
                   10117: * Objects Implementation::      
                   10118: * Objects Glossary::            
1.26      crook    10119: @end menu
1.5       anton    10120: 
1.78      anton    10121: Marcel Hendrix provided helpful comments on this section.
1.5       anton    10122: 
1.78      anton    10123: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   10124: @subsubsection Properties of the @file{objects.fs} model
                   10125: @cindex @file{objects.fs} properties
1.5       anton    10126: 
1.78      anton    10127: @itemize @bullet
                   10128: @item
                   10129: It is straightforward to pass objects on the stack. Passing
                   10130: selectors on the stack is a little less convenient, but possible.
1.44      crook    10131: 
1.78      anton    10132: @item
                   10133: Objects are just data structures in memory, and are referenced by their
                   10134: address. You can create words for objects with normal defining words
                   10135: like @code{constant}. Likewise, there is no difference between instance
                   10136: variables that contain objects and those that contain other data.
1.5       anton    10137: 
1.78      anton    10138: @item
                   10139: Late binding is efficient and easy to use.
1.44      crook    10140: 
1.78      anton    10141: @item
                   10142: It avoids parsing, and thus avoids problems with state-smartness
                   10143: and reduced extensibility; for convenience there are a few parsing
                   10144: words, but they have non-parsing counterparts. There are also a few
                   10145: defining words that parse. This is hard to avoid, because all standard
                   10146: defining words parse (except @code{:noname}); however, such
                   10147: words are not as bad as many other parsing words, because they are not
                   10148: state-smart.
1.5       anton    10149: 
1.78      anton    10150: @item
                   10151: It does not try to incorporate everything. It does a few things and does
                   10152: them well (IMO). In particular, this model was not designed to support
                   10153: information hiding (although it has features that may help); you can use
                   10154: a separate package for achieving this.
1.5       anton    10155: 
1.78      anton    10156: @item
                   10157: It is layered; you don't have to learn and use all features to use this
                   10158: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   10159: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
                   10160: are optional and independent of each other.
1.5       anton    10161: 
1.78      anton    10162: @item
                   10163: An implementation in ANS Forth is available.
1.5       anton    10164: 
1.78      anton    10165: @end itemize
1.5       anton    10166: 
1.44      crook    10167: 
1.78      anton    10168: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   10169: @subsubsection Basic @file{objects.fs} Usage
                   10170: @cindex basic objects usage
                   10171: @cindex objects, basic usage
1.5       anton    10172: 
1.78      anton    10173: You can define a class for graphical objects like this:
1.44      crook    10174: 
1.78      anton    10175: @cindex @code{class} usage
                   10176: @cindex @code{end-class} usage
                   10177: @cindex @code{selector} usage
1.5       anton    10178: @example
1.78      anton    10179: object class \ "object" is the parent class
                   10180:   selector draw ( x y graphical -- )
                   10181: end-class graphical
                   10182: @end example
                   10183: 
                   10184: This code defines a class @code{graphical} with an
                   10185: operation @code{draw}.  We can perform the operation
                   10186: @code{draw} on any @code{graphical} object, e.g.:
                   10187: 
                   10188: @example
                   10189: 100 100 t-rex draw
1.26      crook    10190: @end example
1.5       anton    10191: 
1.78      anton    10192: @noindent
                   10193: where @code{t-rex} is a word (say, a constant) that produces a
                   10194: graphical object.
                   10195: 
                   10196: @comment TODO add a 2nd operation eg perimeter.. and use for
                   10197: @comment a concrete example
1.5       anton    10198: 
1.78      anton    10199: @cindex abstract class
                   10200: How do we create a graphical object? With the present definitions,
                   10201: we cannot create a useful graphical object. The class
                   10202: @code{graphical} describes graphical objects in general, but not
                   10203: any concrete graphical object type (C++ users would call it an
                   10204: @emph{abstract class}); e.g., there is no method for the selector
                   10205: @code{draw} in the class @code{graphical}.
1.5       anton    10206: 
1.78      anton    10207: For concrete graphical objects, we define child classes of the
                   10208: class @code{graphical}, e.g.:
1.5       anton    10209: 
1.78      anton    10210: @cindex @code{overrides} usage
                   10211: @cindex @code{field} usage in class definition
1.26      crook    10212: @example
1.78      anton    10213: graphical class \ "graphical" is the parent class
                   10214:   cell% field circle-radius
1.5       anton    10215: 
1.78      anton    10216: :noname ( x y circle -- )
                   10217:   circle-radius @@ draw-circle ;
                   10218: overrides draw
1.5       anton    10219: 
1.78      anton    10220: :noname ( n-radius circle -- )
                   10221:   circle-radius ! ;
                   10222: overrides construct
1.5       anton    10223: 
1.78      anton    10224: end-class circle
                   10225: @end example
1.44      crook    10226: 
1.78      anton    10227: Here we define a class @code{circle} as a child of @code{graphical},
                   10228: with field @code{circle-radius} (which behaves just like a field
                   10229: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   10230: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   10231: defined in @code{object}, the parent class of @code{graphical}).
1.5       anton    10232: 
1.78      anton    10233: Now we can create a circle on the heap (i.e.,
                   10234: @code{allocate}d memory) with:
1.44      crook    10235: 
1.78      anton    10236: @cindex @code{heap-new} usage
1.5       anton    10237: @example
1.78      anton    10238: 50 circle heap-new constant my-circle
1.5       anton    10239: @end example
                   10240: 
1.78      anton    10241: @noindent
                   10242: @code{heap-new} invokes @code{construct}, thus
                   10243: initializing the field @code{circle-radius} with 50. We can draw
                   10244: this new circle at (100,100) with:
1.5       anton    10245: 
                   10246: @example
1.78      anton    10247: 100 100 my-circle draw
1.5       anton    10248: @end example
                   10249: 
1.78      anton    10250: @cindex selector invocation, restrictions
                   10251: @cindex class definition, restrictions
                   10252: Note: You can only invoke a selector if the object on the TOS
                   10253: (the receiving object) belongs to the class where the selector was
                   10254: defined or one of its descendents; e.g., you can invoke
                   10255: @code{draw} only for objects belonging to @code{graphical}
                   10256: or its descendents (e.g., @code{circle}).  Immediately before
                   10257: @code{end-class}, the search order has to be the same as
                   10258: immediately after @code{class}.
                   10259: 
                   10260: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   10261: @subsubsection The @file{object.fs} base class
                   10262: @cindex @code{object} class
                   10263: 
                   10264: When you define a class, you have to specify a parent class.  So how do
                   10265: you start defining classes? There is one class available from the start:
                   10266: @code{object}. It is ancestor for all classes and so is the
                   10267: only class that has no parent. It has two selectors: @code{construct}
                   10268: and @code{print}.
                   10269: 
                   10270: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   10271: @subsubsection Creating objects
                   10272: @cindex creating objects
                   10273: @cindex object creation
                   10274: @cindex object allocation options
                   10275: 
                   10276: @cindex @code{heap-new} discussion
                   10277: @cindex @code{dict-new} discussion
                   10278: @cindex @code{construct} discussion
                   10279: You can create and initialize an object of a class on the heap with
                   10280: @code{heap-new} ( ... class -- object ) and in the dictionary
                   10281: (allocation with @code{allot}) with @code{dict-new} (
                   10282: ... class -- object ). Both words invoke @code{construct}, which
                   10283: consumes the stack items indicated by "..." above.
                   10284: 
                   10285: @cindex @code{init-object} discussion
                   10286: @cindex @code{class-inst-size} discussion
                   10287: If you want to allocate memory for an object yourself, you can get its
                   10288: alignment and size with @code{class-inst-size 2@@} ( class --
                   10289: align size ). Once you have memory for an object, you can initialize
                   10290: it with @code{init-object} ( ... class object -- );
                   10291: @code{construct} does only a part of the necessary work.
                   10292: 
                   10293: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   10294: @subsubsection Object-Oriented Programming Style
                   10295: @cindex object-oriented programming style
                   10296: @cindex programming style, object-oriented
1.5       anton    10297: 
1.78      anton    10298: This section is not exhaustive.
1.5       anton    10299: 
1.78      anton    10300: @cindex stack effects of selectors
                   10301: @cindex selectors and stack effects
                   10302: In general, it is a good idea to ensure that all methods for the
                   10303: same selector have the same stack effect: when you invoke a selector,
                   10304: you often have no idea which method will be invoked, so, unless all
                   10305: methods have the same stack effect, you will not know the stack effect
                   10306: of the selector invocation.
1.5       anton    10307: 
1.78      anton    10308: One exception to this rule is methods for the selector
                   10309: @code{construct}. We know which method is invoked, because we
                   10310: specify the class to be constructed at the same place. Actually, I
                   10311: defined @code{construct} as a selector only to give the users a
                   10312: convenient way to specify initialization. The way it is used, a
                   10313: mechanism different from selector invocation would be more natural
                   10314: (but probably would take more code and more space to explain).
1.5       anton    10315: 
1.78      anton    10316: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   10317: @subsubsection Class Binding
                   10318: @cindex class binding
                   10319: @cindex early binding
1.5       anton    10320: 
1.78      anton    10321: @cindex late binding
                   10322: Normal selector invocations determine the method at run-time depending
                   10323: on the class of the receiving object. This run-time selection is called
                   10324: @i{late binding}.
1.5       anton    10325: 
1.78      anton    10326: Sometimes it's preferable to invoke a different method. For example,
                   10327: you might want to use the simple method for @code{print}ing
                   10328: @code{object}s instead of the possibly long-winded @code{print} method
                   10329: of the receiver class. You can achieve this by replacing the invocation
                   10330: of @code{print} with:
1.5       anton    10331: 
1.78      anton    10332: @cindex @code{[bind]} usage
1.5       anton    10333: @example
1.78      anton    10334: [bind] object print
1.5       anton    10335: @end example
                   10336: 
1.78      anton    10337: @noindent
                   10338: in compiled code or:
                   10339: 
                   10340: @cindex @code{bind} usage
1.5       anton    10341: @example
1.78      anton    10342: bind object print
1.5       anton    10343: @end example
                   10344: 
1.78      anton    10345: @cindex class binding, alternative to
                   10346: @noindent
                   10347: in interpreted code. Alternatively, you can define the method with a
                   10348: name (e.g., @code{print-object}), and then invoke it through the
                   10349: name. Class binding is just a (often more convenient) way to achieve
                   10350: the same effect; it avoids name clutter and allows you to invoke
                   10351: methods directly without naming them first.
1.5       anton    10352: 
1.78      anton    10353: @cindex superclass binding
                   10354: @cindex parent class binding
                   10355: A frequent use of class binding is this: When we define a method
                   10356: for a selector, we often want the method to do what the selector does
                   10357: in the parent class, and a little more. There is a special word for
                   10358: this purpose: @code{[parent]}; @code{[parent]
                   10359: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   10360: selector}}, where @code{@emph{parent}} is the parent
                   10361: class of the current class. E.g., a method definition might look like:
1.44      crook    10362: 
1.78      anton    10363: @cindex @code{[parent]} usage
                   10364: @example
                   10365: :noname
                   10366:   dup [parent] foo \ do parent's foo on the receiving object
                   10367:   ... \ do some more
                   10368: ; overrides foo
                   10369: @end example
1.6       pazsan   10370: 
1.78      anton    10371: @cindex class binding as optimization
                   10372: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10373: March 1997), Andrew McKewan presents class binding as an optimization
                   10374: technique. I recommend not using it for this purpose unless you are in
                   10375: an emergency. Late binding is pretty fast with this model anyway, so the
                   10376: benefit of using class binding is small; the cost of using class binding
                   10377: where it is not appropriate is reduced maintainability.
1.44      crook    10378: 
1.78      anton    10379: While we are at programming style questions: You should bind
                   10380: selectors only to ancestor classes of the receiving object. E.g., say,
                   10381: you know that the receiving object is of class @code{foo} or its
                   10382: descendents; then you should bind only to @code{foo} and its
                   10383: ancestors.
1.12      anton    10384: 
1.78      anton    10385: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10386: @subsubsection Method conveniences
                   10387: @cindex method conveniences
1.44      crook    10388: 
1.78      anton    10389: In a method you usually access the receiving object pretty often.  If
                   10390: you define the method as a plain colon definition (e.g., with
                   10391: @code{:noname}), you may have to do a lot of stack
                   10392: gymnastics. To avoid this, you can define the method with @code{m:
                   10393: ... ;m}. E.g., you could define the method for
                   10394: @code{draw}ing a @code{circle} with
1.6       pazsan   10395: 
1.78      anton    10396: @cindex @code{this} usage
                   10397: @cindex @code{m:} usage
                   10398: @cindex @code{;m} usage
                   10399: @example
                   10400: m: ( x y circle -- )
                   10401:   ( x y ) this circle-radius @@ draw-circle ;m
                   10402: @end example
1.6       pazsan   10403: 
1.78      anton    10404: @cindex @code{exit} in @code{m: ... ;m}
                   10405: @cindex @code{exitm} discussion
                   10406: @cindex @code{catch} in @code{m: ... ;m}
                   10407: When this method is executed, the receiver object is removed from the
                   10408: stack; you can access it with @code{this} (admittedly, in this
                   10409: example the use of @code{m: ... ;m} offers no advantage). Note
                   10410: that I specify the stack effect for the whole method (i.e. including
                   10411: the receiver object), not just for the code between @code{m:}
                   10412: and @code{;m}. You cannot use @code{exit} in
                   10413: @code{m:...;m}; instead, use
                   10414: @code{exitm}.@footnote{Moreover, for any word that calls
                   10415: @code{catch} and was defined before loading
                   10416: @code{objects.fs}, you have to redefine it like I redefined
                   10417: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12      anton    10418: 
1.78      anton    10419: @cindex @code{inst-var} usage
                   10420: You will frequently use sequences of the form @code{this
                   10421: @emph{field}} (in the example above: @code{this
                   10422: circle-radius}). If you use the field only in this way, you can
                   10423: define it with @code{inst-var} and eliminate the
                   10424: @code{this} before the field name. E.g., the @code{circle}
                   10425: class above could also be defined with:
1.6       pazsan   10426: 
1.78      anton    10427: @example
                   10428: graphical class
                   10429:   cell% inst-var radius
1.6       pazsan   10430: 
1.78      anton    10431: m: ( x y circle -- )
                   10432:   radius @@ draw-circle ;m
                   10433: overrides draw
1.6       pazsan   10434: 
1.78      anton    10435: m: ( n-radius circle -- )
                   10436:   radius ! ;m
                   10437: overrides construct
1.6       pazsan   10438: 
1.78      anton    10439: end-class circle
                   10440: @end example
1.6       pazsan   10441: 
1.78      anton    10442: @code{radius} can only be used in @code{circle} and its
                   10443: descendent classes and inside @code{m:...;m}.
1.6       pazsan   10444: 
1.78      anton    10445: @cindex @code{inst-value} usage
                   10446: You can also define fields with @code{inst-value}, which is
                   10447: to @code{inst-var} what @code{value} is to
                   10448: @code{variable}.  You can change the value of such a field with
                   10449: @code{[to-inst]}.  E.g., we could also define the class
                   10450: @code{circle} like this:
1.44      crook    10451: 
1.78      anton    10452: @example
                   10453: graphical class
                   10454:   inst-value radius
1.6       pazsan   10455: 
1.78      anton    10456: m: ( x y circle -- )
                   10457:   radius draw-circle ;m
                   10458: overrides draw
1.44      crook    10459: 
1.78      anton    10460: m: ( n-radius circle -- )
                   10461:   [to-inst] radius ;m
                   10462: overrides construct
1.6       pazsan   10463: 
1.78      anton    10464: end-class circle
                   10465: @end example
1.6       pazsan   10466: 
1.78      anton    10467: @c !! :m is easy to confuse with m:.  Another name would be better.
1.6       pazsan   10468: 
1.78      anton    10469: @c Finally, you can define named methods with @code{:m}.  One use of this
                   10470: @c feature is the definition of words that occur only in one class and are
                   10471: @c not intended to be overridden, but which still need method context
                   10472: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   10473: @c would be bound frequently, if defined anonymously.
1.6       pazsan   10474: 
                   10475: 
1.78      anton    10476: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
                   10477: @subsubsection Classes and Scoping
                   10478: @cindex classes and scoping
                   10479: @cindex scoping and classes
1.6       pazsan   10480: 
1.78      anton    10481: Inheritance is frequent, unlike structure extension. This exacerbates
                   10482: the problem with the field name convention (@pxref{Structure Naming
                   10483: Convention}): One always has to remember in which class the field was
                   10484: originally defined; changing a part of the class structure would require
                   10485: changes for renaming in otherwise unaffected code.
1.6       pazsan   10486: 
1.78      anton    10487: @cindex @code{inst-var} visibility
                   10488: @cindex @code{inst-value} visibility
                   10489: To solve this problem, I added a scoping mechanism (which was not in my
                   10490: original charter): A field defined with @code{inst-var} (or
                   10491: @code{inst-value}) is visible only in the class where it is defined and in
                   10492: the descendent classes of this class.  Using such fields only makes
                   10493: sense in @code{m:}-defined methods in these classes anyway.
1.6       pazsan   10494: 
1.78      anton    10495: This scoping mechanism allows us to use the unadorned field name,
                   10496: because name clashes with unrelated words become much less likely.
1.6       pazsan   10497: 
1.78      anton    10498: @cindex @code{protected} discussion
                   10499: @cindex @code{private} discussion
                   10500: Once we have this mechanism, we can also use it for controlling the
                   10501: visibility of other words: All words defined after
                   10502: @code{protected} are visible only in the current class and its
                   10503: descendents. @code{public} restores the compilation
                   10504: (i.e. @code{current}) word list that was in effect before. If you
                   10505: have several @code{protected}s without an intervening
                   10506: @code{public} or @code{set-current}, @code{public}
                   10507: will restore the compilation word list in effect before the first of
                   10508: these @code{protected}s.
1.6       pazsan   10509: 
1.78      anton    10510: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   10511: @subsubsection Dividing classes
                   10512: @cindex Dividing classes
                   10513: @cindex @code{methods}...@code{end-methods}
1.6       pazsan   10514: 
1.78      anton    10515: You may want to do the definition of methods separate from the
                   10516: definition of the class, its selectors, fields, and instance variables,
                   10517: i.e., separate the implementation from the definition.  You can do this
                   10518: in the following way:
1.6       pazsan   10519: 
1.78      anton    10520: @example
                   10521: graphical class
                   10522:   inst-value radius
                   10523: end-class circle
1.6       pazsan   10524: 
1.78      anton    10525: ... \ do some other stuff
1.6       pazsan   10526: 
1.78      anton    10527: circle methods \ now we are ready
1.44      crook    10528: 
1.78      anton    10529: m: ( x y circle -- )
                   10530:   radius draw-circle ;m
                   10531: overrides draw
1.6       pazsan   10532: 
1.78      anton    10533: m: ( n-radius circle -- )
                   10534:   [to-inst] radius ;m
                   10535: overrides construct
1.44      crook    10536: 
1.78      anton    10537: end-methods
                   10538: @end example
1.7       pazsan   10539: 
1.78      anton    10540: You can use several @code{methods}...@code{end-methods} sections.  The
                   10541: only things you can do to the class in these sections are: defining
                   10542: methods, and overriding the class's selectors.  You must not define new
                   10543: selectors or fields.
1.7       pazsan   10544: 
1.78      anton    10545: Note that you often have to override a selector before using it.  In
                   10546: particular, you usually have to override @code{construct} with a new
                   10547: method before you can invoke @code{heap-new} and friends.  E.g., you
                   10548: must not create a circle before the @code{overrides construct} sequence
                   10549: in the example above.
1.7       pazsan   10550: 
1.78      anton    10551: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
                   10552: @subsubsection Object Interfaces
                   10553: @cindex object interfaces
                   10554: @cindex interfaces for objects
1.7       pazsan   10555: 
1.78      anton    10556: In this model you can only call selectors defined in the class of the
                   10557: receiving objects or in one of its ancestors. If you call a selector
                   10558: with a receiving object that is not in one of these classes, the
                   10559: result is undefined; if you are lucky, the program crashes
                   10560: immediately.
1.7       pazsan   10561: 
1.78      anton    10562: @cindex selectors common to hardly-related classes
                   10563: Now consider the case when you want to have a selector (or several)
                   10564: available in two classes: You would have to add the selector to a
                   10565: common ancestor class, in the worst case to @code{object}. You
                   10566: may not want to do this, e.g., because someone else is responsible for
                   10567: this ancestor class.
1.7       pazsan   10568: 
1.78      anton    10569: The solution for this problem is interfaces. An interface is a
                   10570: collection of selectors. If a class implements an interface, the
                   10571: selectors become available to the class and its descendents. A class
                   10572: can implement an unlimited number of interfaces. For the problem
                   10573: discussed above, we would define an interface for the selector(s), and
                   10574: both classes would implement the interface.
1.7       pazsan   10575: 
1.78      anton    10576: As an example, consider an interface @code{storage} for
                   10577: writing objects to disk and getting them back, and a class
                   10578: @code{foo} that implements it. The code would look like this:
1.7       pazsan   10579: 
1.78      anton    10580: @cindex @code{interface} usage
                   10581: @cindex @code{end-interface} usage
                   10582: @cindex @code{implementation} usage
                   10583: @example
                   10584: interface
                   10585:   selector write ( file object -- )
                   10586:   selector read1 ( file object -- )
                   10587: end-interface storage
1.13      pazsan   10588: 
1.78      anton    10589: bar class
                   10590:   storage implementation
1.13      pazsan   10591: 
1.78      anton    10592: ... overrides write
                   10593: ... overrides read1
                   10594: ...
                   10595: end-class foo
                   10596: @end example
1.13      pazsan   10597: 
1.78      anton    10598: @noindent
                   10599: (I would add a word @code{read} @i{( file -- object )} that uses
                   10600: @code{read1} internally, but that's beyond the point illustrated
                   10601: here.)
1.13      pazsan   10602: 
1.78      anton    10603: Note that you cannot use @code{protected} in an interface; and
                   10604: of course you cannot define fields.
1.13      pazsan   10605: 
1.78      anton    10606: In the Neon model, all selectors are available for all classes;
                   10607: therefore it does not need interfaces. The price you pay in this model
                   10608: is slower late binding, and therefore, added complexity to avoid late
                   10609: binding.
1.13      pazsan   10610: 
1.78      anton    10611: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   10612: @subsubsection @file{objects.fs} Implementation
                   10613: @cindex @file{objects.fs} implementation
1.13      pazsan   10614: 
1.78      anton    10615: @cindex @code{object-map} discussion
                   10616: An object is a piece of memory, like one of the data structures
                   10617: described with @code{struct...end-struct}. It has a field
                   10618: @code{object-map} that points to the method map for the object's
                   10619: class.
1.13      pazsan   10620: 
1.78      anton    10621: @cindex method map
                   10622: @cindex virtual function table
                   10623: The @emph{method map}@footnote{This is Self terminology; in C++
                   10624: terminology: virtual function table.} is an array that contains the
                   10625: execution tokens (@i{xt}s) of the methods for the object's class. Each
                   10626: selector contains an offset into a method map.
1.13      pazsan   10627: 
1.78      anton    10628: @cindex @code{selector} implementation, class
                   10629: @code{selector} is a defining word that uses
                   10630: @code{CREATE} and @code{DOES>}. The body of the
                   10631: selector contains the offset; the @code{DOES>} action for a
                   10632: class selector is, basically:
1.8       pazsan   10633: 
                   10634: @example
1.78      anton    10635: ( object addr ) @@ over object-map @@ + @@ execute
1.13      pazsan   10636: @end example
                   10637: 
1.78      anton    10638: Since @code{object-map} is the first field of the object, it
                   10639: does not generate any code. As you can see, calling a selector has a
                   10640: small, constant cost.
1.26      crook    10641: 
1.78      anton    10642: @cindex @code{current-interface} discussion
                   10643: @cindex class implementation and representation
                   10644: A class is basically a @code{struct} combined with a method
                   10645: map. During the class definition the alignment and size of the class
                   10646: are passed on the stack, just as with @code{struct}s, so
                   10647: @code{field} can also be used for defining class
                   10648: fields. However, passing more items on the stack would be
                   10649: inconvenient, so @code{class} builds a data structure in memory,
                   10650: which is accessed through the variable
                   10651: @code{current-interface}. After its definition is complete, the
                   10652: class is represented on the stack by a pointer (e.g., as parameter for
                   10653: a child class definition).
1.26      crook    10654: 
1.78      anton    10655: A new class starts off with the alignment and size of its parent,
                   10656: and a copy of the parent's method map. Defining new fields extends the
                   10657: size and alignment; likewise, defining new selectors extends the
                   10658: method map. @code{overrides} just stores a new @i{xt} in the method
                   10659: map at the offset given by the selector.
1.13      pazsan   10660: 
1.78      anton    10661: @cindex class binding, implementation
                   10662: Class binding just gets the @i{xt} at the offset given by the selector
                   10663: from the class's method map and @code{compile,}s (in the case of
                   10664: @code{[bind]}) it.
1.13      pazsan   10665: 
1.78      anton    10666: @cindex @code{this} implementation
                   10667: @cindex @code{catch} and @code{this}
                   10668: @cindex @code{this} and @code{catch}
                   10669: I implemented @code{this} as a @code{value}. At the
                   10670: start of an @code{m:...;m} method the old @code{this} is
                   10671: stored to the return stack and restored at the end; and the object on
                   10672: the TOS is stored @code{TO this}. This technique has one
                   10673: disadvantage: If the user does not leave the method via
                   10674: @code{;m}, but via @code{throw} or @code{exit},
                   10675: @code{this} is not restored (and @code{exit} may
                   10676: crash). To deal with the @code{throw} problem, I have redefined
                   10677: @code{catch} to save and restore @code{this}; the same
                   10678: should be done with any word that can catch an exception. As for
                   10679: @code{exit}, I simply forbid it (as a replacement, there is
                   10680: @code{exitm}).
1.13      pazsan   10681: 
1.78      anton    10682: @cindex @code{inst-var} implementation
                   10683: @code{inst-var} is just the same as @code{field}, with
                   10684: a different @code{DOES>} action:
1.13      pazsan   10685: @example
1.78      anton    10686: @@ this +
1.8       pazsan   10687: @end example
1.78      anton    10688: Similar for @code{inst-value}.
1.8       pazsan   10689: 
1.78      anton    10690: @cindex class scoping implementation
                   10691: Each class also has a word list that contains the words defined with
                   10692: @code{inst-var} and @code{inst-value}, and its protected
                   10693: words. It also has a pointer to its parent. @code{class} pushes
                   10694: the word lists of the class and all its ancestors onto the search order stack,
                   10695: and @code{end-class} drops them.
1.20      pazsan   10696: 
1.78      anton    10697: @cindex interface implementation
                   10698: An interface is like a class without fields, parent and protected
                   10699: words; i.e., it just has a method map. If a class implements an
                   10700: interface, its method map contains a pointer to the method map of the
                   10701: interface. The positive offsets in the map are reserved for class
                   10702: methods, therefore interface map pointers have negative
                   10703: offsets. Interfaces have offsets that are unique throughout the
                   10704: system, unlike class selectors, whose offsets are only unique for the
                   10705: classes where the selector is available (invokable).
1.20      pazsan   10706: 
1.78      anton    10707: This structure means that interface selectors have to perform one
                   10708: indirection more than class selectors to find their method. Their body
                   10709: contains the interface map pointer offset in the class method map, and
                   10710: the method offset in the interface method map. The
                   10711: @code{does>} action for an interface selector is, basically:
1.20      pazsan   10712: 
                   10713: @example
1.78      anton    10714: ( object selector-body )
                   10715: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   10716: swap object-map @@ + @@ ( object selector-body map )
                   10717: swap selector-offset @@ + @@ execute
1.20      pazsan   10718: @end example
                   10719: 
1.78      anton    10720: where @code{object-map} and @code{selector-offset} are
                   10721: first fields and generate no code.
1.20      pazsan   10722: 
1.78      anton    10723: As a concrete example, consider the following code:
1.20      pazsan   10724: 
                   10725: @example
1.78      anton    10726: interface
                   10727:   selector if1sel1
                   10728:   selector if1sel2
                   10729: end-interface if1
1.20      pazsan   10730: 
1.78      anton    10731: object class
                   10732:   if1 implementation
                   10733:   selector cl1sel1
                   10734:   cell% inst-var cl1iv1
1.20      pazsan   10735: 
1.78      anton    10736: ' m1 overrides construct
                   10737: ' m2 overrides if1sel1
                   10738: ' m3 overrides if1sel2
                   10739: ' m4 overrides cl1sel2
                   10740: end-class cl1
1.20      pazsan   10741: 
1.78      anton    10742: create obj1 object dict-new drop
                   10743: create obj2 cl1    dict-new drop
                   10744: @end example
1.20      pazsan   10745: 
1.78      anton    10746: The data structure created by this code (including the data structure
                   10747: for @code{object}) is shown in the
                   10748: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
                   10749: @comment TODO add this diagram..
1.20      pazsan   10750: 
1.78      anton    10751: @node Objects Glossary,  , Objects Implementation, Objects
                   10752: @subsubsection @file{objects.fs} Glossary
                   10753: @cindex @file{objects.fs} Glossary
1.20      pazsan   10754: 
                   10755: 
1.78      anton    10756: doc---objects-bind
                   10757: doc---objects-<bind>
                   10758: doc---objects-bind'
                   10759: doc---objects-[bind]
                   10760: doc---objects-class
                   10761: doc---objects-class->map
                   10762: doc---objects-class-inst-size
                   10763: doc---objects-class-override!
1.79      anton    10764: doc---objects-class-previous
                   10765: doc---objects-class>order
1.78      anton    10766: doc---objects-construct
                   10767: doc---objects-current'
                   10768: doc---objects-[current]
                   10769: doc---objects-current-interface
                   10770: doc---objects-dict-new
                   10771: doc---objects-end-class
                   10772: doc---objects-end-class-noname
                   10773: doc---objects-end-interface
                   10774: doc---objects-end-interface-noname
                   10775: doc---objects-end-methods
                   10776: doc---objects-exitm
                   10777: doc---objects-heap-new
                   10778: doc---objects-implementation
                   10779: doc---objects-init-object
                   10780: doc---objects-inst-value
                   10781: doc---objects-inst-var
                   10782: doc---objects-interface
                   10783: doc---objects-m:
                   10784: doc---objects-:m
                   10785: doc---objects-;m
                   10786: doc---objects-method
                   10787: doc---objects-methods
                   10788: doc---objects-object
                   10789: doc---objects-overrides
                   10790: doc---objects-[parent]
                   10791: doc---objects-print
                   10792: doc---objects-protected
                   10793: doc---objects-public
                   10794: doc---objects-selector
                   10795: doc---objects-this
                   10796: doc---objects-<to-inst>
                   10797: doc---objects-[to-inst]
                   10798: doc---objects-to-this
                   10799: doc---objects-xt-new
1.20      pazsan   10800: 
                   10801: 
1.78      anton    10802: @c -------------------------------------------------------------
                   10803: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   10804: @subsection The @file{oof.fs} model
                   10805: @cindex oof
                   10806: @cindex object-oriented programming
1.20      pazsan   10807: 
1.78      anton    10808: @cindex @file{objects.fs}
                   10809: @cindex @file{oof.fs}
1.20      pazsan   10810: 
1.78      anton    10811: This section describes the @file{oof.fs} package.
1.20      pazsan   10812: 
1.78      anton    10813: The package described in this section has been used in bigFORTH since 1991, and
                   10814: used for two large applications: a chromatographic system used to
                   10815: create new medicaments, and a graphic user interface library (MINOS).
1.20      pazsan   10816: 
1.78      anton    10817: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   10818: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   10819: 10(2), 1994.
1.20      pazsan   10820: 
1.78      anton    10821: @menu
                   10822: * Properties of the OOF model::  
                   10823: * Basic OOF Usage::             
                   10824: * The OOF base class::          
                   10825: * Class Declaration::           
                   10826: * Class Implementation::        
                   10827: @end menu
1.20      pazsan   10828: 
1.78      anton    10829: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   10830: @subsubsection Properties of the @file{oof.fs} model
                   10831: @cindex @file{oof.fs} properties
1.20      pazsan   10832: 
1.78      anton    10833: @itemize @bullet
                   10834: @item
                   10835: This model combines object oriented programming with information
                   10836: hiding. It helps you writing large application, where scoping is
                   10837: necessary, because it provides class-oriented scoping.
1.20      pazsan   10838: 
1.78      anton    10839: @item
                   10840: Named objects, object pointers, and object arrays can be created,
                   10841: selector invocation uses the ``object selector'' syntax. Selector invocation
                   10842: to objects and/or selectors on the stack is a bit less convenient, but
                   10843: possible.
1.44      crook    10844: 
1.78      anton    10845: @item
                   10846: Selector invocation and instance variable usage of the active object is
                   10847: straightforward, since both make use of the active object.
1.44      crook    10848: 
1.78      anton    10849: @item
                   10850: Late binding is efficient and easy to use.
1.20      pazsan   10851: 
1.78      anton    10852: @item
                   10853: State-smart objects parse selectors. However, extensibility is provided
                   10854: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20      pazsan   10855: 
1.78      anton    10856: @item
                   10857: An implementation in ANS Forth is available.
1.20      pazsan   10858: 
1.78      anton    10859: @end itemize
1.23      crook    10860: 
                   10861: 
1.78      anton    10862: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   10863: @subsubsection Basic @file{oof.fs} Usage
                   10864: @cindex @file{oof.fs} usage
1.23      crook    10865: 
1.78      anton    10866: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23      crook    10867: 
1.78      anton    10868: You can define a class for graphical objects like this:
1.23      crook    10869: 
1.78      anton    10870: @cindex @code{class} usage
                   10871: @cindex @code{class;} usage
                   10872: @cindex @code{method} usage
                   10873: @example
                   10874: object class graphical \ "object" is the parent class
                   10875:   method draw ( x y graphical -- )
                   10876: class;
                   10877: @end example
1.23      crook    10878: 
1.78      anton    10879: This code defines a class @code{graphical} with an
                   10880: operation @code{draw}.  We can perform the operation
                   10881: @code{draw} on any @code{graphical} object, e.g.:
1.23      crook    10882: 
1.78      anton    10883: @example
                   10884: 100 100 t-rex draw
                   10885: @end example
1.23      crook    10886: 
1.78      anton    10887: @noindent
                   10888: where @code{t-rex} is an object or object pointer, created with e.g.
                   10889: @code{graphical : t-rex}.
1.23      crook    10890: 
1.78      anton    10891: @cindex abstract class
                   10892: How do we create a graphical object? With the present definitions,
                   10893: we cannot create a useful graphical object. The class
                   10894: @code{graphical} describes graphical objects in general, but not
                   10895: any concrete graphical object type (C++ users would call it an
                   10896: @emph{abstract class}); e.g., there is no method for the selector
                   10897: @code{draw} in the class @code{graphical}.
1.23      crook    10898: 
1.78      anton    10899: For concrete graphical objects, we define child classes of the
                   10900: class @code{graphical}, e.g.:
1.23      crook    10901: 
1.78      anton    10902: @example
                   10903: graphical class circle \ "graphical" is the parent class
                   10904:   cell var circle-radius
                   10905: how:
                   10906:   : draw ( x y -- )
                   10907:     circle-radius @@ draw-circle ;
1.23      crook    10908: 
1.78      anton    10909:   : init ( n-radius -- (
                   10910:     circle-radius ! ;
                   10911: class;
                   10912: @end example
1.1       anton    10913: 
1.78      anton    10914: Here we define a class @code{circle} as a child of @code{graphical},
                   10915: with a field @code{circle-radius}; it defines new methods for the
                   10916: selectors @code{draw} and @code{init} (@code{init} is defined in
                   10917: @code{object}, the parent class of @code{graphical}).
1.1       anton    10918: 
1.78      anton    10919: Now we can create a circle in the dictionary with:
1.1       anton    10920: 
1.78      anton    10921: @example
                   10922: 50 circle : my-circle
                   10923: @end example
1.21      crook    10924: 
1.78      anton    10925: @noindent
                   10926: @code{:} invokes @code{init}, thus initializing the field
                   10927: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   10928: with:
1.1       anton    10929: 
1.78      anton    10930: @example
                   10931: 100 100 my-circle draw
                   10932: @end example
1.1       anton    10933: 
1.78      anton    10934: @cindex selector invocation, restrictions
                   10935: @cindex class definition, restrictions
                   10936: Note: You can only invoke a selector if the receiving object belongs to
                   10937: the class where the selector was defined or one of its descendents;
                   10938: e.g., you can invoke @code{draw} only for objects belonging to
                   10939: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   10940: mechanism will check if you try to invoke a selector that is not
                   10941: defined in this class hierarchy, so you'll get an error at compilation
                   10942: time.
1.1       anton    10943: 
                   10944: 
1.78      anton    10945: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   10946: @subsubsection The @file{oof.fs} base class
                   10947: @cindex @file{oof.fs} base class
1.1       anton    10948: 
1.78      anton    10949: When you define a class, you have to specify a parent class.  So how do
                   10950: you start defining classes? There is one class available from the start:
                   10951: @code{object}. You have to use it as ancestor for all classes. It is the
                   10952: only class that has no parent. Classes are also objects, except that
                   10953: they don't have instance variables; class manipulation such as
                   10954: inheritance or changing definitions of a class is handled through
                   10955: selectors of the class @code{object}.
1.1       anton    10956: 
1.78      anton    10957: @code{object} provides a number of selectors:
1.1       anton    10958: 
1.78      anton    10959: @itemize @bullet
                   10960: @item
                   10961: @code{class} for subclassing, @code{definitions} to add definitions
                   10962: later on, and @code{class?} to get type informations (is the class a
                   10963: subclass of the class passed on the stack?).
1.1       anton    10964: 
1.78      anton    10965: doc---object-class
                   10966: doc---object-definitions
                   10967: doc---object-class?
1.1       anton    10968: 
                   10969: 
1.26      crook    10970: @item
1.78      anton    10971: @code{init} and @code{dispose} as constructor and destructor of the
                   10972: object. @code{init} is invocated after the object's memory is allocated,
                   10973: while @code{dispose} also handles deallocation. Thus if you redefine
                   10974: @code{dispose}, you have to call the parent's dispose with @code{super
                   10975: dispose}, too.
                   10976: 
                   10977: doc---object-init
                   10978: doc---object-dispose
                   10979: 
1.1       anton    10980: 
1.26      crook    10981: @item
1.78      anton    10982: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   10983: @code{[]} to create named and unnamed objects and object arrays or
                   10984: object pointers.
                   10985: 
                   10986: doc---object-new
                   10987: doc---object-new[]
                   10988: doc---object-:
                   10989: doc---object-ptr
                   10990: doc---object-asptr
                   10991: doc---object-[]
                   10992: 
1.1       anton    10993: 
1.26      crook    10994: @item
1.78      anton    10995: @code{::} and @code{super} for explicit scoping. You should use explicit
                   10996: scoping only for super classes or classes with the same set of instance
                   10997: variables. Explicitly-scoped selectors use early binding.
1.21      crook    10998: 
1.78      anton    10999: doc---object-::
                   11000: doc---object-super
1.21      crook    11001: 
                   11002: 
1.26      crook    11003: @item
1.78      anton    11004: @code{self} to get the address of the object
1.21      crook    11005: 
1.78      anton    11006: doc---object-self
1.21      crook    11007: 
                   11008: 
1.78      anton    11009: @item
                   11010: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   11011: pointers and instance defers.
1.21      crook    11012: 
1.78      anton    11013: doc---object-bind
                   11014: doc---object-bound
                   11015: doc---object-link
                   11016: doc---object-is
1.21      crook    11017: 
                   11018: 
1.78      anton    11019: @item
                   11020: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   11021: form the stack, and @code{postpone} to generate selector invocation code.
1.21      crook    11022: 
1.78      anton    11023: doc---object-'
                   11024: doc---object-postpone
1.21      crook    11025: 
                   11026: 
1.78      anton    11027: @item
                   11028: @code{with} and @code{endwith} to select the active object from the
                   11029: stack, and enable its scope. Using @code{with} and @code{endwith}
                   11030: also allows you to create code using selector @code{postpone} without being
                   11031: trapped by the state-smart objects.
1.21      crook    11032: 
1.78      anton    11033: doc---object-with
                   11034: doc---object-endwith
1.21      crook    11035: 
                   11036: 
1.78      anton    11037: @end itemize
1.21      crook    11038: 
1.78      anton    11039: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   11040: @subsubsection Class Declaration
                   11041: @cindex class declaration
1.21      crook    11042: 
1.78      anton    11043: @itemize @bullet
                   11044: @item
                   11045: Instance variables
1.21      crook    11046: 
1.78      anton    11047: doc---oof-var
1.21      crook    11048: 
                   11049: 
1.78      anton    11050: @item
                   11051: Object pointers
1.21      crook    11052: 
1.78      anton    11053: doc---oof-ptr
                   11054: doc---oof-asptr
1.21      crook    11055: 
                   11056: 
1.78      anton    11057: @item
                   11058: Instance defers
1.21      crook    11059: 
1.78      anton    11060: doc---oof-defer
1.21      crook    11061: 
                   11062: 
1.78      anton    11063: @item
                   11064: Method selectors
1.21      crook    11065: 
1.78      anton    11066: doc---oof-early
                   11067: doc---oof-method
1.21      crook    11068: 
                   11069: 
1.78      anton    11070: @item
                   11071: Class-wide variables
1.21      crook    11072: 
1.78      anton    11073: doc---oof-static
1.21      crook    11074: 
                   11075: 
1.78      anton    11076: @item
                   11077: End declaration
1.1       anton    11078: 
1.78      anton    11079: doc---oof-how:
                   11080: doc---oof-class;
1.21      crook    11081: 
                   11082: 
1.78      anton    11083: @end itemize
1.21      crook    11084: 
1.78      anton    11085: @c -------------------------------------------------------------
                   11086: @node Class Implementation,  , Class Declaration, OOF
                   11087: @subsubsection Class Implementation
                   11088: @cindex class implementation
1.21      crook    11089: 
1.78      anton    11090: @c -------------------------------------------------------------
                   11091: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   11092: @subsection The @file{mini-oof.fs} model
                   11093: @cindex mini-oof
1.21      crook    11094: 
1.78      anton    11095: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79      anton    11096: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78      anton    11097: and reduces to the bare minimum of features. This is based on a posting
                   11098: of Bernd Paysan in comp.lang.forth.
1.21      crook    11099: 
1.78      anton    11100: @menu
                   11101: * Basic Mini-OOF Usage::        
                   11102: * Mini-OOF Example::            
                   11103: * Mini-OOF Implementation::     
                   11104: @end menu
1.21      crook    11105: 
1.78      anton    11106: @c -------------------------------------------------------------
                   11107: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
                   11108: @subsubsection Basic @file{mini-oof.fs} Usage
                   11109: @cindex mini-oof usage
1.21      crook    11110: 
1.78      anton    11111: There is a base class (@code{class}, which allocates one cell for the
                   11112: object pointer) plus seven other words: to define a method, a variable,
                   11113: a class; to end a class, to resolve binding, to allocate an object and
                   11114: to compile a class method.
                   11115: @comment TODO better description of the last one
1.26      crook    11116: 
1.21      crook    11117: 
1.78      anton    11118: doc-object
                   11119: doc-method
                   11120: doc-var
                   11121: doc-class
                   11122: doc-end-class
                   11123: doc-defines
                   11124: doc-new
                   11125: doc-::
1.21      crook    11126: 
                   11127: 
                   11128: 
1.78      anton    11129: @c -------------------------------------------------------------
                   11130: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   11131: @subsubsection Mini-OOF Example
                   11132: @cindex mini-oof example
1.1       anton    11133: 
1.78      anton    11134: A short example shows how to use this package. This example, in slightly
                   11135: extended form, is supplied as @file{moof-exm.fs}
                   11136: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20      pazsan   11137: 
1.26      crook    11138: @example
1.78      anton    11139: object class
                   11140:   method init
                   11141:   method draw
                   11142: end-class graphical
1.26      crook    11143: @end example
1.20      pazsan   11144: 
1.78      anton    11145: This code defines a class @code{graphical} with an
                   11146: operation @code{draw}.  We can perform the operation
                   11147: @code{draw} on any @code{graphical} object, e.g.:
1.20      pazsan   11148: 
1.26      crook    11149: @example
1.78      anton    11150: 100 100 t-rex draw
1.26      crook    11151: @end example
1.12      anton    11152: 
1.78      anton    11153: where @code{t-rex} is an object or object pointer, created with e.g.
                   11154: @code{graphical new Constant t-rex}.
1.12      anton    11155: 
1.78      anton    11156: For concrete graphical objects, we define child classes of the
                   11157: class @code{graphical}, e.g.:
1.12      anton    11158: 
1.26      crook    11159: @example
                   11160: graphical class
1.78      anton    11161:   cell var circle-radius
                   11162: end-class circle \ "graphical" is the parent class
1.12      anton    11163: 
1.78      anton    11164: :noname ( x y -- )
                   11165:   circle-radius @@ draw-circle ; circle defines draw
                   11166: :noname ( r -- )
                   11167:   circle-radius ! ; circle defines init
                   11168: @end example
1.12      anton    11169: 
1.78      anton    11170: There is no implicit init method, so we have to define one. The creation
                   11171: code of the object now has to call init explicitely.
1.21      crook    11172: 
1.78      anton    11173: @example
                   11174: circle new Constant my-circle
                   11175: 50 my-circle init
1.12      anton    11176: @end example
                   11177: 
1.78      anton    11178: It is also possible to add a function to create named objects with
                   11179: automatic call of @code{init}, given that all objects have @code{init}
                   11180: on the same place:
1.38      anton    11181: 
1.78      anton    11182: @example
                   11183: : new: ( .. o "name" -- )
                   11184:     new dup Constant init ;
                   11185: 80 circle new: large-circle
                   11186: @end example
1.12      anton    11187: 
1.78      anton    11188: We can draw this new circle at (100,100) with:
1.12      anton    11189: 
1.78      anton    11190: @example
                   11191: 100 100 my-circle draw
                   11192: @end example
1.12      anton    11193: 
1.78      anton    11194: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
                   11195: @subsubsection @file{mini-oof.fs} Implementation
1.12      anton    11196: 
1.78      anton    11197: Object-oriented systems with late binding typically use a
                   11198: ``vtable''-approach: the first variable in each object is a pointer to a
                   11199: table, which contains the methods as function pointers. The vtable
                   11200: may also contain other information.
1.12      anton    11201: 
1.79      anton    11202: So first, let's declare selectors:
1.37      anton    11203: 
                   11204: @example
1.79      anton    11205: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
1.78      anton    11206:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
                   11207: @end example
1.37      anton    11208: 
1.79      anton    11209: During selector declaration, the number of selectors and instance
                   11210: variables is on the stack (in address units). @code{method} creates one
                   11211: selector and increments the selector number. To execute a selector, it
1.78      anton    11212: takes the object, fetches the vtable pointer, adds the offset, and
1.79      anton    11213: executes the method @i{xt} stored there. Each selector takes the object
                   11214: it is invoked with as top of stack parameter; it passes the parameters
                   11215: (including the object) unchanged to the appropriate method which should
1.78      anton    11216: consume that object.
1.37      anton    11217: 
1.78      anton    11218: Now, we also have to declare instance variables
1.37      anton    11219: 
1.78      anton    11220: @example
1.79      anton    11221: : var ( m v size "name" -- m v' ) Create  over , +
1.78      anton    11222:   DOES> ( o -- addr ) @@ + ;
1.37      anton    11223: @end example
                   11224: 
1.78      anton    11225: As before, a word is created with the current offset. Instance
                   11226: variables can have different sizes (cells, floats, doubles, chars), so
                   11227: all we do is take the size and add it to the offset. If your machine
                   11228: has alignment restrictions, put the proper @code{aligned} or
                   11229: @code{faligned} before the variable, to adjust the variable
                   11230: offset. That's why it is on the top of stack.
1.37      anton    11231: 
1.78      anton    11232: We need a starting point (the base object) and some syntactic sugar:
1.37      anton    11233: 
1.78      anton    11234: @example
                   11235: Create object  1 cells , 2 cells ,
1.79      anton    11236: : class ( class -- class selectors vars ) dup 2@@ ;
1.78      anton    11237: @end example
1.12      anton    11238: 
1.78      anton    11239: For inheritance, the vtable of the parent object has to be
                   11240: copied when a new, derived class is declared. This gives all the
                   11241: methods of the parent class, which can be overridden, though.
1.12      anton    11242: 
1.78      anton    11243: @example
1.79      anton    11244: : end-class  ( class selectors vars "name" -- )
1.78      anton    11245:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   11246:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
                   11247: @end example
1.12      anton    11248: 
1.78      anton    11249: The first line creates the vtable, initialized with
                   11250: @code{noop}s. The second line is the inheritance mechanism, it
                   11251: copies the xts from the parent vtable.
1.12      anton    11252: 
1.78      anton    11253: We still have no way to define new methods, let's do that now:
1.12      anton    11254: 
1.26      crook    11255: @example
1.79      anton    11256: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78      anton    11257: @end example
1.12      anton    11258: 
1.78      anton    11259: To allocate a new object, we need a word, too:
1.12      anton    11260: 
1.78      anton    11261: @example
                   11262: : new ( class -- o )  here over @@ allot swap over ! ;
1.12      anton    11263: @end example
                   11264: 
1.78      anton    11265: Sometimes derived classes want to access the method of the
                   11266: parent object. There are two ways to achieve this with Mini-OOF:
                   11267: first, you could use named words, and second, you could look up the
                   11268: vtable of the parent object.
1.12      anton    11269: 
1.78      anton    11270: @example
                   11271: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
                   11272: @end example
1.12      anton    11273: 
                   11274: 
1.78      anton    11275: Nothing can be more confusing than a good example, so here is
                   11276: one. First let's declare a text object (called
                   11277: @code{button}), that stores text and position:
1.12      anton    11278: 
1.78      anton    11279: @example
                   11280: object class
                   11281:   cell var text
                   11282:   cell var len
                   11283:   cell var x
                   11284:   cell var y
                   11285:   method init
                   11286:   method draw
                   11287: end-class button
                   11288: @end example
1.12      anton    11289: 
1.78      anton    11290: @noindent
                   11291: Now, implement the two methods, @code{draw} and @code{init}:
1.21      crook    11292: 
1.26      crook    11293: @example
1.78      anton    11294: :noname ( o -- )
                   11295:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
                   11296:  button defines draw
                   11297: :noname ( addr u o -- )
                   11298:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
                   11299:  button defines init
1.26      crook    11300: @end example
1.12      anton    11301: 
1.78      anton    11302: @noindent
                   11303: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79      anton    11304: new data and no new selectors:
1.78      anton    11305: 
                   11306: @example
                   11307: button class
                   11308: end-class bold-button
1.12      anton    11309: 
1.78      anton    11310: : bold   27 emit ." [1m" ;
                   11311: : normal 27 emit ." [0m" ;
                   11312: @end example
1.1       anton    11313: 
1.78      anton    11314: @noindent
                   11315: The class @code{bold-button} has a different draw method to
                   11316: @code{button}, but the new method is defined in terms of the draw method
                   11317: for @code{button}:
1.20      pazsan   11318: 
1.78      anton    11319: @example
                   11320: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   11321: @end example
1.21      crook    11322: 
1.78      anton    11323: @noindent
1.79      anton    11324: Finally, create two objects and apply selectors:
1.21      crook    11325: 
1.26      crook    11326: @example
1.78      anton    11327: button new Constant foo
                   11328: s" thin foo" foo init
                   11329: page
                   11330: foo draw
                   11331: bold-button new Constant bar
                   11332: s" fat bar" bar init
                   11333: 1 bar y !
                   11334: bar draw
1.26      crook    11335: @end example
1.21      crook    11336: 
                   11337: 
1.78      anton    11338: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   11339: @subsection Comparison with other object models
                   11340: @cindex comparison of object models
                   11341: @cindex object models, comparison
                   11342: 
                   11343: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   11344: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   11345: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   11346: relation of the object models described here to two well-known and two
                   11347: closely-related (by the use of method maps) models.  Andras Zsoter
                   11348: helped us with this section.
                   11349: 
                   11350: @cindex Neon model
                   11351: The most popular model currently seems to be the Neon model (see
                   11352: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   11353: 1997) by Andrew McKewan) but this model has a number of limitations
                   11354: @footnote{A longer version of this critique can be
                   11355: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   11356: Dimensions, May 1997) by Anton Ertl.}:
                   11357: 
                   11358: @itemize @bullet
                   11359: @item
                   11360: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11361: to pass objects on the stack.
1.21      crook    11362: 
1.78      anton    11363: @item
                   11364: It requires that the selector parses the input stream (at
1.79      anton    11365: compile time); this leads to reduced extensibility and to bugs that are
1.78      anton    11366: hard to find.
1.21      crook    11367: 
1.78      anton    11368: @item
1.79      anton    11369: It allows using every selector on every object; this eliminates the
                   11370: need for interfaces, but makes it harder to create efficient
                   11371: implementations.
1.78      anton    11372: @end itemize
1.21      crook    11373: 
1.78      anton    11374: @cindex Pountain's object-oriented model
                   11375: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11376: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11377: object-oriented programming, because it hardly deals with late
                   11378: binding. Instead, it focuses on features like information hiding and
                   11379: overloading that are characteristic of modular languages like Ada (83).
1.26      crook    11380: 
1.78      anton    11381: @cindex Zsoter's object-oriented model
1.79      anton    11382: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
                   11383: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
                   11384: describes a model that makes heavy use of an active object (like
                   11385: @code{this} in @file{objects.fs}): The active object is not only used
                   11386: for accessing all fields, but also specifies the receiving object of
                   11387: every selector invocation; you have to change the active object
                   11388: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   11389: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   11390: the method entry point is unnecessary with Zsoter's model, because the
                   11391: receiving object is the active object already. On the other hand, the
                   11392: explicit change is absolutely necessary in that model, because otherwise
                   11393: no one could ever change the active object. An ANS Forth implementation
                   11394: of this model is available through
                   11395: @uref{http://www.forth.org/oopf.html}.
1.21      crook    11396: 
1.78      anton    11397: @cindex @file{oof.fs}, differences to other models
                   11398: The @file{oof.fs} model combines information hiding and overloading
                   11399: resolution (by keeping names in various word lists) with object-oriented
                   11400: programming. It sets the active object implicitly on method entry, but
                   11401: also allows explicit changing (with @code{>o...o>} or with
                   11402: @code{with...endwith}). It uses parsing and state-smart objects and
                   11403: classes for resolving overloading and for early binding: the object or
                   11404: class parses the selector and determines the method from this. If the
                   11405: selector is not parsed by an object or class, it performs a call to the
                   11406: selector for the active object (late binding), like Zsoter's model.
                   11407: Fields are always accessed through the active object. The big
                   11408: disadvantage of this model is the parsing and the state-smartness, which
                   11409: reduces extensibility and increases the opportunities for subtle bugs;
                   11410: essentially, you are only safe if you never tick or @code{postpone} an
                   11411: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21      crook    11412: 
1.78      anton    11413: @cindex @file{mini-oof.fs}, differences to other models
                   11414: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11415: version of the @file{objects.fs} model, but syntactically it is a
                   11416: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21      crook    11417: 
                   11418: 
1.78      anton    11419: @c -------------------------------------------------------------
                   11420: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
                   11421: @section Programming Tools
                   11422: @cindex programming tools
1.21      crook    11423: 
1.78      anton    11424: @c !! move this and assembler down below OO stuff.
1.21      crook    11425: 
1.78      anton    11426: @menu
                   11427: * Examining::                   
                   11428: * Forgetting words::            
                   11429: * Debugging::                   Simple and quick.
                   11430: * Assertions::                  Making your programs self-checking.
                   11431: * Singlestep Debugger::         Executing your program word by word.
                   11432: @end menu
1.21      crook    11433: 
1.78      anton    11434: @node Examining, Forgetting words, Programming Tools, Programming Tools
                   11435: @subsection Examining data and code
                   11436: @cindex examining data and code
                   11437: @cindex data examination
                   11438: @cindex code examination
1.44      crook    11439: 
1.78      anton    11440: The following words inspect the stack non-destructively:
1.21      crook    11441: 
1.78      anton    11442: doc-.s
                   11443: doc-f.s
1.44      crook    11444: 
1.78      anton    11445: There is a word @code{.r} but it does @i{not} display the return stack!
                   11446: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21      crook    11447: 
1.78      anton    11448: doc-depth
                   11449: doc-fdepth
                   11450: doc-clearstack
1.21      crook    11451: 
1.78      anton    11452: The following words inspect memory.
1.21      crook    11453: 
1.78      anton    11454: doc-?
                   11455: doc-dump
1.21      crook    11456: 
1.78      anton    11457: And finally, @code{see} allows to inspect code:
1.21      crook    11458: 
1.78      anton    11459: doc-see
                   11460: doc-xt-see
1.21      crook    11461: 
1.78      anton    11462: @node Forgetting words, Debugging, Examining, Programming Tools
                   11463: @subsection Forgetting words
                   11464: @cindex words, forgetting
                   11465: @cindex forgeting words
1.21      crook    11466: 
1.78      anton    11467: @c  anton: other, maybe better places for this subsection: Defining Words;
                   11468: @c  Dictionary allocation.  At least a reference should be there.
1.21      crook    11469: 
1.78      anton    11470: Forth allows you to forget words (and everything that was alloted in the
                   11471: dictonary after them) in a LIFO manner.
1.21      crook    11472: 
1.78      anton    11473: doc-marker
1.21      crook    11474: 
1.78      anton    11475: The most common use of this feature is during progam development: when
                   11476: you change a source file, forget all the words it defined and load it
                   11477: again (since you also forget everything defined after the source file
                   11478: was loaded, you have to reload that, too).  Note that effects like
                   11479: storing to variables and destroyed system words are not undone when you
                   11480: forget words.  With a system like Gforth, that is fast enough at
                   11481: starting up and compiling, I find it more convenient to exit and restart
                   11482: Gforth, as this gives me a clean slate.
1.21      crook    11483: 
1.78      anton    11484: Here's an example of using @code{marker} at the start of a source file
                   11485: that you are debugging; it ensures that you only ever have one copy of
                   11486: the file's definitions compiled at any time:
1.21      crook    11487: 
1.78      anton    11488: @example
                   11489: [IFDEF] my-code
                   11490:     my-code
                   11491: [ENDIF]
1.26      crook    11492: 
1.78      anton    11493: marker my-code
                   11494: init-included-files
1.21      crook    11495: 
1.78      anton    11496: \ .. definitions start here
                   11497: \ .
                   11498: \ .
                   11499: \ end
                   11500: @end example
1.21      crook    11501: 
1.26      crook    11502: 
1.78      anton    11503: @node Debugging, Assertions, Forgetting words, Programming Tools
                   11504: @subsection Debugging
                   11505: @cindex debugging
1.21      crook    11506: 
1.78      anton    11507: Languages with a slow edit/compile/link/test development loop tend to
                   11508: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21      crook    11509: 
1.78      anton    11510: A much better (faster) way in fast-compiling languages is to add
                   11511: printing code at well-selected places, let the program run, look at
                   11512: the output, see where things went wrong, add more printing code, etc.,
                   11513: until the bug is found.
1.21      crook    11514: 
1.78      anton    11515: The simple debugging aids provided in @file{debugs.fs}
                   11516: are meant to support this style of debugging.
1.21      crook    11517: 
1.78      anton    11518: The word @code{~~} prints debugging information (by default the source
                   11519: location and the stack contents). It is easy to insert. If you use Emacs
                   11520: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   11521: query-replace them with nothing). The deferred words
                   11522: @code{printdebugdata} and @code{printdebugline} control the output of
                   11523: @code{~~}. The default source location output format works well with
                   11524: Emacs' compilation mode, so you can step through the program at the
                   11525: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   11526: is that you can step in any direction and you know where the crash has
                   11527: happened or where the strange data has occurred).
1.21      crook    11528: 
1.78      anton    11529: doc-~~
                   11530: doc-printdebugdata
                   11531: doc-printdebugline
1.21      crook    11532: 
1.78      anton    11533: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   11534: @subsection Assertions
                   11535: @cindex assertions
1.21      crook    11536: 
1.78      anton    11537: It is a good idea to make your programs self-checking, especially if you
                   11538: make an assumption that may become invalid during maintenance (for
                   11539: example, that a certain field of a data structure is never zero). Gforth
                   11540: supports @dfn{assertions} for this purpose. They are used like this:
1.21      crook    11541: 
                   11542: @example
1.78      anton    11543: assert( @i{flag} )
1.26      crook    11544: @end example
                   11545: 
1.78      anton    11546: The code between @code{assert(} and @code{)} should compute a flag, that
                   11547: should be true if everything is alright and false otherwise. It should
                   11548: not change anything else on the stack. The overall stack effect of the
                   11549: assertion is @code{( -- )}. E.g.
1.21      crook    11550: 
1.26      crook    11551: @example
1.78      anton    11552: assert( 1 1 + 2 = ) \ what we learn in school
                   11553: assert( dup 0<> ) \ assert that the top of stack is not zero
                   11554: assert( false ) \ this code should not be reached
1.21      crook    11555: @end example
                   11556: 
1.78      anton    11557: The need for assertions is different at different times. During
                   11558: debugging, we want more checking, in production we sometimes care more
                   11559: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   11560: becomes a comment. Depending on the importance of an assertion and the
                   11561: time it takes to check it, you may want to turn off some assertions and
                   11562: keep others turned on. Gforth provides several levels of assertions for
                   11563: this purpose:
                   11564: 
                   11565: 
                   11566: doc-assert0(
                   11567: doc-assert1(
                   11568: doc-assert2(
                   11569: doc-assert3(
                   11570: doc-assert(
                   11571: doc-)
1.21      crook    11572: 
                   11573: 
1.78      anton    11574: The variable @code{assert-level} specifies the highest assertions that
                   11575: are turned on. I.e., at the default @code{assert-level} of one,
                   11576: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   11577: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26      crook    11578: 
1.78      anton    11579: The value of @code{assert-level} is evaluated at compile-time, not at
                   11580: run-time. Therefore you cannot turn assertions on or off at run-time;
                   11581: you have to set the @code{assert-level} appropriately before compiling a
                   11582: piece of code. You can compile different pieces of code at different
                   11583: @code{assert-level}s (e.g., a trusted library at level 1 and
                   11584: newly-written code at level 3).
1.26      crook    11585: 
                   11586: 
1.78      anton    11587: doc-assert-level
1.26      crook    11588: 
                   11589: 
1.78      anton    11590: If an assertion fails, a message compatible with Emacs' compilation mode
                   11591: is produced and the execution is aborted (currently with @code{ABORT"}.
                   11592: If there is interest, we will introduce a special throw code. But if you
                   11593: intend to @code{catch} a specific condition, using @code{throw} is
                   11594: probably more appropriate than an assertion).
1.44      crook    11595: 
1.78      anton    11596: Definitions in ANS Forth for these assertion words are provided
                   11597: in @file{compat/assert.fs}.
1.26      crook    11598: 
1.44      crook    11599: 
1.78      anton    11600: @node Singlestep Debugger,  , Assertions, Programming Tools
                   11601: @subsection Singlestep Debugger
                   11602: @cindex singlestep Debugger
                   11603: @cindex debugging Singlestep
1.44      crook    11604: 
1.78      anton    11605: When you create a new word there's often the need to check whether it
                   11606: behaves correctly or not. You can do this by typing @code{dbg
                   11607: badword}. A debug session might look like this:
1.26      crook    11608: 
1.78      anton    11609: @example
                   11610: : badword 0 DO i . LOOP ;  ok
                   11611: 2 dbg badword 
                   11612: : badword  
                   11613: Scanning code...
1.44      crook    11614: 
1.78      anton    11615: Nesting debugger ready!
1.44      crook    11616: 
1.78      anton    11617: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   11618: 400D4740  8049F68 DO             -> [ 0 ] 
                   11619: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   11620: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   11621: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   11622: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   11623: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   11624: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   11625: 400D4758  804B384 ;              ->  ok
                   11626: @end example
1.21      crook    11627: 
1.78      anton    11628: Each line displayed is one step. You always have to hit return to
                   11629: execute the next word that is displayed. If you don't want to execute
                   11630: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   11631: an overview what keys are available:
1.44      crook    11632: 
1.78      anton    11633: @table @i
1.44      crook    11634: 
1.78      anton    11635: @item @key{RET}
                   11636: Next; Execute the next word.
1.21      crook    11637: 
1.78      anton    11638: @item n
                   11639: Nest; Single step through next word.
1.44      crook    11640: 
1.78      anton    11641: @item u
                   11642: Unnest; Stop debugging and execute rest of word. If we got to this word
                   11643: with nest, continue debugging with the calling word.
1.44      crook    11644: 
1.78      anton    11645: @item d
                   11646: Done; Stop debugging and execute rest.
1.21      crook    11647: 
1.78      anton    11648: @item s
                   11649: Stop; Abort immediately.
1.44      crook    11650: 
1.78      anton    11651: @end table
1.44      crook    11652: 
1.78      anton    11653: Debugging large application with this mechanism is very difficult, because
                   11654: you have to nest very deeply into the program before the interesting part
                   11655: begins. This takes a lot of time. 
1.26      crook    11656: 
1.78      anton    11657: To do it more directly put a @code{BREAK:} command into your source code.
                   11658: When program execution reaches @code{BREAK:} the single step debugger is
                   11659: invoked and you have all the features described above.
1.44      crook    11660: 
1.78      anton    11661: If you have more than one part to debug it is useful to know where the
                   11662: program has stopped at the moment. You can do this by the 
                   11663: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   11664: string is typed out when the ``breakpoint'' is reached.
1.44      crook    11665: 
1.26      crook    11666: 
1.78      anton    11667: doc-dbg
                   11668: doc-break:
                   11669: doc-break"
1.44      crook    11670: 
                   11671: 
1.26      crook    11672: 
1.78      anton    11673: @c -------------------------------------------------------------
                   11674: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   11675: @section Assembler and Code Words
                   11676: @cindex assembler
                   11677: @cindex code words
1.44      crook    11678: 
1.78      anton    11679: @menu
                   11680: * Code and ;code::              
                   11681: * Common Assembler::            Assembler Syntax
                   11682: * Common Disassembler::         
                   11683: * 386 Assembler::               Deviations and special cases
                   11684: * Alpha Assembler::             Deviations and special cases
                   11685: * MIPS assembler::              Deviations and special cases
                   11686: * Other assemblers::            How to write them
                   11687: @end menu
1.21      crook    11688: 
1.78      anton    11689: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
                   11690: @subsection @code{Code} and @code{;code}
1.26      crook    11691: 
1.78      anton    11692: Gforth provides some words for defining primitives (words written in
                   11693: machine code), and for defining the machine-code equivalent of
                   11694: @code{DOES>}-based defining words. However, the machine-independent
                   11695: nature of Gforth poses a few problems: First of all, Gforth runs on
                   11696: several architectures, so it can provide no standard assembler. What's
                   11697: worse is that the register allocation not only depends on the processor,
                   11698: but also on the @code{gcc} version and options used.
1.44      crook    11699: 
1.78      anton    11700: The words that Gforth offers encapsulate some system dependences (e.g.,
                   11701: the header structure), so a system-independent assembler may be used in
                   11702: Gforth. If you do not have an assembler, you can compile machine code
                   11703: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   11704: because these words emit stuff in @i{data} space; it works because
                   11705: Gforth has unified code/data spaces. Assembler isn't likely to be
                   11706: portable anyway.}.
1.21      crook    11707: 
1.44      crook    11708: 
1.78      anton    11709: doc-assembler
                   11710: doc-init-asm
                   11711: doc-code
                   11712: doc-end-code
                   11713: doc-;code
                   11714: doc-flush-icache
1.44      crook    11715: 
1.21      crook    11716: 
1.78      anton    11717: If @code{flush-icache} does not work correctly, @code{code} words
                   11718: etc. will not work (reliably), either.
1.44      crook    11719: 
1.78      anton    11720: The typical usage of these @code{code} words can be shown most easily by
                   11721: analogy to the equivalent high-level defining words:
1.44      crook    11722: 
1.78      anton    11723: @example
                   11724: : foo                              code foo
                   11725:    <high-level Forth words>              <assembler>
                   11726: ;                                  end-code
                   11727:                                 
                   11728: : bar                              : bar
                   11729:    <high-level Forth words>           <high-level Forth words>
                   11730:    CREATE                             CREATE
                   11731:       <high-level Forth words>           <high-level Forth words>
                   11732:    DOES>                              ;code
                   11733:       <high-level Forth words>           <assembler>
                   11734: ;                                  end-code
                   11735: @end example
1.21      crook    11736: 
1.78      anton    11737: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44      crook    11738: 
1.78      anton    11739: @cindex registers of the inner interpreter
                   11740: In the assembly code you will want to refer to the inner interpreter's
                   11741: registers (e.g., the data stack pointer) and you may want to use other
                   11742: registers for temporary storage. Unfortunately, the register allocation
                   11743: is installation-dependent.
1.44      crook    11744: 
1.78      anton    11745: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
                   11746: (return stack pointer) are in different places in @code{gforth} and
                   11747: @code{gforth-fast}.  This means that you cannot write a @code{NEXT}
                   11748: routine that works on both versions; so for doing @code{NEXT}, I
                   11749: recomment jumping to @code{' noop >code-address}, which contains nothing
                   11750: but a @code{NEXT}.
1.21      crook    11751: 
1.78      anton    11752: For general accesses to the inner interpreter's registers, the easiest
                   11753: solution is to use explicit register declarations (@pxref{Explicit Reg
                   11754: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
                   11755: all of the inner interpreter's registers: You have to compile Gforth
                   11756: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
                   11757: the appropriate declarations must be present in the @code{machine.h}
                   11758: file (see @code{mips.h} for an example; you can find a full list of all
                   11759: declarable register symbols with @code{grep register engine.c}). If you
                   11760: give explicit registers to all variables that are declared at the
                   11761: beginning of @code{engine()}, you should be able to use the other
                   11762: caller-saved registers for temporary storage. Alternatively, you can use
                   11763: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
                   11764: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
                   11765: reserve a register (however, this restriction on register allocation may
                   11766: slow Gforth significantly).
1.44      crook    11767: 
1.78      anton    11768: If this solution is not viable (e.g., because @code{gcc} does not allow
                   11769: you to explicitly declare all the registers you need), you have to find
                   11770: out by looking at the code where the inner interpreter's registers
                   11771: reside and which registers can be used for temporary storage. You can
                   11772: get an assembly listing of the engine's code with @code{make engine.s}.
1.44      crook    11773: 
1.78      anton    11774: In any case, it is good practice to abstract your assembly code from the
                   11775: actual register allocation. E.g., if the data stack pointer resides in
                   11776: register @code{$17}, create an alias for this register called @code{sp},
                   11777: and use that in your assembly code.
1.21      crook    11778: 
1.78      anton    11779: @cindex code words, portable
                   11780: Another option for implementing normal and defining words efficiently
                   11781: is to add the desired functionality to the source of Gforth. For normal
                   11782: words you just have to edit @file{primitives} (@pxref{Automatic
                   11783: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   11784: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   11785: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44      crook    11786: 
1.78      anton    11787: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
                   11788: @subsection Common Assembler
1.44      crook    11789: 
1.78      anton    11790: The assemblers in Gforth generally use a postfix syntax, i.e., the
                   11791: instruction name follows the operands.
1.21      crook    11792: 
1.78      anton    11793: The operands are passed in the usual order (the same that is used in the
                   11794: manual of the architecture).  Since they all are Forth words, they have
                   11795: to be separated by spaces; you can also use Forth words to compute the
                   11796: operands.
1.44      crook    11797: 
1.78      anton    11798: The instruction names usually end with a @code{,}.  This makes it easier
                   11799: to visually separate instructions if you put several of them on one
                   11800: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21      crook    11801: 
1.78      anton    11802: Registers are usually specified by number; e.g., (decimal) @code{11}
                   11803: specifies registers R11 and F11 on the Alpha architecture (which one,
                   11804: depends on the instruction).  The usual names are also available, e.g.,
                   11805: @code{s2} for R11 on Alpha.
1.21      crook    11806: 
1.78      anton    11807: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
                   11808: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
                   11809: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
                   11810: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
                   11811: conditions are specified in a way specific to each assembler.
1.1       anton    11812: 
1.78      anton    11813: Note that the register assignments of the Gforth engine can change
                   11814: between Gforth versions, or even between different compilations of the
                   11815: same Gforth version (e.g., if you use a different GCC version).  So if
                   11816: you want to refer to Gforth's registers (e.g., the stack pointer or
                   11817: TOS), I recommend defining your own words for refering to these
                   11818: registers, and using them later on; then you can easily adapt to a
                   11819: changed register assignment.  The stability of the register assignment
                   11820: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1       anton    11821: 
1.78      anton    11822: In particular, the return stack pointer and the instruction pointer are
                   11823: in memory in @code{gforth}, and usually in registers in
                   11824: @code{gforth-fast}.  The most common use of these registers is to
                   11825: dispatch to the next word (the @code{next} routine).  A portable way to
                   11826: do this is to jump to @code{' noop >code-address} (of course, this is
                   11827: less efficient than integrating the @code{next} code and scheduling it
                   11828: well).
1.1       anton    11829: 
1.78      anton    11830: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
                   11831: @subsection Common Disassembler
1.1       anton    11832: 
1.78      anton    11833: You can disassemble a @code{code} word with @code{see}
                   11834: (@pxref{Debugging}).  You can disassemble a section of memory with
1.1       anton    11835: 
1.78      anton    11836: doc-disasm
1.44      crook    11837: 
1.78      anton    11838: The disassembler generally produces output that can be fed into the
                   11839: assembler (i.e., same syntax, etc.).  It also includes additional
                   11840: information in comments.  In particular, the address of the instruction
                   11841: is given in a comment before the instruction.
1.1       anton    11842: 
1.78      anton    11843: @code{See} may display more or less than the actual code of the word,
                   11844: because the recognition of the end of the code is unreliable.  You can
                   11845: use @code{disasm} if it did not display enough.  It may display more, if
                   11846: the code word is not immediately followed by a named word.  If you have
                   11847: something else there, you can follow the word with @code{align last @ ,}
                   11848: to ensure that the end is recognized.
1.21      crook    11849: 
1.78      anton    11850: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
                   11851: @subsection 386 Assembler
1.44      crook    11852: 
1.78      anton    11853: The 386 assembler included in Gforth was written by Bernd Paysan, it's
                   11854: available under GPL, and originally part of bigFORTH.
1.21      crook    11855: 
1.78      anton    11856: The 386 disassembler included in Gforth was written by Andrew McKewan
                   11857: and is in the public domain.
1.21      crook    11858: 
1.91      anton    11859: The disassembler displays code in an Intel-like prefix syntax.
1.21      crook    11860: 
1.78      anton    11861: The assembler uses a postfix syntax with reversed parameters.
1.1       anton    11862: 
1.78      anton    11863: The assembler includes all instruction of the Athlon, i.e. 486 core
                   11864: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
                   11865: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
                   11866: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1       anton    11867: 
1.78      anton    11868: There are several prefixes to switch between different operation sizes,
                   11869: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
                   11870: double-word accesses. Addressing modes can be switched with @code{.wa}
                   11871: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
                   11872: need a prefix for byte register names (@code{AL} et al).
1.1       anton    11873: 
1.78      anton    11874: For floating point operations, the prefixes are @code{.fs} (IEEE
                   11875: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
                   11876: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21      crook    11877: 
1.78      anton    11878: The MMX opcodes don't have size prefixes, they are spelled out like in
                   11879: the Intel assembler. Instead of move from and to memory, there are
                   11880: PLDQ/PLDD and PSTQ/PSTD.
1.21      crook    11881: 
1.78      anton    11882: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
                   11883: ax.  Immediate values are indicated by postfixing them with @code{#},
1.91      anton    11884: e.g., @code{3 #}.  Here are some examples of addressing modes in various
                   11885: syntaxes:
1.21      crook    11886: 
1.26      crook    11887: @example
1.91      anton    11888: Gforth          Intel (NASM)   AT&T (gas)      Name
                   11889: .w ax           ax             %ax             register (16 bit)
                   11890: ax              eax            %eax            register (32 bit)
                   11891: 3 #             offset 3       $3              immediate
                   11892: 1000 #)         byte ptr 1000  1000            displacement
                   11893: bx )            [ebx]          (%ebx)          base
                   11894: 100 di d)       100[edi]       100(%edi)       base+displacement
                   11895: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
                   11896: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
                   11897: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
                   11898: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
                   11899: @end example
                   11900: 
                   11901: You can use @code{L)} and @code{LI)} instead of @code{D)} and
                   11902: @code{DI)} to enforce 32-bit displacement fields (useful for
                   11903: later patching).
1.21      crook    11904: 
1.78      anton    11905: Some example of instructions are:
1.1       anton    11906: 
                   11907: @example
1.78      anton    11908: ax bx mov             \ move ebx,eax
                   11909: 3 # ax mov            \ mov eax,3
                   11910: 100 di ) ax mov       \ mov eax,100[edi]
                   11911: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
                   11912: .w ax bx mov          \ mov bx,ax
1.1       anton    11913: @end example
                   11914: 
1.78      anton    11915: The following forms are supported for binary instructions:
1.1       anton    11916: 
                   11917: @example
1.78      anton    11918: <reg> <reg> <inst>
                   11919: <n> # <reg> <inst>
                   11920: <mem> <reg> <inst>
                   11921: <reg> <mem> <inst>
1.1       anton    11922: @end example
                   11923: 
1.78      anton    11924: Immediate to memory is not supported.  The shift/rotate syntax is:
1.1       anton    11925: 
1.26      crook    11926: @example
1.78      anton    11927: <reg/mem> 1 # shl \ shortens to shift without immediate
                   11928: <reg/mem> 4 # shl
                   11929: <reg/mem> cl shl
1.26      crook    11930: @end example
1.1       anton    11931: 
1.78      anton    11932: Precede string instructions (@code{movs} etc.) with @code{.b} to get
                   11933: the byte version.
1.1       anton    11934: 
1.78      anton    11935: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
                   11936: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
                   11937: pc < >= <= >}. (Note that most of these words shadow some Forth words
                   11938: when @code{assembler} is in front of @code{forth} in the search path,
                   11939: e.g., in @code{code} words).  Currently the control structure words use
                   11940: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
                   11941: to shuffle them (you can also use @code{swap} etc.).
1.21      crook    11942: 
1.78      anton    11943: Here is an example of a @code{code} word (assumes that the stack pointer
                   11944: is in esi and the TOS is in ebx):
1.21      crook    11945: 
1.26      crook    11946: @example
1.78      anton    11947: code my+ ( n1 n2 -- n )
                   11948:     4 si D) bx add
                   11949:     4 # si add
                   11950:     Next
                   11951: end-code
1.26      crook    11952: @end example
1.21      crook    11953: 
1.78      anton    11954: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
                   11955: @subsection Alpha Assembler
1.21      crook    11956: 
1.78      anton    11957: The Alpha assembler and disassembler were originally written by Bernd
                   11958: Thallner.
1.26      crook    11959: 
1.78      anton    11960: The register names @code{a0}--@code{a5} are not available to avoid
                   11961: shadowing hex numbers.
1.2       jwilke   11962: 
1.78      anton    11963: Immediate forms of arithmetic instructions are distinguished by a
                   11964: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
                   11965: does not count as arithmetic instruction).
1.2       jwilke   11966: 
1.78      anton    11967: You have to specify all operands to an instruction, even those that
                   11968: other assemblers consider optional, e.g., the destination register for
                   11969: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2       jwilke   11970: 
1.78      anton    11971: You can specify conditions for @code{if,} by removing the first @code{b}
                   11972: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2       jwilke   11973: 
1.26      crook    11974: @example
1.78      anton    11975: 11 fgt if, \ if F11>0e
                   11976:   ...
                   11977: endif,
1.26      crook    11978: @end example
1.2       jwilke   11979: 
1.78      anton    11980: @code{fbgt,} gives @code{fgt}.  
                   11981: 
                   11982: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
                   11983: @subsection MIPS assembler
1.2       jwilke   11984: 
1.78      anton    11985: The MIPS assembler was originally written by Christian Pirker.
1.2       jwilke   11986: 
1.78      anton    11987: Currently the assembler and disassembler only cover the MIPS-I
                   11988: architecture (R3000), and don't support FP instructions.
1.2       jwilke   11989: 
1.78      anton    11990: The register names @code{$a0}--@code{$a3} are not available to avoid
                   11991: shadowing hex numbers.
1.2       jwilke   11992: 
1.78      anton    11993: Because there is no way to distinguish registers from immediate values,
                   11994: you have to explicitly use the immediate forms of instructions, i.e.,
                   11995: @code{addiu,}, not just @code{addu,} (@command{as} does this
                   11996: implicitly).
1.2       jwilke   11997: 
1.78      anton    11998: If the architecture manual specifies several formats for the instruction
                   11999: (e.g., for @code{jalr,}), you usually have to use the one with more
                   12000: arguments (i.e., two for @code{jalr,}).  When in doubt, see
                   12001: @code{arch/mips/testasm.fs} for an example of correct use.
1.2       jwilke   12002: 
1.78      anton    12003: Branches and jumps in the MIPS architecture have a delay slot.  You have
                   12004: to fill it yourself (the simplest way is to use @code{nop,}), the
                   12005: assembler does not do it for you (unlike @command{as}).  Even
                   12006: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
                   12007: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
                   12008: and @code{then,} just specify branch targets, they are not affected.
1.2       jwilke   12009: 
1.78      anton    12010: Note that you must not put branches, jumps, or @code{li,} into the delay
                   12011: slot: @code{li,} may expand to several instructions, and control flow
                   12012: instructions may not be put into the branch delay slot in any case.
1.2       jwilke   12013: 
1.78      anton    12014: For branches the argument specifying the target is a relative address;
                   12015: You have to add the address of the delay slot to get the absolute
                   12016: address.
1.1       anton    12017: 
1.78      anton    12018: The MIPS architecture also has load delay slots and restrictions on
                   12019: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
                   12020: yourself to satisfy these restrictions, the assembler does not do it for
                   12021: you.
1.1       anton    12022: 
1.78      anton    12023: You can specify the conditions for @code{if,} etc. by taking a
                   12024: conditional branch and leaving away the @code{b} at the start and the
                   12025: @code{,} at the end.  E.g.,
1.1       anton    12026: 
1.26      crook    12027: @example
1.78      anton    12028: 4 5 eq if,
                   12029:   ... \ do something if $4 equals $5
                   12030: then,
1.26      crook    12031: @end example
1.1       anton    12032: 
1.78      anton    12033: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
                   12034: @subsection Other assemblers
                   12035: 
                   12036: If you want to contribute another assembler/disassembler, please contact
                   12037: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
                   12038: already.  If you are writing them from scratch, please use a similar
                   12039: syntax style as the one we use (i.e., postfix, commas at the end of the
                   12040: instruction names, @pxref{Common Assembler}); make the output of the
                   12041: disassembler be valid input for the assembler, and keep the style
                   12042: similar to the style we used.
                   12043: 
                   12044: Hints on implementation: The most important part is to have a good test
                   12045: suite that contains all instructions.  Once you have that, the rest is
                   12046: easy.  For actual coding you can take a look at
                   12047: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
                   12048: the assembler and disassembler, avoiding redundancy and some potential
                   12049: bugs.  You can also look at that file (and @pxref{Advanced does> usage
                   12050: example}) to get ideas how to factor a disassembler.
                   12051: 
                   12052: Start with the disassembler, because it's easier to reuse data from the
                   12053: disassembler for the assembler than the other way round.
1.1       anton    12054: 
1.78      anton    12055: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
                   12056: how simple it can be.
1.1       anton    12057: 
1.78      anton    12058: @c -------------------------------------------------------------
                   12059: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
                   12060: @section Threading Words
                   12061: @cindex threading words
1.1       anton    12062: 
1.78      anton    12063: @cindex code address
                   12064: These words provide access to code addresses and other threading stuff
                   12065: in Gforth (and, possibly, other interpretive Forths). It more or less
                   12066: abstracts away the differences between direct and indirect threading
                   12067: (and, for direct threading, the machine dependences). However, at
                   12068: present this wordset is still incomplete. It is also pretty low-level;
                   12069: some day it will hopefully be made unnecessary by an internals wordset
                   12070: that abstracts implementation details away completely.
1.1       anton    12071: 
1.78      anton    12072: The terminology used here stems from indirect threaded Forth systems; in
                   12073: such a system, the XT of a word is represented by the CFA (code field
                   12074: address) of a word; the CFA points to a cell that contains the code
                   12075: address.  The code address is the address of some machine code that
                   12076: performs the run-time action of invoking the word (e.g., the
                   12077: @code{dovar:} routine pushes the address of the body of the word (a
                   12078: variable) on the stack
                   12079: ).
1.1       anton    12080: 
1.78      anton    12081: @cindex code address
                   12082: @cindex code field address
                   12083: In an indirect threaded Forth, you can get the code address of @i{name}
                   12084: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
                   12085: >code-address}, independent of the threading method.
1.1       anton    12086: 
1.78      anton    12087: doc-threading-method
                   12088: doc->code-address
                   12089: doc-code-address!
1.1       anton    12090: 
1.78      anton    12091: @cindex @code{does>}-handler
                   12092: @cindex @code{does>}-code
                   12093: For a word defined with @code{DOES>}, the code address usually points to
                   12094: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
                   12095: routine (in Gforth on some platforms, it can also point to the dodoes
                   12096: routine itself).  What you are typically interested in, though, is
                   12097: whether a word is a @code{DOES>}-defined word, and what Forth code it
                   12098: executes; @code{>does-code} tells you that.
1.1       anton    12099: 
1.78      anton    12100: doc->does-code
1.1       anton    12101: 
1.78      anton    12102: To create a @code{DOES>}-defined word with the following basic words,
                   12103: you have to set up a @code{DOES>}-handler with @code{does-handler!};
                   12104: @code{/does-handler} aus behind you have to place your executable Forth
                   12105: code.  Finally you have to create a word and modify its behaviour with
                   12106: @code{does-handler!}.
1.1       anton    12107: 
1.78      anton    12108: doc-does-code!
                   12109: doc-does-handler!
                   12110: doc-/does-handler
1.1       anton    12111: 
1.78      anton    12112: The code addresses produced by various defining words are produced by
                   12113: the following words:
1.1       anton    12114: 
1.78      anton    12115: doc-docol:
                   12116: doc-docon:
                   12117: doc-dovar:
                   12118: doc-douser:
                   12119: doc-dodefer:
                   12120: doc-dofield:
1.1       anton    12121: 
1.26      crook    12122: @c -------------------------------------------------------------
1.78      anton    12123: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21      crook    12124: @section Passing Commands to the Operating System
                   12125: @cindex operating system - passing commands
                   12126: @cindex shell commands
                   12127: 
                   12128: Gforth allows you to pass an arbitrary string to the host operating
                   12129: system shell (if such a thing exists) for execution.
                   12130: 
1.44      crook    12131: 
1.21      crook    12132: doc-sh
                   12133: doc-system
                   12134: doc-$?
1.23      crook    12135: doc-getenv
1.21      crook    12136: 
1.44      crook    12137: 
1.26      crook    12138: @c -------------------------------------------------------------
1.47      crook    12139: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
                   12140: @section Keeping track of Time
                   12141: @cindex time-related words
                   12142: 
                   12143: doc-ms
                   12144: doc-time&date
1.79      anton    12145: doc-utime
                   12146: doc-cputime
1.47      crook    12147: 
                   12148: 
                   12149: @c -------------------------------------------------------------
                   12150: @node Miscellaneous Words,  , Keeping track of Time, Words
1.21      crook    12151: @section Miscellaneous Words
                   12152: @cindex miscellaneous words
                   12153: 
1.29      crook    12154: @comment TODO find homes for these
                   12155: 
1.26      crook    12156: These section lists the ANS Forth words that are not documented
1.21      crook    12157: elsewhere in this manual. Ultimately, they all need proper homes.
                   12158: 
1.68      anton    12159: doc-quit
1.44      crook    12160: 
1.26      crook    12161: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    12162: (@pxref{ANS conformance}):
1.21      crook    12163: 
                   12164: @code{EDITOR} 
                   12165: @code{EMIT?} 
                   12166: @code{FORGET} 
                   12167: 
1.24      anton    12168: @c ******************************************************************
                   12169: @node Error messages, Tools, Words, Top
                   12170: @chapter Error messages
                   12171: @cindex error messages
                   12172: @cindex backtrace
                   12173: 
                   12174: A typical Gforth error message looks like this:
                   12175: 
                   12176: @example
1.86      anton    12177: in file included from \evaluated string/:-1
1.24      anton    12178: in file included from ./yyy.fs:1
                   12179: ./xxx.fs:4: Invalid memory address
                   12180: bar
                   12181: ^^^
1.79      anton    12182: Backtrace:
1.25      anton    12183: $400E664C @@
                   12184: $400E6664 foo
1.24      anton    12185: @end example
                   12186: 
                   12187: The message identifying the error is @code{Invalid memory address}.  The
                   12188: error happened when text-interpreting line 4 of the file
                   12189: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   12190: word on the line where the error happened, is pointed out (with
                   12191: @code{^^^}).
                   12192: 
                   12193: The file containing the error was included in line 1 of @file{./yyy.fs},
                   12194: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   12195: @file{yyy.fs} as command-line parameter to Gforth).
                   12196: 
                   12197: At the end of the error message you find a return stack dump that can be
                   12198: interpreted as a backtrace (possibly empty). On top you find the top of
                   12199: the return stack when the @code{throw} happened, and at the bottom you
                   12200: find the return stack entry just above the return stack of the topmost
                   12201: text interpreter.
                   12202: 
                   12203: To the right of most return stack entries you see a guess for the word
                   12204: that pushed that return stack entry as its return address. This gives a
                   12205: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   12206: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   12207: address} exception).
                   12208: 
                   12209: Note that the backtrace is not perfect: We don't know which return stack
                   12210: entries are return addresses (so we may get false positives); and in
                   12211: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   12212: address the word that pushed the return address, so for some return
                   12213: addresses you see no names in the return stack dump.
1.25      anton    12214: 
                   12215: @cindex @code{catch} and backtraces
                   12216: The return stack dump represents the return stack at the time when a
                   12217: specific @code{throw} was executed.  In programs that make use of
                   12218: @code{catch}, it is not necessarily clear which @code{throw} should be
                   12219: used for the return stack dump (e.g., consider one @code{throw} that
                   12220: indicates an error, which is caught, and during recovery another error
1.42      anton    12221: happens; which @code{throw} should be used for the stack dump?).  Gforth
1.25      anton    12222: presents the return stack dump for the first @code{throw} after the last
                   12223: executed (not returned-to) @code{catch}; this works well in the usual
                   12224: case.
                   12225: 
                   12226: @cindex @code{gforth-fast} and backtraces
                   12227: @cindex @code{gforth-fast}, difference from @code{gforth}
                   12228: @cindex backtraces with @code{gforth-fast}
                   12229: @cindex return stack dump with @code{gforth-fast}
1.79      anton    12230: @code{Gforth} is able to do a return stack dump for throws generated
1.25      anton    12231: from primitives (e.g., invalid memory address, stack empty etc.);
                   12232: @code{gforth-fast} is only able to do a return stack dump from a
                   12233: directly called @code{throw} (including @code{abort} etc.).  This is the
1.30      anton    12234: only difference (apart from a speed factor of between 1.15 (K6-2) and
1.78      anton    12235: 2 (21264)) between @code{gforth} and @code{gforth-fast}.  Given an
1.30      anton    12236: exception caused by a primitive in @code{gforth-fast}, you will
                   12237: typically see no return stack dump at all; however, if the exception is
                   12238: caught by @code{catch} (e.g., for restoring some state), and then
                   12239: @code{throw}n again, the return stack dump will be for the first such
                   12240: @code{throw}.
1.2       jwilke   12241: 
1.5       anton    12242: @c ******************************************************************
1.24      anton    12243: @node Tools, ANS conformance, Error messages, Top
1.1       anton    12244: @chapter Tools
                   12245: 
                   12246: @menu
                   12247: * ANS Report::                  Report the words used, sorted by wordset.
                   12248: @end menu
                   12249: 
                   12250: See also @ref{Emacs and Gforth}.
                   12251: 
                   12252: @node ANS Report,  , Tools, Tools
                   12253: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   12254: @cindex @file{ans-report.fs}
                   12255: @cindex report the words used in your program
                   12256: @cindex words used in your program
                   12257: 
                   12258: If you want to label a Forth program as ANS Forth Program, you must
                   12259: document which wordsets the program uses; for extension wordsets, it is
                   12260: helpful to list the words the program requires from these wordsets
                   12261: (because Forth systems are allowed to provide only some words of them).
                   12262: 
                   12263: The @file{ans-report.fs} tool makes it easy for you to determine which
                   12264: words from which wordset and which non-ANS words your application
                   12265: uses. You simply have to include @file{ans-report.fs} before loading the
                   12266: program you want to check. After loading your program, you can get the
                   12267: report with @code{print-ans-report}. A typical use is to run this as
                   12268: batch job like this:
                   12269: @example
                   12270: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   12271: @end example
                   12272: 
                   12273: The output looks like this (for @file{compat/control.fs}):
                   12274: @example
                   12275: The program uses the following words
                   12276: from CORE :
                   12277: : POSTPONE THEN ; immediate ?dup IF 0= 
                   12278: from BLOCK-EXT :
                   12279: \ 
                   12280: from FILE :
                   12281: ( 
                   12282: @end example
                   12283: 
                   12284: @subsection Caveats
                   12285: 
                   12286: Note that @file{ans-report.fs} just checks which words are used, not whether
                   12287: they are used in an ANS Forth conforming way!
                   12288: 
                   12289: Some words are defined in several wordsets in the
                   12290: standard. @file{ans-report.fs} reports them for only one of the
                   12291: wordsets, and not necessarily the one you expect. It depends on usage
                   12292: which wordset is the right one to specify. E.g., if you only use the
                   12293: compilation semantics of @code{S"}, it is a Core word; if you also use
                   12294: its interpretation semantics, it is a File word.
                   12295: 
                   12296: @c ******************************************************************
1.65      anton    12297: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1       anton    12298: @chapter ANS conformance
                   12299: @cindex ANS conformance of Gforth
                   12300: 
                   12301: To the best of our knowledge, Gforth is an
                   12302: 
                   12303: ANS Forth System
                   12304: @itemize @bullet
                   12305: @item providing the Core Extensions word set
                   12306: @item providing the Block word set
                   12307: @item providing the Block Extensions word set
                   12308: @item providing the Double-Number word set
                   12309: @item providing the Double-Number Extensions word set
                   12310: @item providing the Exception word set
                   12311: @item providing the Exception Extensions word set
                   12312: @item providing the Facility word set
1.40      anton    12313: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1       anton    12314: @item providing the File Access word set
                   12315: @item providing the File Access Extensions word set
                   12316: @item providing the Floating-Point word set
                   12317: @item providing the Floating-Point Extensions word set
                   12318: @item providing the Locals word set
                   12319: @item providing the Locals Extensions word set
                   12320: @item providing the Memory-Allocation word set
                   12321: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   12322: @item providing the Programming-Tools word set
                   12323: @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
                   12324: @item providing the Search-Order word set
                   12325: @item providing the Search-Order Extensions word set
                   12326: @item providing the String word set
                   12327: @item providing the String Extensions word set (another easy one)
                   12328: @end itemize
                   12329: 
                   12330: @cindex system documentation
                   12331: In addition, ANS Forth systems are required to document certain
                   12332: implementation choices. This chapter tries to meet these
                   12333: requirements. In many cases it gives a way to ask the system for the
                   12334: information instead of providing the information directly, in
                   12335: particular, if the information depends on the processor, the operating
                   12336: system or the installation options chosen, or if they are likely to
                   12337: change during the maintenance of Gforth.
                   12338: 
                   12339: @comment The framework for the rest has been taken from pfe.
                   12340: 
                   12341: @menu
                   12342: * The Core Words::              
                   12343: * The optional Block word set::  
                   12344: * The optional Double Number word set::  
                   12345: * The optional Exception word set::  
                   12346: * The optional Facility word set::  
                   12347: * The optional File-Access word set::  
                   12348: * The optional Floating-Point word set::  
                   12349: * The optional Locals word set::  
                   12350: * The optional Memory-Allocation word set::  
                   12351: * The optional Programming-Tools word set::  
                   12352: * The optional Search-Order word set::  
                   12353: @end menu
                   12354: 
                   12355: 
                   12356: @c =====================================================================
                   12357: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   12358: @comment  node-name,  next,  previous,  up
                   12359: @section The Core Words
                   12360: @c =====================================================================
                   12361: @cindex core words, system documentation
                   12362: @cindex system documentation, core words
                   12363: 
                   12364: @menu
                   12365: * core-idef::                   Implementation Defined Options                   
                   12366: * core-ambcond::                Ambiguous Conditions                
                   12367: * core-other::                  Other System Documentation                  
                   12368: @end menu
                   12369: 
                   12370: @c ---------------------------------------------------------------------
                   12371: @node core-idef, core-ambcond, The Core Words, The Core Words
                   12372: @subsection Implementation Defined Options
                   12373: @c ---------------------------------------------------------------------
                   12374: @cindex core words, implementation-defined options
                   12375: @cindex implementation-defined options, core words
                   12376: 
                   12377: 
                   12378: @table @i
                   12379: @item (Cell) aligned addresses:
                   12380: @cindex cell-aligned addresses
                   12381: @cindex aligned addresses
                   12382: processor-dependent. Gforth's alignment words perform natural alignment
                   12383: (e.g., an address aligned for a datum of size 8 is divisible by
                   12384: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   12385: 
                   12386: @item @code{EMIT} and non-graphic characters:
                   12387: @cindex @code{EMIT} and non-graphic characters
                   12388: @cindex non-graphic characters and @code{EMIT}
                   12389: The character is output using the C library function (actually, macro)
                   12390: @code{putc}.
                   12391: 
                   12392: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   12393: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   12394: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   12395: @cindex @code{ACCEPT}, editing
                   12396: @cindex @code{EXPECT}, editing
                   12397: This is modeled on the GNU readline library (@pxref{Readline
                   12398: Interaction, , Command Line Editing, readline, The GNU Readline
                   12399: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   12400: producing a full word completion every time you type it (instead of
1.28      crook    12401: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    12402: 
                   12403: @item character set:
                   12404: @cindex character set
                   12405: The character set of your computer and display device. Gforth is
                   12406: 8-bit-clean (but some other component in your system may make trouble).
                   12407: 
                   12408: @item Character-aligned address requirements:
                   12409: @cindex character-aligned address requirements
                   12410: installation-dependent. Currently a character is represented by a C
                   12411: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   12412: (Comments on that requested).
                   12413: 
                   12414: @item character-set extensions and matching of names:
                   12415: @cindex character-set extensions and matching of names
1.26      crook    12416: @cindex case-sensitivity for name lookup
                   12417: @cindex name lookup, case-sensitivity
                   12418: @cindex locale and case-sensitivity
1.21      crook    12419: Any character except the ASCII NUL character can be used in a
1.1       anton    12420: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47      crook    12421: matching is performed using the C library function @code{strncasecmp}, whose
1.1       anton    12422: function is probably influenced by the locale. E.g., the @code{C} locale
                   12423: does not know about accents and umlauts, so they are matched
                   12424: case-sensitively in that locale. For portability reasons it is best to
                   12425: write programs such that they work in the @code{C} locale. Then one can
                   12426: use libraries written by a Polish programmer (who might use words
                   12427: containing ISO Latin-2 encoded characters) and by a French programmer
                   12428: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   12429: funny results for some of the words (which ones, depends on the font you
                   12430: are using)). Also, the locale you prefer may not be available in other
                   12431: operating systems. Hopefully, Unicode will solve these problems one day.
                   12432: 
                   12433: @item conditions under which control characters match a space delimiter:
                   12434: @cindex space delimiters
                   12435: @cindex control characters as delimiters
                   12436: If @code{WORD} is called with the space character as a delimiter, all
                   12437: white-space characters (as identified by the C macro @code{isspace()})
                   12438: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44      crook    12439: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.79      anton    12440: like @code{PARSE} otherwise. @code{Name}, which is used by the outer
1.1       anton    12441: interpreter (aka text interpreter) by default, treats all white-space
                   12442: characters as delimiters.
                   12443: 
1.26      crook    12444: @item format of the control-flow stack:
                   12445: @cindex control-flow stack, format
                   12446: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    12447: stack item in cells is given by the constant @code{cs-item-size}. At the
                   12448: time of this writing, an item consists of a (pointer to a) locals list
                   12449: (third), an address in the code (second), and a tag for identifying the
                   12450: item (TOS). The following tags are used: @code{defstart},
                   12451: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   12452: @code{scopestart}.
                   12453: 
                   12454: @item conversion of digits > 35
                   12455: @cindex digits > 35
                   12456: The characters @code{[\]^_'} are the digits with the decimal value
                   12457: 36@minus{}41. There is no way to input many of the larger digits.
                   12458: 
                   12459: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   12460: @cindex @code{EXPECT}, display after end of input
                   12461: @cindex @code{ACCEPT}, display after end of input
                   12462: The cursor is moved to the end of the entered string. If the input is
                   12463: terminated using the @kbd{Return} key, a space is typed.
                   12464: 
                   12465: @item exception abort sequence of @code{ABORT"}:
                   12466: @cindex exception abort sequence of @code{ABORT"}
                   12467: @cindex @code{ABORT"}, exception abort sequence
                   12468: The error string is stored into the variable @code{"error} and a
                   12469: @code{-2 throw} is performed.
                   12470: 
                   12471: @item input line terminator:
                   12472: @cindex input line terminator
                   12473: @cindex line terminator on input
1.26      crook    12474: @cindex newline character on input
1.1       anton    12475: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   12476: lines. One of these characters is typically produced when you type the
                   12477: @kbd{Enter} or @kbd{Return} key.
                   12478: 
                   12479: @item maximum size of a counted string:
                   12480: @cindex maximum size of a counted string
                   12481: @cindex counted string, maximum size
                   12482: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79      anton    12483: on all platforms, but this may change.
1.1       anton    12484: 
                   12485: @item maximum size of a parsed string:
                   12486: @cindex maximum size of a parsed string
                   12487: @cindex parsed string, maximum size
                   12488: Given by the constant @code{/line}. Currently 255 characters.
                   12489: 
                   12490: @item maximum size of a definition name, in characters:
                   12491: @cindex maximum size of a definition name, in characters
                   12492: @cindex name, maximum length
                   12493: 31
                   12494: 
                   12495: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   12496: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   12497: @cindex @code{ENVIRONMENT?} string length, maximum
                   12498: 31
                   12499: 
                   12500: @item method of selecting the user input device:
                   12501: @cindex user input device, method of selecting
                   12502: The user input device is the standard input. There is currently no way to
                   12503: change it from within Gforth. However, the input can typically be
                   12504: redirected in the command line that starts Gforth.
                   12505: 
                   12506: @item method of selecting the user output device:
                   12507: @cindex user output device, method of selecting
                   12508: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    12509: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   12510: output when the user output device is a terminal, otherwise the output
                   12511: is buffered.
1.1       anton    12512: 
                   12513: @item methods of dictionary compilation:
                   12514: What are we expected to document here?
                   12515: 
                   12516: @item number of bits in one address unit:
                   12517: @cindex number of bits in one address unit
                   12518: @cindex address unit, size in bits
                   12519: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79      anton    12520: platforms.
1.1       anton    12521: 
                   12522: @item number representation and arithmetic:
                   12523: @cindex number representation and arithmetic
1.79      anton    12524: Processor-dependent. Binary two's complement on all current platforms.
1.1       anton    12525: 
                   12526: @item ranges for integer types:
                   12527: @cindex ranges for integer types
                   12528: @cindex integer types, ranges
                   12529: Installation-dependent. Make environmental queries for @code{MAX-N},
                   12530: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   12531: unsigned (and positive) types is 0. The lower bound for signed types on
                   12532: two's complement and one's complement machines machines can be computed
                   12533: by adding 1 to the upper bound.
                   12534: 
                   12535: @item read-only data space regions:
                   12536: @cindex read-only data space regions
                   12537: @cindex data-space, read-only regions
                   12538: The whole Forth data space is writable.
                   12539: 
                   12540: @item size of buffer at @code{WORD}:
                   12541: @cindex size of buffer at @code{WORD}
                   12542: @cindex @code{WORD} buffer size
                   12543: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   12544: shared with the pictured numeric output string. If overwriting
                   12545: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   12546: space, although only as much can be sensibly used as fits in a counted
                   12547: string.
                   12548: 
                   12549: @item size of one cell in address units:
                   12550: @cindex cell size
                   12551: @code{1 cells .}.
                   12552: 
                   12553: @item size of one character in address units:
                   12554: @cindex char size
1.79      anton    12555: @code{1 chars .}. 1 on all current platforms.
1.1       anton    12556: 
                   12557: @item size of the keyboard terminal buffer:
                   12558: @cindex size of the keyboard terminal buffer
                   12559: @cindex terminal buffer, size
                   12560: Varies. You can determine the size at a specific time using @code{lp@@
                   12561: tib - .}. It is shared with the locals stack and TIBs of files that
                   12562: include the current file. You can change the amount of space for TIBs
                   12563: and locals stack at Gforth startup with the command line option
                   12564: @code{-l}.
                   12565: 
                   12566: @item size of the pictured numeric output buffer:
                   12567: @cindex size of the pictured numeric output buffer
                   12568: @cindex pictured numeric output buffer, size
                   12569: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   12570: shared with @code{WORD}.
                   12571: 
                   12572: @item size of the scratch area returned by @code{PAD}:
                   12573: @cindex size of the scratch area returned by @code{PAD}
                   12574: @cindex @code{PAD} size
                   12575: The remainder of dictionary space. @code{unused pad here - - .}.
                   12576: 
                   12577: @item system case-sensitivity characteristics:
                   12578: @cindex case-sensitivity characteristics
1.26      crook    12579: Dictionary searches are case-insensitive (except in
1.1       anton    12580: @code{TABLE}s). However, as explained above under @i{character-set
                   12581: extensions}, the matching for non-ASCII characters is determined by the
                   12582: locale you are using. In the default @code{C} locale all non-ASCII
                   12583: characters are matched case-sensitively.
                   12584: 
                   12585: @item system prompt:
                   12586: @cindex system prompt
                   12587: @cindex prompt
                   12588: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   12589: 
                   12590: @item division rounding:
                   12591: @cindex division rounding
                   12592: installation dependent. @code{s" floored" environment? drop .}. We leave
                   12593: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
                   12594: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
                   12595: 
                   12596: @item values of @code{STATE} when true:
                   12597: @cindex @code{STATE} values
                   12598: -1.
                   12599: 
                   12600: @item values returned after arithmetic overflow:
                   12601: On two's complement machines, arithmetic is performed modulo
                   12602: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   12603: arithmetic (with appropriate mapping for signed types). Division by zero
                   12604: typically results in a @code{-55 throw} (Floating-point unidentified
1.80      anton    12605: fault) or @code{-10 throw} (divide by zero).
1.1       anton    12606: 
                   12607: @item whether the current definition can be found after @t{DOES>}:
                   12608: @cindex @t{DOES>}, visibility of current definition
                   12609: No.
                   12610: 
                   12611: @end table
                   12612: 
                   12613: @c ---------------------------------------------------------------------
                   12614: @node core-ambcond, core-other, core-idef, The Core Words
                   12615: @subsection Ambiguous conditions
                   12616: @c ---------------------------------------------------------------------
                   12617: @cindex core words, ambiguous conditions
                   12618: @cindex ambiguous conditions, core words
                   12619: 
                   12620: @table @i
                   12621: 
                   12622: @item a name is neither a word nor a number:
                   12623: @cindex name not found
1.26      crook    12624: @cindex undefined word
1.80      anton    12625: @code{-13 throw} (Undefined word).
1.1       anton    12626: 
                   12627: @item a definition name exceeds the maximum length allowed:
1.26      crook    12628: @cindex word name too long
1.1       anton    12629: @code{-19 throw} (Word name too long)
                   12630: 
                   12631: @item addressing a region not inside the various data spaces of the forth system:
                   12632: @cindex Invalid memory address
1.32      anton    12633: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    12634: typically readable. Accessing other addresses gives results dependent on
                   12635: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   12636: address).
                   12637: 
                   12638: @item argument type incompatible with parameter:
1.26      crook    12639: @cindex argument type mismatch
1.1       anton    12640: This is usually not caught. Some words perform checks, e.g., the control
                   12641: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   12642: mismatch).
                   12643: 
                   12644: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   12645: @cindex Interpreting a compile-only word, for @code{'} etc.
                   12646: @cindex execution token of words with undefined execution semantics
                   12647: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   12648: get an execution token for @code{compile-only-error} (which performs a
                   12649: @code{-14 throw} when executed).
                   12650: 
                   12651: @item dividing by zero:
                   12652: @cindex dividing by zero
                   12653: @cindex floating point unidentified fault, integer division
1.80      anton    12654: On some platforms, this produces a @code{-10 throw} (Division by
1.24      anton    12655: zero); on other systems, this typically results in a @code{-55 throw}
                   12656: (Floating-point unidentified fault).
1.1       anton    12657: 
                   12658: @item insufficient data stack or return stack space:
                   12659: @cindex insufficient data stack or return stack space
                   12660: @cindex stack overflow
1.26      crook    12661: @cindex address alignment exception, stack overflow
1.1       anton    12662: @cindex Invalid memory address, stack overflow
                   12663: Depending on the operating system, the installation, and the invocation
                   12664: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    12665: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   12666: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   12667: throw} (Invalid memory address) (depending on the platform and how you
                   12668: achieved the overflow) as soon as the overflow happens. If it is not
                   12669: checked, overflows typically result in mysterious illegal memory
                   12670: accesses, producing @code{-9 throw} (Invalid memory address) or
                   12671: @code{-23 throw} (Address alignment exception); they might also destroy
                   12672: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   12673: various errors in these words.
1.1       anton    12674: 
                   12675: @item insufficient space for loop control parameters:
                   12676: @cindex insufficient space for loop control parameters
1.80      anton    12677: Like other return stack overflows.
1.1       anton    12678: 
                   12679: @item insufficient space in the dictionary:
                   12680: @cindex insufficient space in the dictionary
                   12681: @cindex dictionary overflow
1.12      anton    12682: If you try to allot (either directly with @code{allot}, or indirectly
                   12683: with @code{,}, @code{create} etc.) more memory than available in the
                   12684: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   12685: to access memory beyond the end of the dictionary, the results are
                   12686: similar to stack overflows.
1.1       anton    12687: 
                   12688: @item interpreting a word with undefined interpretation semantics:
                   12689: @cindex interpreting a word with undefined interpretation semantics
                   12690: @cindex Interpreting a compile-only word
                   12691: For some words, we have defined interpretation semantics. For the
                   12692: others: @code{-14 throw} (Interpreting a compile-only word).
                   12693: 
                   12694: @item modifying the contents of the input buffer or a string literal:
                   12695: @cindex modifying the contents of the input buffer or a string literal
                   12696: These are located in writable memory and can be modified.
                   12697: 
                   12698: @item overflow of the pictured numeric output string:
                   12699: @cindex overflow of the pictured numeric output string
                   12700: @cindex pictured numeric output string, overflow
1.24      anton    12701: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    12702: 
                   12703: @item parsed string overflow:
                   12704: @cindex parsed string overflow
                   12705: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   12706: 
                   12707: @item producing a result out of range:
                   12708: @cindex result out of range
                   12709: On two's complement machines, arithmetic is performed modulo
                   12710: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   12711: arithmetic (with appropriate mapping for signed types). Division by zero
1.24      anton    12712: typically results in a @code{-10 throw} (divide by zero) or @code{-55
                   12713: throw} (floating point unidentified fault). @code{convert} and
                   12714: @code{>number} currently overflow silently.
1.1       anton    12715: 
                   12716: @item reading from an empty data or return stack:
                   12717: @cindex stack empty
                   12718: @cindex stack underflow
1.24      anton    12719: @cindex return stack underflow
1.1       anton    12720: The data stack is checked by the outer (aka text) interpreter after
                   12721: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   12722: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    12723: depending on operating system, installation, and invocation. If they are
                   12724: caught by a check, they typically result in @code{-4 throw} (Stack
                   12725: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   12726: (Invalid memory address), depending on the platform and which stack
                   12727: underflows and by how much. Note that even if the system uses checking
                   12728: (through the MMU), your program may have to underflow by a significant
                   12729: number of stack items to trigger the reaction (the reason for this is
                   12730: that the MMU, and therefore the checking, works with a page-size
                   12731: granularity).  If there is no checking, the symptoms resulting from an
                   12732: underflow are similar to those from an overflow.  Unbalanced return
1.80      anton    12733: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24      anton    12734: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   12735: throw}).
1.1       anton    12736: 
                   12737: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   12738: @cindex unexpected end of the input buffer
                   12739: @cindex zero-length string as a name
                   12740: @cindex Attempt to use zero-length string as a name
                   12741: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   12742: use zero-length string as a name). Words like @code{'} probably will not
                   12743: find what they search. Note that it is possible to create zero-length
                   12744: names with @code{nextname} (should it not?).
                   12745: 
                   12746: @item @code{>IN} greater than input buffer:
                   12747: @cindex @code{>IN} greater than input buffer
                   12748: The next invocation of a parsing word returns a string with length 0.
                   12749: 
                   12750: @item @code{RECURSE} appears after @code{DOES>}:
                   12751: @cindex @code{RECURSE} appears after @code{DOES>}
                   12752: Compiles a recursive call to the defining word, not to the defined word.
                   12753: 
                   12754: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   12755: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    12756: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    12757: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   12758: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   12759: the end of the file was reached), its source-id may be
                   12760: reused. Therefore, restoring an input source specification referencing a
                   12761: closed file may lead to unpredictable results instead of a @code{-12
                   12762: THROW}.
                   12763: 
                   12764: In the future, Gforth may be able to restore input source specifications
                   12765: from other than the current input source.
                   12766: 
                   12767: @item data space containing definitions gets de-allocated:
                   12768: @cindex data space containing definitions gets de-allocated
                   12769: Deallocation with @code{allot} is not checked. This typically results in
                   12770: memory access faults or execution of illegal instructions.
                   12771: 
                   12772: @item data space read/write with incorrect alignment:
                   12773: @cindex data space read/write with incorrect alignment
                   12774: @cindex alignment faults
1.26      crook    12775: @cindex address alignment exception
1.1       anton    12776: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    12777: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    12778: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   12779: (Invalid memory address). There are reportedly some processors with
1.12      anton    12780: alignment restrictions that do not report violations.
1.1       anton    12781: 
                   12782: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   12783: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   12784: Like other alignment errors.
                   12785: 
                   12786: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   12787: Like other stack underflows.
                   12788: 
                   12789: @item loop control parameters not available:
                   12790: @cindex loop control parameters not available
                   12791: Not checked. The counted loop words simply assume that the top of return
                   12792: stack items are loop control parameters and behave accordingly.
                   12793: 
                   12794: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   12795: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   12796: @cindex last word was headerless
                   12797: @code{abort" last word was headerless"}.
                   12798: 
                   12799: @item name not defined by @code{VALUE} used by @code{TO}:
                   12800: @cindex name not defined by @code{VALUE} used by @code{TO}
                   12801: @cindex @code{TO} on non-@code{VALUE}s
                   12802: @cindex Invalid name argument, @code{TO}
                   12803: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   12804: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   12805: 
                   12806: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   12807: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    12808: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    12809: @code{-13 throw} (Undefined word)
                   12810: 
                   12811: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   12812: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   12813: Gforth behaves as if they were of the same type. I.e., you can predict
                   12814: the behaviour by interpreting all parameters as, e.g., signed.
                   12815: 
                   12816: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   12817: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   12818: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   12819: compilation semantics of @code{TO}.
                   12820: 
                   12821: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    12822: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    12823: @cindex @code{WORD}, string overflow
                   12824: Not checked. The string will be ok, but the count will, of course,
                   12825: contain only the least significant bits of the length.
                   12826: 
                   12827: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   12828: @cindex @code{LSHIFT}, large shift counts
                   12829: @cindex @code{RSHIFT}, large shift counts
                   12830: Processor-dependent. Typical behaviours are returning 0 and using only
                   12831: the low bits of the shift count.
                   12832: 
                   12833: @item word not defined via @code{CREATE}:
                   12834: @cindex @code{>BODY} of non-@code{CREATE}d words
                   12835: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   12836: 
                   12837: @cindex @code{DOES>} of non-@code{CREATE}d words
                   12838: @code{DOES>} changes the execution semantics of the last defined word no
                   12839: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   12840: @code{CREATE , DOES>}.
                   12841: 
                   12842: @item words improperly used outside @code{<#} and @code{#>}:
                   12843: Not checked. As usual, you can expect memory faults.
                   12844: 
                   12845: @end table
                   12846: 
                   12847: 
                   12848: @c ---------------------------------------------------------------------
                   12849: @node core-other,  , core-ambcond, The Core Words
                   12850: @subsection Other system documentation
                   12851: @c ---------------------------------------------------------------------
                   12852: @cindex other system documentation, core words
                   12853: @cindex core words, other system documentation
                   12854: 
                   12855: @table @i
                   12856: @item nonstandard words using @code{PAD}:
                   12857: @cindex @code{PAD} use by nonstandard words
                   12858: None.
                   12859: 
                   12860: @item operator's terminal facilities available:
                   12861: @cindex operator's terminal facilities available
1.80      anton    12862: After processing the OS's command line, Gforth goes into interactive mode,
1.1       anton    12863: and you can give commands to Gforth interactively. The actual facilities
                   12864: available depend on how you invoke Gforth.
                   12865: 
                   12866: @item program data space available:
                   12867: @cindex program data space available
                   12868: @cindex data space available
                   12869: @code{UNUSED .} gives the remaining dictionary space. The total
                   12870: dictionary space can be specified with the @code{-m} switch
                   12871: (@pxref{Invoking Gforth}) when Gforth starts up.
                   12872: 
                   12873: @item return stack space available:
                   12874: @cindex return stack space available
                   12875: You can compute the total return stack space in cells with
                   12876: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   12877: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   12878: 
                   12879: @item stack space available:
                   12880: @cindex stack space available
                   12881: You can compute the total data stack space in cells with
                   12882: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   12883: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   12884: 
                   12885: @item system dictionary space required, in address units:
                   12886: @cindex system dictionary space required, in address units
                   12887: Type @code{here forthstart - .} after startup. At the time of this
                   12888: writing, this gives 80080 (bytes) on a 32-bit system.
                   12889: @end table
                   12890: 
                   12891: 
                   12892: @c =====================================================================
                   12893: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   12894: @section The optional Block word set
                   12895: @c =====================================================================
                   12896: @cindex system documentation, block words
                   12897: @cindex block words, system documentation
                   12898: 
                   12899: @menu
                   12900: * block-idef::                  Implementation Defined Options
                   12901: * block-ambcond::               Ambiguous Conditions               
                   12902: * block-other::                 Other System Documentation                 
                   12903: @end menu
                   12904: 
                   12905: 
                   12906: @c ---------------------------------------------------------------------
                   12907: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   12908: @subsection Implementation Defined Options
                   12909: @c ---------------------------------------------------------------------
                   12910: @cindex implementation-defined options, block words
                   12911: @cindex block words, implementation-defined options
                   12912: 
                   12913: @table @i
                   12914: @item the format for display by @code{LIST}:
                   12915: @cindex @code{LIST} display format
                   12916: First the screen number is displayed, then 16 lines of 64 characters,
                   12917: each line preceded by the line number.
                   12918: 
                   12919: @item the length of a line affected by @code{\}:
                   12920: @cindex length of a line affected by @code{\}
                   12921: @cindex @code{\}, line length in blocks
                   12922: 64 characters.
                   12923: @end table
                   12924: 
                   12925: 
                   12926: @c ---------------------------------------------------------------------
                   12927: @node block-ambcond, block-other, block-idef, The optional Block word set
                   12928: @subsection Ambiguous conditions
                   12929: @c ---------------------------------------------------------------------
                   12930: @cindex block words, ambiguous conditions
                   12931: @cindex ambiguous conditions, block words
                   12932: 
                   12933: @table @i
                   12934: @item correct block read was not possible:
                   12935: @cindex block read not possible
                   12936: Typically results in a @code{throw} of some OS-derived value (between
                   12937: -512 and -2048). If the blocks file was just not long enough, blanks are
                   12938: supplied for the missing portion.
                   12939: 
                   12940: @item I/O exception in block transfer:
                   12941: @cindex I/O exception in block transfer
                   12942: @cindex block transfer, I/O exception
                   12943: Typically results in a @code{throw} of some OS-derived value (between
                   12944: -512 and -2048).
                   12945: 
                   12946: @item invalid block number:
                   12947: @cindex invalid block number
                   12948: @cindex block number invalid
                   12949: @code{-35 throw} (Invalid block number)
                   12950: 
                   12951: @item a program directly alters the contents of @code{BLK}:
                   12952: @cindex @code{BLK}, altering @code{BLK}
                   12953: The input stream is switched to that other block, at the same
                   12954: position. If the storing to @code{BLK} happens when interpreting
                   12955: non-block input, the system will get quite confused when the block ends.
                   12956: 
                   12957: @item no current block buffer for @code{UPDATE}:
                   12958: @cindex @code{UPDATE}, no current block buffer
                   12959: @code{UPDATE} has no effect.
                   12960: 
                   12961: @end table
                   12962: 
                   12963: @c ---------------------------------------------------------------------
                   12964: @node block-other,  , block-ambcond, The optional Block word set
                   12965: @subsection Other system documentation
                   12966: @c ---------------------------------------------------------------------
                   12967: @cindex other system documentation, block words
                   12968: @cindex block words, other system documentation
                   12969: 
                   12970: @table @i
                   12971: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   12972: No restrictions (yet).
                   12973: 
                   12974: @item the number of blocks available for source and data:
                   12975: depends on your disk space.
                   12976: 
                   12977: @end table
                   12978: 
                   12979: 
                   12980: @c =====================================================================
                   12981: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   12982: @section The optional Double Number word set
                   12983: @c =====================================================================
                   12984: @cindex system documentation, double words
                   12985: @cindex double words, system documentation
                   12986: 
                   12987: @menu
                   12988: * double-ambcond::              Ambiguous Conditions              
                   12989: @end menu
                   12990: 
                   12991: 
                   12992: @c ---------------------------------------------------------------------
                   12993: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   12994: @subsection Ambiguous conditions
                   12995: @c ---------------------------------------------------------------------
                   12996: @cindex double words, ambiguous conditions
                   12997: @cindex ambiguous conditions, double words
                   12998: 
                   12999: @table @i
1.29      crook    13000: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   13001: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   13002: The least significant cell of @i{d} is produced.
1.1       anton    13003: 
                   13004: @end table
                   13005: 
                   13006: 
                   13007: @c =====================================================================
                   13008: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   13009: @section The optional Exception word set
                   13010: @c =====================================================================
                   13011: @cindex system documentation, exception words
                   13012: @cindex exception words, system documentation
                   13013: 
                   13014: @menu
                   13015: * exception-idef::              Implementation Defined Options              
                   13016: @end menu
                   13017: 
                   13018: 
                   13019: @c ---------------------------------------------------------------------
                   13020: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   13021: @subsection Implementation Defined Options
                   13022: @c ---------------------------------------------------------------------
                   13023: @cindex implementation-defined options, exception words
                   13024: @cindex exception words, implementation-defined options
                   13025: 
                   13026: @table @i
                   13027: @item @code{THROW}-codes used in the system:
                   13028: @cindex @code{THROW}-codes used in the system
                   13029: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    13030: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    13031: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   13032: allocation operations). The mapping from OS error numbers to throw codes
                   13033: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   13034: undefined OS errors produce a message with a strange number; e.g.,
                   13035: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   13036: @end table
                   13037: 
                   13038: @c =====================================================================
                   13039: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   13040: @section The optional Facility word set
                   13041: @c =====================================================================
                   13042: @cindex system documentation, facility words
                   13043: @cindex facility words, system documentation
                   13044: 
                   13045: @menu
                   13046: * facility-idef::               Implementation Defined Options               
                   13047: * facility-ambcond::            Ambiguous Conditions            
                   13048: @end menu
                   13049: 
                   13050: 
                   13051: @c ---------------------------------------------------------------------
                   13052: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   13053: @subsection Implementation Defined Options
                   13054: @c ---------------------------------------------------------------------
                   13055: @cindex implementation-defined options, facility words
                   13056: @cindex facility words, implementation-defined options
                   13057: 
                   13058: @table @i
                   13059: @item encoding of keyboard events (@code{EKEY}):
                   13060: @cindex keyboard events, encoding in @code{EKEY}
                   13061: @cindex @code{EKEY}, encoding of keyboard events
1.40      anton    13062: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41      anton    13063: Other keys are encoded with the constants @code{k-left}, @code{k-right},
                   13064: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
                   13065: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
                   13066: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40      anton    13067: 
1.1       anton    13068: 
                   13069: @item duration of a system clock tick:
                   13070: @cindex duration of a system clock tick
                   13071: @cindex clock tick duration
                   13072: System dependent. With respect to @code{MS}, the time is specified in
                   13073: microseconds. How well the OS and the hardware implement this, is
                   13074: another question.
                   13075: 
                   13076: @item repeatability to be expected from the execution of @code{MS}:
                   13077: @cindex repeatability to be expected from the execution of @code{MS}
                   13078: @cindex @code{MS}, repeatability to be expected
                   13079: System dependent. On Unix, a lot depends on load. If the system is
                   13080: lightly loaded, and the delay is short enough that Gforth does not get
                   13081: swapped out, the performance should be acceptable. Under MS-DOS and
                   13082: other single-tasking systems, it should be good.
                   13083: 
                   13084: @end table
                   13085: 
                   13086: 
                   13087: @c ---------------------------------------------------------------------
                   13088: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   13089: @subsection Ambiguous conditions
                   13090: @c ---------------------------------------------------------------------
                   13091: @cindex facility words, ambiguous conditions
                   13092: @cindex ambiguous conditions, facility words
                   13093: 
                   13094: @table @i
                   13095: @item @code{AT-XY} can't be performed on user output device:
                   13096: @cindex @code{AT-XY} can't be performed on user output device
                   13097: Largely terminal dependent. No range checks are done on the arguments.
                   13098: No errors are reported. You may see some garbage appearing, you may see
                   13099: simply nothing happen.
                   13100: 
                   13101: @end table
                   13102: 
                   13103: 
                   13104: @c =====================================================================
                   13105: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   13106: @section The optional File-Access word set
                   13107: @c =====================================================================
                   13108: @cindex system documentation, file words
                   13109: @cindex file words, system documentation
                   13110: 
                   13111: @menu
                   13112: * file-idef::                   Implementation Defined Options
                   13113: * file-ambcond::                Ambiguous Conditions                
                   13114: @end menu
                   13115: 
                   13116: @c ---------------------------------------------------------------------
                   13117: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   13118: @subsection Implementation Defined Options
                   13119: @c ---------------------------------------------------------------------
                   13120: @cindex implementation-defined options, file words
                   13121: @cindex file words, implementation-defined options
                   13122: 
                   13123: @table @i
                   13124: @item file access methods used:
                   13125: @cindex file access methods used
                   13126: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   13127: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   13128: @code{wb}): The file is cleared, if it exists, and created, if it does
                   13129: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   13130: @code{create-file} creates a file with 666 permissions modified by your
                   13131: umask.
                   13132: 
                   13133: @item file exceptions:
                   13134: @cindex file exceptions
                   13135: The file words do not raise exceptions (except, perhaps, memory access
                   13136: faults when you pass illegal addresses or file-ids).
                   13137: 
                   13138: @item file line terminator:
                   13139: @cindex file line terminator
                   13140: System-dependent. Gforth uses C's newline character as line
                   13141: terminator. What the actual character code(s) of this are is
                   13142: system-dependent.
                   13143: 
                   13144: @item file name format:
                   13145: @cindex file name format
                   13146: System dependent. Gforth just uses the file name format of your OS.
                   13147: 
                   13148: @item information returned by @code{FILE-STATUS}:
                   13149: @cindex @code{FILE-STATUS}, returned information
                   13150: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   13151: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   13152: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   13153: along with the returned mode.
                   13154: 
                   13155: @item input file state after an exception when including source:
                   13156: @cindex exception when including source
                   13157: All files that are left via the exception are closed.
                   13158: 
1.29      crook    13159: @item @i{ior} values and meaning:
                   13160: @cindex @i{ior} values and meaning
1.68      anton    13161: @cindex @i{wior} values and meaning
1.29      crook    13162: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    13163: intended as throw codes. They typically are in the range
                   13164: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    13165: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    13166: 
                   13167: @item maximum depth of file input nesting:
                   13168: @cindex maximum depth of file input nesting
                   13169: @cindex file input nesting, maximum depth
                   13170: limited by the amount of return stack, locals/TIB stack, and the number
                   13171: of open files available. This should not give you troubles.
                   13172: 
                   13173: @item maximum size of input line:
                   13174: @cindex maximum size of input line
                   13175: @cindex input line size, maximum
                   13176: @code{/line}. Currently 255.
                   13177: 
                   13178: @item methods of mapping block ranges to files:
                   13179: @cindex mapping block ranges to files
                   13180: @cindex files containing blocks
                   13181: @cindex blocks in files
                   13182: By default, blocks are accessed in the file @file{blocks.fb} in the
                   13183: current working directory. The file can be switched with @code{USE}.
                   13184: 
                   13185: @item number of string buffers provided by @code{S"}:
                   13186: @cindex @code{S"}, number of string buffers
                   13187: 1
                   13188: 
                   13189: @item size of string buffer used by @code{S"}:
                   13190: @cindex @code{S"}, size of string buffer
                   13191: @code{/line}. currently 255.
                   13192: 
                   13193: @end table
                   13194: 
                   13195: @c ---------------------------------------------------------------------
                   13196: @node file-ambcond,  , file-idef, The optional File-Access word set
                   13197: @subsection Ambiguous conditions
                   13198: @c ---------------------------------------------------------------------
                   13199: @cindex file words, ambiguous conditions
                   13200: @cindex ambiguous conditions, file words
                   13201: 
                   13202: @table @i
                   13203: @item attempting to position a file outside its boundaries:
                   13204: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   13205: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   13206: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   13207: 
                   13208: @item attempting to read from file positions not yet written:
                   13209: @cindex reading from file positions not yet written
                   13210: End-of-file, i.e., zero characters are read and no error is reported.
                   13211: 
1.29      crook    13212: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   13213: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    13214: An appropriate exception may be thrown, but a memory fault or other
                   13215: problem is more probable.
                   13216: 
1.29      crook    13217: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   13218: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   13219: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   13220: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    13221: thrown.
                   13222: 
                   13223: @item named file cannot be opened (@code{INCLUDED}):
                   13224: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    13225: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    13226: 
                   13227: @item requesting an unmapped block number:
                   13228: @cindex unmapped block numbers
                   13229: There are no unmapped legal block numbers. On some operating systems,
                   13230: writing a block with a large number may overflow the file system and
                   13231: have an error message as consequence.
                   13232: 
                   13233: @item using @code{source-id} when @code{blk} is non-zero:
                   13234: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   13235: @code{source-id} performs its function. Typically it will give the id of
                   13236: the source which loaded the block. (Better ideas?)
                   13237: 
                   13238: @end table
                   13239: 
                   13240: 
                   13241: @c =====================================================================
                   13242: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   13243: @section The optional Floating-Point word set
                   13244: @c =====================================================================
                   13245: @cindex system documentation, floating-point words
                   13246: @cindex floating-point words, system documentation
                   13247: 
                   13248: @menu
                   13249: * floating-idef::               Implementation Defined Options
                   13250: * floating-ambcond::            Ambiguous Conditions            
                   13251: @end menu
                   13252: 
                   13253: 
                   13254: @c ---------------------------------------------------------------------
                   13255: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   13256: @subsection Implementation Defined Options
                   13257: @c ---------------------------------------------------------------------
                   13258: @cindex implementation-defined options, floating-point words
                   13259: @cindex floating-point words, implementation-defined options
                   13260: 
                   13261: @table @i
                   13262: @item format and range of floating point numbers:
                   13263: @cindex format and range of floating point numbers
                   13264: @cindex floating point numbers, format and range
                   13265: System-dependent; the @code{double} type of C.
                   13266: 
1.29      crook    13267: @item results of @code{REPRESENT} when @i{float} is out of range:
                   13268: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    13269: System dependent; @code{REPRESENT} is implemented using the C library
                   13270: function @code{ecvt()} and inherits its behaviour in this respect.
                   13271: 
                   13272: @item rounding or truncation of floating-point numbers:
                   13273: @cindex rounding of floating-point numbers
                   13274: @cindex truncation of floating-point numbers
                   13275: @cindex floating-point numbers, rounding or truncation
                   13276: System dependent; the rounding behaviour is inherited from the hosting C
                   13277: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   13278: nearest, and break ties by rounding to even (i.e., such that the last
                   13279: bit of the mantissa is 0).
                   13280: 
                   13281: @item size of floating-point stack:
                   13282: @cindex floating-point stack size
                   13283: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   13284: the floating-point stack (in floats). You can specify this on startup
                   13285: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   13286: 
                   13287: @item width of floating-point stack:
                   13288: @cindex floating-point stack width 
                   13289: @code{1 floats}.
                   13290: 
                   13291: @end table
                   13292: 
                   13293: 
                   13294: @c ---------------------------------------------------------------------
                   13295: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   13296: @subsection Ambiguous conditions
                   13297: @c ---------------------------------------------------------------------
                   13298: @cindex floating-point words, ambiguous conditions
                   13299: @cindex ambiguous conditions, floating-point words
                   13300: 
                   13301: @table @i
                   13302: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   13303: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   13304: System-dependent. Typically results in a @code{-23 THROW} like other
                   13305: alignment violations.
                   13306: 
                   13307: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   13308: @cindex @code{f@@} used with an address that is not float aligned
                   13309: @cindex @code{f!} used with an address that is not float aligned
                   13310: System-dependent. Typically results in a @code{-23 THROW} like other
                   13311: alignment violations.
                   13312: 
                   13313: @item floating-point result out of range:
                   13314: @cindex floating-point result out of range
1.80      anton    13315: System-dependent. Can result in a @code{-43 throw} (floating point
                   13316: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
                   13317: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1       anton    13318: unidentified fault), or can produce a special value representing, e.g.,
                   13319: Infinity.
                   13320: 
                   13321: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   13322: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   13323: System-dependent. Typically results in an alignment fault like other
                   13324: alignment violations.
                   13325: 
1.35      anton    13326: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   13327: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    13328: The floating-point number is converted into decimal nonetheless.
                   13329: 
                   13330: @item Both arguments are equal to zero (@code{FATAN2}):
                   13331: @cindex @code{FATAN2}, both arguments are equal to zero
                   13332: System-dependent. @code{FATAN2} is implemented using the C library
                   13333: function @code{atan2()}.
                   13334: 
1.29      crook    13335: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   13336: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   13337: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    13338: because of small errors and the tan will be a very large (or very small)
                   13339: but finite number.
                   13340: 
1.29      crook    13341: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   13342: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    13343: The result is rounded to the nearest float.
                   13344: 
                   13345: @item dividing by zero:
                   13346: @cindex dividing by zero, floating-point
                   13347: @cindex floating-point dividing by zero
                   13348: @cindex floating-point unidentified fault, FP divide-by-zero
1.80      anton    13349: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
                   13350: (floating point divide by zero) or @code{-55 throw} (Floating-point
                   13351: unidentified fault).
1.1       anton    13352: 
                   13353: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   13354: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   13355: System dependent. On IEEE-FP based systems the number is converted into
                   13356: an infinity.
                   13357: 
1.29      crook    13358: @item @i{float}<1 (@code{FACOSH}):
                   13359: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    13360: @cindex floating-point unidentified fault, @code{FACOSH}
1.80      anton    13361: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1       anton    13362: 
1.29      crook    13363: @item @i{float}=<-1 (@code{FLNP1}):
                   13364: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    13365: @cindex floating-point unidentified fault, @code{FLNP1}
1.80      anton    13366: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   13367: negative infinity for @i{float}=-1).
1.1       anton    13368: 
1.29      crook    13369: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   13370: @cindex @code{FLN}, @i{float}=<0
                   13371: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    13372: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80      anton    13373: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   13374: negative infinity for @i{float}=0).
1.1       anton    13375: 
1.29      crook    13376: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   13377: @cindex @code{FASINH}, @i{float}<0
                   13378: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    13379: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80      anton    13380: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
                   13381: @code{fasinh} some platforms produce a NaN, others a number (bug in the
                   13382: C library?).
1.1       anton    13383: 
1.29      crook    13384: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   13385: @cindex @code{FACOS}, |@i{float}|>1
                   13386: @cindex @code{FASIN}, |@i{float}|>1
                   13387: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    13388: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80      anton    13389: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1       anton    13390: 
1.29      crook    13391: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   13392: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    13393: @cindex floating-point unidentified fault, @code{F>D}
1.80      anton    13394: Platform-dependent; typically, some double number is produced and no
                   13395: error is reported.
1.1       anton    13396: 
                   13397: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   13398: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80      anton    13399: @code{Precision} characters of the numeric output area are used.  If
                   13400: @code{precision} is too high, these words will smash the data or code
                   13401: close to @code{here}.
1.1       anton    13402: @end table
                   13403: 
                   13404: @c =====================================================================
                   13405: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   13406: @section The optional Locals word set
                   13407: @c =====================================================================
                   13408: @cindex system documentation, locals words
                   13409: @cindex locals words, system documentation
                   13410: 
                   13411: @menu
                   13412: * locals-idef::                 Implementation Defined Options                 
                   13413: * locals-ambcond::              Ambiguous Conditions              
                   13414: @end menu
                   13415: 
                   13416: 
                   13417: @c ---------------------------------------------------------------------
                   13418: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   13419: @subsection Implementation Defined Options
                   13420: @c ---------------------------------------------------------------------
                   13421: @cindex implementation-defined options, locals words
                   13422: @cindex locals words, implementation-defined options
                   13423: 
                   13424: @table @i
                   13425: @item maximum number of locals in a definition:
                   13426: @cindex maximum number of locals in a definition
                   13427: @cindex locals, maximum number in a definition
                   13428: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   13429: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   13430: characters. The number of locals in a definition is bounded by the size
                   13431: of locals-buffer, which contains the names of the locals.
                   13432: 
                   13433: @end table
                   13434: 
                   13435: 
                   13436: @c ---------------------------------------------------------------------
                   13437: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   13438: @subsection Ambiguous conditions
                   13439: @c ---------------------------------------------------------------------
                   13440: @cindex locals words, ambiguous conditions
                   13441: @cindex ambiguous conditions, locals words
                   13442: 
                   13443: @table @i
                   13444: @item executing a named local in interpretation state:
                   13445: @cindex local in interpretation state
                   13446: @cindex Interpreting a compile-only word, for a local
                   13447: Locals have no interpretation semantics. If you try to perform the
                   13448: interpretation semantics, you will get a @code{-14 throw} somewhere
                   13449: (Interpreting a compile-only word). If you perform the compilation
                   13450: semantics, the locals access will be compiled (irrespective of state).
                   13451: 
1.29      crook    13452: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    13453: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   13454: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   13455: @cindex Invalid name argument, @code{TO}
                   13456: @code{-32 throw} (Invalid name argument)
                   13457: 
                   13458: @end table
                   13459: 
                   13460: 
                   13461: @c =====================================================================
                   13462: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   13463: @section The optional Memory-Allocation word set
                   13464: @c =====================================================================
                   13465: @cindex system documentation, memory-allocation words
                   13466: @cindex memory-allocation words, system documentation
                   13467: 
                   13468: @menu
                   13469: * memory-idef::                 Implementation Defined Options                 
                   13470: @end menu
                   13471: 
                   13472: 
                   13473: @c ---------------------------------------------------------------------
                   13474: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   13475: @subsection Implementation Defined Options
                   13476: @c ---------------------------------------------------------------------
                   13477: @cindex implementation-defined options, memory-allocation words
                   13478: @cindex memory-allocation words, implementation-defined options
                   13479: 
                   13480: @table @i
1.29      crook    13481: @item values and meaning of @i{ior}:
                   13482: @cindex  @i{ior} values and meaning
                   13483: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    13484: intended as throw codes. They typically are in the range
                   13485: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    13486: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    13487: 
                   13488: @end table
                   13489: 
                   13490: @c =====================================================================
                   13491: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   13492: @section The optional Programming-Tools word set
                   13493: @c =====================================================================
                   13494: @cindex system documentation, programming-tools words
                   13495: @cindex programming-tools words, system documentation
                   13496: 
                   13497: @menu
                   13498: * programming-idef::            Implementation Defined Options            
                   13499: * programming-ambcond::         Ambiguous Conditions         
                   13500: @end menu
                   13501: 
                   13502: 
                   13503: @c ---------------------------------------------------------------------
                   13504: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   13505: @subsection Implementation Defined Options
                   13506: @c ---------------------------------------------------------------------
                   13507: @cindex implementation-defined options, programming-tools words
                   13508: @cindex programming-tools words, implementation-defined options
                   13509: 
                   13510: @table @i
                   13511: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   13512: @cindex @code{;CODE} ending sequence
                   13513: @cindex @code{CODE} ending sequence
                   13514: @code{END-CODE}
                   13515: 
                   13516: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   13517: @cindex @code{;CODE}, processing input
                   13518: @cindex @code{CODE}, processing input
                   13519: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   13520: the input is processed by the text interpreter, (starting) in interpret
                   13521: state.
                   13522: 
                   13523: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   13524: @cindex @code{ASSEMBLER}, search order capability
                   13525: The ANS Forth search order word set.
                   13526: 
                   13527: @item source and format of display by @code{SEE}:
                   13528: @cindex @code{SEE}, source and format of output
1.80      anton    13529: The source for @code{see} is the executable code used by the inner
1.1       anton    13530: interpreter.  The current @code{see} tries to output Forth source code
1.80      anton    13531: (and on some platforms, assembly code for primitives) as well as
                   13532: possible.
1.1       anton    13533: 
                   13534: @end table
                   13535: 
                   13536: @c ---------------------------------------------------------------------
                   13537: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   13538: @subsection Ambiguous conditions
                   13539: @c ---------------------------------------------------------------------
                   13540: @cindex programming-tools words, ambiguous conditions
                   13541: @cindex ambiguous conditions, programming-tools words
                   13542: 
                   13543: @table @i
                   13544: 
1.21      crook    13545: @item deleting the compilation word list (@code{FORGET}):
                   13546: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    13547: Not implemented (yet).
                   13548: 
1.29      crook    13549: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   13550: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   13551: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    13552: @cindex control-flow stack underflow
                   13553: This typically results in an @code{abort"} with a descriptive error
                   13554: message (may change into a @code{-22 throw} (Control structure mismatch)
                   13555: in the future). You may also get a memory access error. If you are
                   13556: unlucky, this ambiguous condition is not caught.
                   13557: 
1.29      crook    13558: @item @i{name} can't be found (@code{FORGET}):
                   13559: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    13560: Not implemented (yet).
                   13561: 
1.29      crook    13562: @item @i{name} not defined via @code{CREATE}:
                   13563: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    13564: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   13565: the execution semantics of the last defined word no matter how it was
                   13566: defined.
                   13567: 
                   13568: @item @code{POSTPONE} applied to @code{[IF]}:
                   13569: @cindex @code{POSTPONE} applied to @code{[IF]}
                   13570: @cindex @code{[IF]} and @code{POSTPONE}
                   13571: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   13572: equivalent to @code{[IF]}.
                   13573: 
                   13574: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   13575: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   13576: Continue in the same state of conditional compilation in the next outer
                   13577: input source. Currently there is no warning to the user about this.
                   13578: 
                   13579: @item removing a needed definition (@code{FORGET}):
                   13580: @cindex @code{FORGET}, removing a needed definition
                   13581: Not implemented (yet).
                   13582: 
                   13583: @end table
                   13584: 
                   13585: 
                   13586: @c =====================================================================
                   13587: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   13588: @section The optional Search-Order word set
                   13589: @c =====================================================================
                   13590: @cindex system documentation, search-order words
                   13591: @cindex search-order words, system documentation
                   13592: 
                   13593: @menu
                   13594: * search-idef::                 Implementation Defined Options                 
                   13595: * search-ambcond::              Ambiguous Conditions              
                   13596: @end menu
                   13597: 
                   13598: 
                   13599: @c ---------------------------------------------------------------------
                   13600: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   13601: @subsection Implementation Defined Options
                   13602: @c ---------------------------------------------------------------------
                   13603: @cindex implementation-defined options, search-order words
                   13604: @cindex search-order words, implementation-defined options
                   13605: 
                   13606: @table @i
                   13607: @item maximum number of word lists in search order:
                   13608: @cindex maximum number of word lists in search order
                   13609: @cindex search order, maximum depth
                   13610: @code{s" wordlists" environment? drop .}. Currently 16.
                   13611: 
                   13612: @item minimum search order:
                   13613: @cindex minimum search order
                   13614: @cindex search order, minimum
                   13615: @code{root root}.
                   13616: 
                   13617: @end table
                   13618: 
                   13619: @c ---------------------------------------------------------------------
                   13620: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   13621: @subsection Ambiguous conditions
                   13622: @c ---------------------------------------------------------------------
                   13623: @cindex search-order words, ambiguous conditions
                   13624: @cindex ambiguous conditions, search-order words
                   13625: 
                   13626: @table @i
1.21      crook    13627: @item changing the compilation word list (during compilation):
                   13628: @cindex changing the compilation word list (during compilation)
                   13629: @cindex compilation word list, change before definition ends
                   13630: The word is entered into the word list that was the compilation word list
1.1       anton    13631: at the start of the definition. Any changes to the name field (e.g.,
                   13632: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
                   13633: are applied to the latest defined word (as reported by @code{last} or
1.21      crook    13634: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1       anton    13635: 
                   13636: @item search order empty (@code{previous}):
                   13637: @cindex @code{previous}, search order empty
1.26      crook    13638: @cindex vocstack empty, @code{previous}
1.1       anton    13639: @code{abort" Vocstack empty"}.
                   13640: 
                   13641: @item too many word lists in search order (@code{also}):
                   13642: @cindex @code{also}, too many word lists in search order
1.26      crook    13643: @cindex vocstack full, @code{also}
1.1       anton    13644: @code{abort" Vocstack full"}.
                   13645: 
                   13646: @end table
                   13647: 
                   13648: @c ***************************************************************
1.65      anton    13649: @node Standard vs Extensions, Model, ANS conformance, Top
                   13650: @chapter Should I use Gforth extensions?
                   13651: @cindex Gforth extensions
                   13652: 
                   13653: As you read through the rest of this manual, you will see documentation
                   13654: for @i{Standard} words, and documentation for some appealing Gforth
                   13655: @i{extensions}. You might ask yourself the question: @i{``Should I
                   13656: restrict myself to the standard, or should I use the extensions?''}
                   13657: 
                   13658: The answer depends on the goals you have for the program you are working
                   13659: on:
                   13660: 
                   13661: @itemize @bullet
                   13662: 
                   13663: @item Is it just for yourself or do you want to share it with others?
                   13664: 
                   13665: @item
                   13666: If you want to share it, do the others all use Gforth?
                   13667: 
                   13668: @item
                   13669: If it is just for yourself, do you want to restrict yourself to Gforth?
                   13670: 
                   13671: @end itemize
                   13672: 
                   13673: If restricting the program to Gforth is ok, then there is no reason not
                   13674: to use extensions.  It is still a good idea to keep to the standard
                   13675: where it is easy, in case you want to reuse these parts in another
                   13676: program that you want to be portable.
                   13677: 
                   13678: If you want to be able to port the program to other Forth systems, there
                   13679: are the following points to consider:
                   13680: 
                   13681: @itemize @bullet
                   13682: 
                   13683: @item
                   13684: Most Forth systems that are being maintained support the ANS Forth
                   13685: standard.  So if your program complies with the standard, it will be
                   13686: portable among many systems.
                   13687: 
                   13688: @item
                   13689: A number of the Gforth extensions can be implemented in ANS Forth using
                   13690: public-domain files provided in the @file{compat/} directory. These are
                   13691: mentioned in the text in passing.  There is no reason not to use these
                   13692: extensions, your program will still be ANS Forth compliant; just include
                   13693: the appropriate compat files with your program.
                   13694: 
                   13695: @item
                   13696: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                   13697: analyse your program and determine what non-Standard words it relies
                   13698: upon.  However, it does not check whether you use standard words in a
                   13699: non-standard way.
                   13700: 
                   13701: @item
                   13702: Some techniques are not standardized by ANS Forth, and are hard or
                   13703: impossible to implement in a standard way, but can be implemented in
                   13704: most Forth systems easily, and usually in similar ways (e.g., accessing
                   13705: word headers).  Forth has a rich historical precedent for programmers
                   13706: taking advantage of implementation-dependent features of their tools
                   13707: (for example, relying on a knowledge of the dictionary
                   13708: structure). Sometimes these techniques are necessary to extract every
                   13709: last bit of performance from the hardware, sometimes they are just a
                   13710: programming shorthand.
                   13711: 
                   13712: @item
                   13713: Does using a Gforth extension save more work than the porting this part
                   13714: to other Forth systems (if any) will cost?
                   13715: 
                   13716: @item
                   13717: Is the additional functionality worth the reduction in portability and
                   13718: the additional porting problems?
                   13719: 
                   13720: @end itemize
                   13721: 
                   13722: In order to perform these consideratios, you need to know what's
                   13723: standard and what's not.  This manual generally states if something is
1.81      anton    13724: non-standard, but the authoritative source is the
                   13725: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65      anton    13726: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
                   13727: into the thought processes of the technical committee.
                   13728: 
                   13729: Note also that portability between Forth systems is not the only
                   13730: portability issue; there is also the issue of portability between
                   13731: different platforms (processor/OS combinations).
                   13732: 
                   13733: @c ***************************************************************
                   13734: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1       anton    13735: @chapter Model
                   13736: 
                   13737: This chapter has yet to be written. It will contain information, on
                   13738: which internal structures you can rely.
                   13739: 
                   13740: @c ***************************************************************
                   13741: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   13742: @chapter Integrating Gforth into C programs
                   13743: 
                   13744: This is not yet implemented.
                   13745: 
                   13746: Several people like to use Forth as scripting language for applications
                   13747: that are otherwise written in C, C++, or some other language.
                   13748: 
                   13749: The Forth system ATLAST provides facilities for embedding it into
                   13750: applications; unfortunately it has several disadvantages: most
                   13751: importantly, it is not based on ANS Forth, and it is apparently dead
                   13752: (i.e., not developed further and not supported). The facilities
1.21      crook    13753: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    13754: making the switch should not be hard.
                   13755: 
                   13756: We also tried to design the interface such that it can easily be
                   13757: implemented by other Forth systems, so that we may one day arrive at a
                   13758: standardized interface. Such a standard interface would allow you to
                   13759: replace the Forth system without having to rewrite C code.
                   13760: 
                   13761: You embed the Gforth interpreter by linking with the library
                   13762: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   13763: global symbols in this library that belong to the interface, have the
                   13764: prefix @code{forth_}. (Global symbols that are used internally have the
                   13765: prefix @code{gforth_}).
                   13766: 
                   13767: You can include the declarations of Forth types and the functions and
                   13768: variables of the interface with @code{#include <forth.h>}.
                   13769: 
                   13770: Types.
                   13771: 
                   13772: Variables.
                   13773: 
                   13774: Data and FP Stack pointer. Area sizes.
                   13775: 
                   13776: functions.
                   13777: 
                   13778: forth_init(imagefile)
                   13779: forth_evaluate(string) exceptions?
                   13780: forth_goto(address) (or forth_execute(xt)?)
                   13781: forth_continue() (a corountining mechanism)
                   13782: 
                   13783: Adding primitives.
                   13784: 
                   13785: No checking.
                   13786: 
                   13787: Signals?
                   13788: 
                   13789: Accessing the Stacks
                   13790: 
1.26      crook    13791: @c ******************************************************************
1.1       anton    13792: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   13793: @chapter Emacs and Gforth
                   13794: @cindex Emacs and Gforth
                   13795: 
                   13796: @cindex @file{gforth.el}
                   13797: @cindex @file{forth.el}
                   13798: @cindex Rydqvist, Goran
                   13799: @cindex comment editing commands
                   13800: @cindex @code{\}, editing with Emacs
                   13801: @cindex debug tracer editing commands
                   13802: @cindex @code{~~}, removal with Emacs
                   13803: @cindex Forth mode in Emacs
                   13804: Gforth comes with @file{gforth.el}, an improved version of
                   13805: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    13806: improvements are:
                   13807: 
                   13808: @itemize @bullet
                   13809: @item
                   13810: A better (but still not perfect) handling of indentation.
                   13811: @item
                   13812: Comment paragraph filling (@kbd{M-q})
                   13813: @item
                   13814: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   13815: @item
                   13816: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41      anton    13817: @item
                   13818: Support of the @code{info-lookup} feature for looking up the
                   13819: documentation of a word.
1.26      crook    13820: @end itemize
                   13821: 
                   13822: I left the stuff I do not use alone, even though some of it only makes
                   13823: sense for TILE. To get a description of these features, enter Forth mode
                   13824: and type @kbd{C-h m}.
1.1       anton    13825: 
                   13826: @cindex source location of error or debugging output in Emacs
                   13827: @cindex error output, finding the source location in Emacs
                   13828: @cindex debugging output, finding the source location in Emacs
                   13829: In addition, Gforth supports Emacs quite well: The source code locations
                   13830: given in error messages, debugging output (from @code{~~}) and failed
                   13831: assertion messages are in the right format for Emacs' compilation mode
                   13832: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   13833: Manual}) so the source location corresponding to an error or other
                   13834: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   13835: @kbd{C-c C-c} for the error under the cursor).
                   13836: 
                   13837: @cindex @file{TAGS} file
                   13838: @cindex @file{etags.fs}
                   13839: @cindex viewing the source of a word in Emacs
1.43      anton    13840: @cindex @code{require}, placement in files
                   13841: @cindex @code{include}, placement in files
                   13842: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
1.26      crook    13843: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    13844: contains the definitions of all words defined afterwards. You can then
                   13845: find the source for a word using @kbd{M-.}. Note that emacs can use
                   13846: several tags files at the same time (e.g., one for the Gforth sources
                   13847: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   13848: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   13849: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43      anton    13850: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
                   13851: with @file{etags.fs}, you should avoid putting definitions both before
                   13852: and after @code{require} etc., otherwise you will see the same file
                   13853: visited several times by commands like @code{tags-search}.
1.1       anton    13854: 
1.41      anton    13855: @cindex viewing the documentation of a word in Emacs
                   13856: @cindex context-sensitive help
                   13857: Moreover, for words documented in this manual, you can look up the
                   13858: glossary entry quickly by using @kbd{C-h TAB}
1.80      anton    13859: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
1.41      anton    13860: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
1.42      anton    13861: later and does not work for words containing @code{:}.
1.41      anton    13862: 
                   13863: 
1.1       anton    13864: @cindex @file{.emacs}
                   13865: To get all these benefits, add the following lines to your @file{.emacs}
                   13866: file:
                   13867: 
                   13868: @example
                   13869: (autoload 'forth-mode "gforth.el")
                   13870: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
                   13871: @end example
                   13872: 
1.26      crook    13873: @c ******************************************************************
1.1       anton    13874: @node Image Files, Engine, Emacs and Gforth, Top
                   13875: @chapter Image Files
1.26      crook    13876: @cindex image file
                   13877: @cindex @file{.fi} files
1.1       anton    13878: @cindex precompiled Forth code
                   13879: @cindex dictionary in persistent form
                   13880: @cindex persistent form of dictionary
                   13881: 
                   13882: An image file is a file containing an image of the Forth dictionary,
                   13883: i.e., compiled Forth code and data residing in the dictionary.  By
                   13884: convention, we use the extension @code{.fi} for image files.
                   13885: 
                   13886: @menu
1.18      anton    13887: * Image Licensing Issues::      Distribution terms for images.
                   13888: * Image File Background::       Why have image files?
1.67      anton    13889: * Non-Relocatable Image Files::  don't always work.
1.18      anton    13890: * Data-Relocatable Image Files::  are better.
1.67      anton    13891: * Fully Relocatable Image Files::  better yet.
1.18      anton    13892: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    13893: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    13894: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    13895: @end menu
                   13896: 
1.18      anton    13897: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   13898: @section Image Licensing Issues
                   13899: @cindex license for images
                   13900: @cindex image license
                   13901: 
                   13902: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   13903: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   13904: original image; i.e., according to copyright law it is a derived work of
                   13905: the original image.
                   13906: 
                   13907: Since Gforth is distributed under the GNU GPL, the newly created image
                   13908: falls under the GNU GPL, too. In particular, this means that if you
                   13909: distribute the image, you have to make all of the sources for the image
                   13910: available, including those you wrote.  For details see @ref{License, ,
                   13911: GNU General Public License (Section 3)}.
                   13912: 
                   13913: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   13914: contains only code compiled from the sources you gave it; if none of
                   13915: these sources is under the GPL, the terms discussed above do not apply
                   13916: to the image. However, if your image needs an engine (a gforth binary)
                   13917: that is under the GPL, you should make sure that you distribute both in
                   13918: a way that is at most a @emph{mere aggregation}, if you don't want the
                   13919: terms of the GPL to apply to the image.
                   13920: 
                   13921: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    13922: @section Image File Background
                   13923: @cindex image file background
                   13924: 
1.80      anton    13925: Gforth consists not only of primitives (in the engine), but also of
1.1       anton    13926: definitions written in Forth. Since the Forth compiler itself belongs to
                   13927: those definitions, it is not possible to start the system with the
1.80      anton    13928: engine and the Forth source alone. Therefore we provide the Forth
1.26      crook    13929: code as an image file in nearly executable form. When Gforth starts up,
                   13930: a C routine loads the image file into memory, optionally relocates the
                   13931: addresses, then sets up the memory (stacks etc.) according to
                   13932: information in the image file, and (finally) starts executing Forth
                   13933: code.
1.1       anton    13934: 
                   13935: The image file variants represent different compromises between the
                   13936: goals of making it easy to generate image files and making them
                   13937: portable.
                   13938: 
                   13939: @cindex relocation at run-time
1.26      crook    13940: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    13941: run-time. This avoids many of the complications discussed below (image
                   13942: files are data relocatable without further ado), but costs performance
                   13943: (one addition per memory access).
                   13944: 
                   13945: @cindex relocation at load-time
1.26      crook    13946: By contrast, the Gforth loader performs relocation at image load time. The
                   13947: loader also has to replace tokens that represent primitive calls with the
1.1       anton    13948: appropriate code-field addresses (or code addresses in the case of
                   13949: direct threading).
                   13950: 
                   13951: There are three kinds of image files, with different degrees of
                   13952: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   13953: image files.
                   13954: 
                   13955: @cindex image file loader
                   13956: @cindex relocating loader
                   13957: @cindex loader for image files
                   13958: These image file variants have several restrictions in common; they are
                   13959: caused by the design of the image file loader:
                   13960: 
                   13961: @itemize @bullet
                   13962: @item
                   13963: There is only one segment; in particular, this means, that an image file
                   13964: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    13965: them). The contents of the stacks are not represented, either.
1.1       anton    13966: 
                   13967: @item
                   13968: The only kinds of relocation supported are: adding the same offset to
                   13969: all cells that represent data addresses; and replacing special tokens
                   13970: with code addresses or with pieces of machine code.
                   13971: 
                   13972: If any complex computations involving addresses are performed, the
                   13973: results cannot be represented in the image file. Several applications that
                   13974: use such computations come to mind:
                   13975: @itemize @minus
                   13976: @item
                   13977: Hashing addresses (or data structures which contain addresses) for table
                   13978: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   13979: purpose, you will have no problem, because the hash tables are
                   13980: recomputed automatically when the system is started. If you use your own
                   13981: hash tables, you will have to do something similar.
                   13982: 
                   13983: @item
                   13984: There's a cute implementation of doubly-linked lists that uses
                   13985: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   13986: in the image file, and restore the doubly-linked representation on
                   13987: startup.@footnote{In my opinion, though, you should think thrice before
                   13988: using a doubly-linked list (whatever implementation).}
                   13989: 
                   13990: @item
                   13991: The code addresses of run-time routines like @code{docol:} cannot be
                   13992: represented in the image file (because their tokens would be replaced by
                   13993: machine code in direct threaded implementations). As a workaround,
                   13994: compute these addresses at run-time with @code{>code-address} from the
                   13995: executions tokens of appropriate words (see the definitions of
1.80      anton    13996: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1       anton    13997: 
                   13998: @item
                   13999: On many architectures addresses are represented in machine code in some
                   14000: shifted or mangled form. You cannot put @code{CODE} words that contain
                   14001: absolute addresses in this form in a relocatable image file. Workarounds
                   14002: are representing the address in some relative form (e.g., relative to
                   14003: the CFA, which is present in some register), or loading the address from
                   14004: a place where it is stored in a non-mangled form.
                   14005: @end itemize
                   14006: @end itemize
                   14007: 
                   14008: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   14009: @section Non-Relocatable Image Files
                   14010: @cindex non-relocatable image files
1.26      crook    14011: @cindex image file, non-relocatable
1.1       anton    14012: 
                   14013: These files are simple memory dumps of the dictionary. They are specific
                   14014: to the executable (i.e., @file{gforth} file) they were created
                   14015: with. What's worse, they are specific to the place on which the
                   14016: dictionary resided when the image was created. Now, there is no
                   14017: guarantee that the dictionary will reside at the same place the next
                   14018: time you start Gforth, so there's no guarantee that a non-relocatable
                   14019: image will work the next time (Gforth will complain instead of crashing,
                   14020: though).
                   14021: 
                   14022: You can create a non-relocatable image file with
                   14023: 
1.44      crook    14024: 
1.1       anton    14025: doc-savesystem
                   14026: 
1.44      crook    14027: 
1.1       anton    14028: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   14029: @section Data-Relocatable Image Files
                   14030: @cindex data-relocatable image files
1.26      crook    14031: @cindex image file, data-relocatable
1.1       anton    14032: 
                   14033: These files contain relocatable data addresses, but fixed code addresses
                   14034: (instead of tokens). They are specific to the executable (i.e.,
                   14035: @file{gforth} file) they were created with. For direct threading on some
                   14036: architectures (e.g., the i386), data-relocatable images do not work. You
                   14037: get a data-relocatable image, if you use @file{gforthmi} with a
                   14038: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   14039: Relocatable Image Files}).
                   14040: 
                   14041: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   14042: @section Fully Relocatable Image Files
                   14043: @cindex fully relocatable image files
1.26      crook    14044: @cindex image file, fully relocatable
1.1       anton    14045: 
                   14046: @cindex @file{kern*.fi}, relocatability
                   14047: @cindex @file{gforth.fi}, relocatability
                   14048: These image files have relocatable data addresses, and tokens for code
                   14049: addresses. They can be used with different binaries (e.g., with and
                   14050: without debugging) on the same machine, and even across machines with
                   14051: the same data formats (byte order, cell size, floating point
                   14052: format). However, they are usually specific to the version of Gforth
                   14053: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   14054: are fully relocatable.
                   14055: 
                   14056: There are two ways to create a fully relocatable image file:
                   14057: 
                   14058: @menu
1.29      crook    14059: * gforthmi::                    The normal way
1.1       anton    14060: * cross.fs::                    The hard way
                   14061: @end menu
                   14062: 
                   14063: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   14064: @subsection @file{gforthmi}
                   14065: @cindex @file{comp-i.fs}
                   14066: @cindex @file{gforthmi}
                   14067: 
                   14068: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    14069: image @i{file} that contains everything you would load by invoking
                   14070: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    14071: @example
1.29      crook    14072: gforthmi @i{file} @i{options}
1.1       anton    14073: @end example
                   14074: 
                   14075: E.g., if you want to create an image @file{asm.fi} that has the file
                   14076: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   14077: like this:
                   14078: 
                   14079: @example
                   14080: gforthmi asm.fi asm.fs
                   14081: @end example
                   14082: 
1.27      crook    14083: @file{gforthmi} is implemented as a sh script and works like this: It
                   14084: produces two non-relocatable images for different addresses and then
                   14085: compares them. Its output reflects this: first you see the output (if
1.62      crook    14086: any) of the two Gforth invocations that produce the non-relocatable image
1.27      crook    14087: files, then you see the output of the comparing program: It displays the
                   14088: offset used for data addresses and the offset used for code addresses;
1.1       anton    14089: moreover, for each cell that cannot be represented correctly in the
1.44      crook    14090: image files, it displays a line like this:
1.1       anton    14091: 
                   14092: @example
                   14093:      78DC         BFFFFA50         BFFFFA40
                   14094: @end example
                   14095: 
                   14096: This means that at offset $78dc from @code{forthstart}, one input image
                   14097: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   14098: cannot be represented correctly in the output image, you should examine
                   14099: these places in the dictionary and verify that these cells are dead
                   14100: (i.e., not read before they are written).
1.39      anton    14101: 
                   14102: @cindex --application, @code{gforthmi} option
                   14103: If you insert the option @code{--application} in front of the image file
                   14104: name, you will get an image that uses the @code{--appl-image} option
                   14105: instead of the @code{--image-file} option (@pxref{Invoking
                   14106: Gforth}). When you execute such an image on Unix (by typing the image
                   14107: name as command), the Gforth engine will pass all options to the image
                   14108: instead of trying to interpret them as engine options.
1.1       anton    14109: 
1.27      crook    14110: If you type @file{gforthmi} with no arguments, it prints some usage
                   14111: instructions.
                   14112: 
1.1       anton    14113: @cindex @code{savesystem} during @file{gforthmi}
                   14114: @cindex @code{bye} during @file{gforthmi}
                   14115: @cindex doubly indirect threaded code
1.44      crook    14116: @cindex environment variables
                   14117: @cindex @code{GFORTHD} -- environment variable
                   14118: @cindex @code{GFORTH} -- environment variable
1.1       anton    14119: @cindex @code{gforth-ditc}
1.29      crook    14120: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    14121: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   14122: indirect threaded version of the @file{gforth} executable is used for
1.62      crook    14123: creating the non-relocatable images; you can pass the exact filename of
1.1       anton    14124: this executable through the environment variable @code{GFORTHD}
                   14125: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   14126: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    14127: data-relocatable image (because there is no code address offset). The
                   14128: normal @file{gforth} executable is used for creating the relocatable
                   14129: image; you can pass the exact filename of this executable through the
                   14130: environment variable @code{GFORTH}.
1.1       anton    14131: 
                   14132: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   14133: @subsection @file{cross.fs}
                   14134: @cindex @file{cross.fs}
                   14135: @cindex cross-compiler
                   14136: @cindex metacompiler
1.47      crook    14137: @cindex target compiler
1.1       anton    14138: 
                   14139: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47      crook    14140: programming language (@pxref{Cross Compiler}).
1.1       anton    14141: 
1.47      crook    14142: @code{cross} allows you to create image files for machines with
1.1       anton    14143: different data sizes and data formats than the one used for generating
                   14144: the image file. You can also use it to create an application image that
                   14145: does not contain a Forth compiler. These features are bought with
                   14146: restrictions and inconveniences in programming. E.g., addresses have to
                   14147: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   14148: order to make the code relocatable.
                   14149: 
                   14150: 
                   14151: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   14152: @section Stack and Dictionary Sizes
                   14153: @cindex image file, stack and dictionary sizes
                   14154: @cindex dictionary size default
                   14155: @cindex stack size default
                   14156: 
                   14157: If you invoke Gforth with a command line flag for the size
                   14158: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   14159: dictionary. If you save the dictionary with @code{savesystem} or create
                   14160: an image with @file{gforthmi}, this size will become the default
                   14161: for the resulting image file. E.g., the following will create a
1.21      crook    14162: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    14163: 
                   14164: @example
                   14165: gforthmi gforth.fi -m 1M
                   14166: @end example
                   14167: 
                   14168: In other words, if you want to set the default size for the dictionary
                   14169: and the stacks of an image, just invoke @file{gforthmi} with the
                   14170: appropriate options when creating the image.
                   14171: 
                   14172: @cindex stack size, cache-friendly
                   14173: Note: For cache-friendly behaviour (i.e., good performance), you should
                   14174: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   14175: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   14176: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   14177: 
                   14178: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   14179: @section Running Image Files
                   14180: @cindex running image files
                   14181: @cindex invoking image files
                   14182: @cindex image file invocation
                   14183: 
                   14184: @cindex -i, invoke image file
                   14185: @cindex --image file, invoke image file
1.29      crook    14186: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    14187: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   14188: @example
1.29      crook    14189: gforth -i @i{image}
1.1       anton    14190: @end example
                   14191: 
                   14192: @cindex executable image file
1.26      crook    14193: @cindex image file, executable
1.1       anton    14194: If your operating system supports starting scripts with a line of the
                   14195: form @code{#! ...}, you just have to type the image file name to start
                   14196: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    14197: just a convention). I.e., to run Gforth with the image file @i{image},
                   14198: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    14199: This works because every @code{.fi} file starts with a line of this
                   14200: format:
                   14201: 
                   14202: @example
                   14203: #! /usr/local/bin/gforth-0.4.0 -i
                   14204: @end example
                   14205: 
                   14206: The file and pathname for the Gforth engine specified on this line is
                   14207: the specific Gforth executable that it was built against; i.e. the value
                   14208: of the environment variable @code{GFORTH} at the time that
                   14209: @file{gforthmi} was executed.
1.1       anton    14210: 
1.27      crook    14211: You can make use of the same shell capability to make a Forth source
                   14212: file into an executable. For example, if you place this text in a file:
1.26      crook    14213: 
                   14214: @example
                   14215: #! /usr/local/bin/gforth
                   14216: 
                   14217: ." Hello, world" CR
                   14218: bye
                   14219: @end example
                   14220: 
                   14221: @noindent
1.27      crook    14222: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    14223: directly from the command line. The sequence @code{#!} is used in two
                   14224: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    14225: system@footnote{The Unix kernel actually recognises two types of files:
                   14226: executable files and files of data, where the data is processed by an
                   14227: interpreter that is specified on the ``interpreter line'' -- the first
                   14228: line of the file, starting with the sequence #!. There may be a small
                   14229: limit (e.g., 32) on the number of characters that may be specified on
                   14230: the interpreter line.} secondly it is treated as a comment character by
                   14231: Gforth. Because of the second usage, a space is required between
1.80      anton    14232: @code{#!} and the path to the executable (moreover, some Unixes
                   14233: require the sequence @code{#! /}).
1.27      crook    14234: 
                   14235: The disadvantage of this latter technique, compared with using
1.80      anton    14236: @file{gforthmi}, is that it is slightly slower; the Forth source code is
                   14237: compiled on-the-fly, each time the program is invoked.
1.26      crook    14238: 
1.1       anton    14239: doc-#!
                   14240: 
1.44      crook    14241: 
1.1       anton    14242: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   14243: @section Modifying the Startup Sequence
                   14244: @cindex startup sequence for image file
                   14245: @cindex image file initialization sequence
                   14246: @cindex initialization sequence of image file
                   14247: 
                   14248: You can add your own initialization to the startup sequence through the
1.26      crook    14249: deferred word @code{'cold}. @code{'cold} is invoked just before the
1.80      anton    14250: image-specific command line processing (i.e., loading files and
1.26      crook    14251: evaluating (@code{-e}) strings) starts.
1.1       anton    14252: 
                   14253: A sequence for adding your initialization usually looks like this:
                   14254: 
                   14255: @example
                   14256: :noname
                   14257:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   14258:     ... \ your stuff
                   14259: ; IS 'cold
                   14260: @end example
                   14261: 
                   14262: @cindex turnkey image files
1.26      crook    14263: @cindex image file, turnkey applications
1.1       anton    14264: You can make a turnkey image by letting @code{'cold} execute a word
                   14265: (your turnkey application) that never returns; instead, it exits Gforth
                   14266: via @code{bye} or @code{throw}.
                   14267: 
                   14268: @cindex command-line arguments, access
                   14269: @cindex arguments on the command line, access
                   14270: You can access the (image-specific) command-line arguments through the
1.26      crook    14271: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1       anton    14272: access to @code{argv}.
                   14273: 
1.26      crook    14274: If @code{'cold} exits normally, Gforth processes the command-line
                   14275: arguments as files to be loaded and strings to be evaluated.  Therefore,
                   14276: @code{'cold} should remove the arguments it has used in this case.
                   14277: 
1.44      crook    14278: 
                   14279: 
1.26      crook    14280: doc-'cold
1.1       anton    14281: doc-argc
                   14282: doc-argv
                   14283: doc-arg
                   14284: 
                   14285: 
1.44      crook    14286: 
1.1       anton    14287: @c ******************************************************************
1.13      pazsan   14288: @node Engine, Binding to System Library, Image Files, Top
1.1       anton    14289: @chapter Engine
                   14290: @cindex engine
                   14291: @cindex virtual machine
                   14292: 
1.26      crook    14293: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    14294: may be helpful for finding your way in the Gforth sources.
                   14295: 
1.66      anton    14296: The ideas in this section have also been published in Bernd Paysan,
                   14297: @cite{ANS fig/GNU/??? Forth} (in German), Forth-Tagung '93 and M. Anton
                   14298: Ertl, @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
                   14299: Portable Forth Engine}}, EuroForth '93.
1.1       anton    14300: 
                   14301: @menu
                   14302: * Portability::                 
                   14303: * Threading::                   
                   14304: * Primitives::                  
                   14305: * Performance::                 
                   14306: @end menu
                   14307: 
                   14308: @node Portability, Threading, Engine, Engine
                   14309: @section Portability
                   14310: @cindex engine portability
                   14311: 
1.26      crook    14312: An important goal of the Gforth Project is availability across a wide
                   14313: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   14314: achieved this goal by manually coding the engine in assembly language
                   14315: for several then-popular processors. This approach is very
                   14316: labor-intensive and the results are short-lived due to progress in
                   14317: computer architecture.
1.1       anton    14318: 
                   14319: @cindex C, using C for the engine
                   14320: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   14321: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   14322: particularly popular for UNIX-based Forths due to the large variety of
                   14323: architectures of UNIX machines. Unfortunately an implementation in C
                   14324: does not mix well with the goals of efficiency and with using
                   14325: traditional techniques: Indirect or direct threading cannot be expressed
                   14326: in C, and switch threading, the fastest technique available in C, is
                   14327: significantly slower. Another problem with C is that it is very
                   14328: cumbersome to express double integer arithmetic.
                   14329: 
                   14330: @cindex GNU C for the engine
                   14331: @cindex long long
                   14332: Fortunately, there is a portable language that does not have these
                   14333: limitations: GNU C, the version of C processed by the GNU C compiler
                   14334: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   14335: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   14336: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   14337: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   14338: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
                   14339: double numbers@footnote{Unfortunately, long longs are not implemented
                   14340: properly on all machines (e.g., on alpha-osf1, long longs are only 64
                   14341: bits, the same size as longs (and pointers), but they should be twice as
1.4       anton    14342: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1       anton    14343: C Manual}). So, we had to implement doubles in C after all. Still, on
                   14344: most machines we can use long longs and achieve better performance than
                   14345: with the emulation package.}. GNU C is available for free on all
                   14346: important (and many unimportant) UNIX machines, VMS, 80386s running
                   14347: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   14348: on all these machines.
                   14349: 
                   14350: Writing in a portable language has the reputation of producing code that
                   14351: is slower than assembly. For our Forth engine we repeatedly looked at
                   14352: the code produced by the compiler and eliminated most compiler-induced
                   14353: inefficiencies by appropriate changes in the source code.
                   14354: 
                   14355: @cindex explicit register declarations
                   14356: @cindex --enable-force-reg, configuration flag
                   14357: @cindex -DFORCE_REG
                   14358: However, register allocation cannot be portably influenced by the
                   14359: programmer, leading to some inefficiencies on register-starved
                   14360: machines. We use explicit register declarations (@pxref{Explicit Reg
                   14361: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   14362: improve the speed on some machines. They are turned on by using the
                   14363: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   14364: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   14365: machine, but also on the compiler version: On some machines some
                   14366: compiler versions produce incorrect code when certain explicit register
                   14367: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   14368: 
                   14369: @node Threading, Primitives, Portability, Engine
                   14370: @section Threading
                   14371: @cindex inner interpreter implementation
                   14372: @cindex threaded code implementation
                   14373: 
                   14374: @cindex labels as values
                   14375: GNU C's labels as values extension (available since @code{gcc-2.0},
                   14376: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    14377: makes it possible to take the address of @i{label} by writing
                   14378: @code{&&@i{label}}.  This address can then be used in a statement like
                   14379: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    14380: @code{goto x}.
                   14381: 
1.26      crook    14382: @cindex @code{NEXT}, indirect threaded
1.1       anton    14383: @cindex indirect threaded inner interpreter
                   14384: @cindex inner interpreter, indirect threaded
1.26      crook    14385: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    14386: @example
                   14387: cfa = *ip++;
                   14388: ca = *cfa;
                   14389: goto *ca;
                   14390: @end example
                   14391: @cindex instruction pointer
                   14392: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   14393: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   14394: execution token and points to the code field of the next word to be
                   14395: executed; The @code{ca} (code address) fetched from there points to some
                   14396: executable code, e.g., a primitive or the colon definition handler
                   14397: @code{docol}.
                   14398: 
1.26      crook    14399: @cindex @code{NEXT}, direct threaded
1.1       anton    14400: @cindex direct threaded inner interpreter
                   14401: @cindex inner interpreter, direct threaded
                   14402: Direct threading is even simpler:
                   14403: @example
                   14404: ca = *ip++;
                   14405: goto *ca;
                   14406: @end example
                   14407: 
                   14408: Of course we have packaged the whole thing neatly in macros called
1.26      crook    14409: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    14410: 
                   14411: @menu
                   14412: * Scheduling::                  
                   14413: * Direct or Indirect Threaded?::  
                   14414: * DOES>::                       
                   14415: @end menu
                   14416: 
                   14417: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   14418: @subsection Scheduling
                   14419: @cindex inner interpreter optimization
                   14420: 
                   14421: There is a little complication: Pipelined and superscalar processors,
                   14422: i.e., RISC and some modern CISC machines can process independent
                   14423: instructions while waiting for the results of an instruction. The
                   14424: compiler usually reorders (schedules) the instructions in a way that
                   14425: achieves good usage of these delay slots. However, on our first tries
                   14426: the compiler did not do well on scheduling primitives. E.g., for
                   14427: @code{+} implemented as
                   14428: @example
                   14429: n=sp[0]+sp[1];
                   14430: sp++;
                   14431: sp[0]=n;
                   14432: NEXT;
                   14433: @end example
1.81      anton    14434: the @code{NEXT} comes strictly after the other code, i.e., there is
                   14435: nearly no scheduling. After a little thought the problem becomes clear:
                   14436: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21      crook    14437: addresses (and the version of @code{gcc} we used would not know it even
                   14438: if it was possible), so it could not move the load of the cfa above the
                   14439: store to the TOS. Indeed the pointers could be the same, if code on or
                   14440: very near the top of stack were executed. In the interest of speed we
                   14441: chose to forbid this probably unused ``feature'' and helped the compiler
1.81      anton    14442: in scheduling: @code{NEXT} is divided into several parts:
                   14443: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
                   14444: like:
1.1       anton    14445: @example
1.81      anton    14446: NEXT_P0;
1.1       anton    14447: n=sp[0]+sp[1];
                   14448: sp++;
                   14449: NEXT_P1;
                   14450: sp[0]=n;
                   14451: NEXT_P2;
                   14452: @end example
                   14453: 
1.81      anton    14454: There are various schemes that distribute the different operations of
                   14455: NEXT between these parts in several ways; in general, different schemes
                   14456: perform best on different processors.  We use a scheme for most
                   14457: architectures that performs well for most processors of this
                   14458: architecture; in the furture we may switch to benchmarking and chosing
                   14459: the scheme on installation time.
                   14460: 
1.1       anton    14461: 
                   14462: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
                   14463: @subsection Direct or Indirect Threaded?
                   14464: @cindex threading, direct or indirect?
                   14465: 
                   14466: @cindex -DDIRECT_THREADED
                   14467: Both! After packaging the nasty details in macro definitions we
                   14468: realized that we could switch between direct and indirect threading by
                   14469: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
                   14470: defining a few machine-specific macros for the direct-threading case.
                   14471: On the Forth level we also offer access words that hide the
                   14472: differences between the threading methods (@pxref{Threading Words}).
                   14473: 
                   14474: Indirect threading is implemented completely machine-independently.
                   14475: Direct threading needs routines for creating jumps to the executable
1.21      crook    14476: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
                   14477: machine-dependent, but they do not amount to many source lines. Therefore,
                   14478: even porting direct threading to a new machine requires little effort.
1.1       anton    14479: 
                   14480: @cindex --enable-indirect-threaded, configuration flag
                   14481: @cindex --enable-direct-threaded, configuration flag
                   14482: The default threading method is machine-dependent. You can enforce a
                   14483: specific threading method when building Gforth with the configuration
                   14484: flag @code{--enable-direct-threaded} or
                   14485: @code{--enable-indirect-threaded}. Note that direct threading is not
                   14486: supported on all machines.
                   14487: 
                   14488: @node DOES>,  , Direct or Indirect Threaded?, Threading
                   14489: @subsection DOES>
                   14490: @cindex @code{DOES>} implementation
                   14491: 
1.26      crook    14492: @cindex @code{dodoes} routine
                   14493: @cindex @code{DOES>}-code
1.1       anton    14494: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   14495: the chunk of code executed by every word defined by a
                   14496: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
                   14497: the Forth code to be executed, i.e. the code after the
1.26      crook    14498: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1       anton    14499: 
1.21      crook    14500: In fig-Forth the code field points directly to the @code{dodoes} and the
1.45      crook    14501: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
1.29      crook    14502: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1       anton    14503: the Forth-79 and all later standards, because in fig-Forth this address
                   14504: lies in the body (which is illegal in these standards). However, by
                   14505: making the code field larger for all words this solution becomes legal
                   14506: again. We use this approach for the indirect threaded version and for
                   14507: direct threading on some machines. Leaving a cell unused in most words
                   14508: is a bit wasteful, but on the machines we are targeting this is hardly a
                   14509: problem. The other reason for having a code field size of two cells is
                   14510: to avoid having different image files for direct and indirect threaded
                   14511: systems (direct threaded systems require two-cell code fields on many
                   14512: machines).
                   14513: 
1.26      crook    14514: @cindex @code{DOES>}-handler
1.1       anton    14515: The other approach is that the code field points or jumps to the cell
1.26      crook    14516: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
                   14517: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
                   14518: @code{DOES>}-code address by computing the code address, i.e., the address of
1.45      crook    14519: the jump to @code{dodoes}, and add the length of that jump field. A variant of
1.1       anton    14520: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
                   14521: return address (which can be found in the return register on RISCs) is
1.26      crook    14522: the @code{DOES>}-code address. Since the two cells available in the code field
1.1       anton    14523: are used up by the jump to the code address in direct threading on many
                   14524: architectures, we use this approach for direct threading on these
                   14525: architectures. We did not want to add another cell to the code field.
                   14526: 
                   14527: @node Primitives, Performance, Threading, Engine
                   14528: @section Primitives
                   14529: @cindex primitives, implementation
                   14530: @cindex virtual machine instructions, implementation
                   14531: 
                   14532: @menu
                   14533: * Automatic Generation::        
                   14534: * TOS Optimization::            
                   14535: * Produced code::               
                   14536: @end menu
                   14537: 
                   14538: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   14539: @subsection Automatic Generation
                   14540: @cindex primitives, automatic generation
                   14541: 
                   14542: @cindex @file{prims2x.fs}
                   14543: Since the primitives are implemented in a portable language, there is no
                   14544: longer any need to minimize the number of primitives. On the contrary,
                   14545: having many primitives has an advantage: speed. In order to reduce the
                   14546: number of errors in primitives and to make programming them easier, we
                   14547: provide a tool, the primitive generator (@file{prims2x.fs}), that
                   14548: automatically generates most (and sometimes all) of the C code for a
                   14549: primitive from the stack effect notation.  The source for a primitive
                   14550: has the following form:
                   14551: 
                   14552: @cindex primitive source format
                   14553: @format
1.58      anton    14554: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
1.29      crook    14555: [@code{""}@i{glossary entry}@code{""}]
                   14556: @i{C code}
1.1       anton    14557: [@code{:}
1.29      crook    14558: @i{Forth code}]
1.1       anton    14559: @end format
                   14560: 
                   14561: The items in brackets are optional. The category and glossary fields
                   14562: are there for generating the documentation, the Forth code is there
                   14563: for manual implementations on machines without GNU C. E.g., the source
                   14564: for the primitive @code{+} is:
                   14565: @example
1.58      anton    14566: +    ( n1 n2 -- n )   core    plus
1.1       anton    14567: n = n1+n2;
                   14568: @end example
                   14569: 
                   14570: This looks like a specification, but in fact @code{n = n1+n2} is C
                   14571: code. Our primitive generation tool extracts a lot of information from
                   14572: the stack effect notations@footnote{We use a one-stack notation, even
                   14573: though we have separate data and floating-point stacks; The separate
                   14574: notation can be generated easily from the unified notation.}: The number
                   14575: of items popped from and pushed on the stack, their type, and by what
                   14576: name they are referred to in the C code. It then generates a C code
                   14577: prelude and postlude for each primitive. The final C code for @code{+}
                   14578: looks like this:
                   14579: 
                   14580: @example
1.46      pazsan   14581: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
1.1       anton    14582: /*  */                          /* documentation */
1.81      anton    14583: NAME("+")                       /* debugging output (with -DDEBUG) */
1.1       anton    14584: @{
                   14585: DEF_CA                          /* definition of variable ca (indirect threading) */
                   14586: Cell n1;                        /* definitions of variables */
                   14587: Cell n2;
                   14588: Cell n;
1.81      anton    14589: NEXT_P0;                        /* NEXT part 0 */
1.1       anton    14590: n1 = (Cell) sp[1];              /* input */
                   14591: n2 = (Cell) TOS;
                   14592: sp += 1;                        /* stack adjustment */
                   14593: @{
                   14594: n = n1+n2;                      /* C code taken from the source */
                   14595: @}
                   14596: NEXT_P1;                        /* NEXT part 1 */
                   14597: TOS = (Cell)n;                  /* output */
                   14598: NEXT_P2;                        /* NEXT part 2 */
                   14599: @}
                   14600: @end example
                   14601: 
                   14602: This looks long and inefficient, but the GNU C compiler optimizes quite
                   14603: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   14604: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   14605: using them as intermediate storage also adds no cost.
                   14606: 
1.26      crook    14607: There are also other optimizations that are not illustrated by this
                   14608: example: assignments between simple variables are usually for free (copy
1.1       anton    14609: propagation). If one of the stack items is not used by the primitive
                   14610: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   14611: (dead code elimination). On the other hand, there are some things that
                   14612: the compiler does not do, therefore they are performed by
                   14613: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   14614: a stack item to the place where it just came from (e.g., @code{over}).
                   14615: 
                   14616: While programming a primitive is usually easy, there are a few cases
                   14617: where the programmer has to take the actions of the generator into
                   14618: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    14619: fall through to @code{NEXT}.
1.1       anton    14620: 
                   14621: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   14622: @subsection TOS Optimization
                   14623: @cindex TOS optimization for primitives
                   14624: @cindex primitives, keeping the TOS in a register
                   14625: 
                   14626: An important optimization for stack machine emulators, e.g., Forth
                   14627: engines, is keeping  one or more of the top stack items in
1.29      crook    14628: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   14629: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    14630: @itemize @bullet
                   14631: @item
1.29      crook    14632: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    14633: due to fewer loads from and stores to the stack.
1.29      crook    14634: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   14635: @i{y<n}, due to additional moves between registers.
1.1       anton    14636: @end itemize
                   14637: 
                   14638: @cindex -DUSE_TOS
                   14639: @cindex -DUSE_NO_TOS
                   14640: In particular, keeping one item in a register is never a disadvantage,
                   14641: if there are enough registers. Keeping two items in registers is a
                   14642: disadvantage for frequent words like @code{?branch}, constants,
                   14643: variables, literals and @code{i}. Therefore our generator only produces
                   14644: code that keeps zero or one items in registers. The generated C code
                   14645: covers both cases; the selection between these alternatives is made at
                   14646: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   14647: code for @code{+} is just a simple variable name in the one-item case,
                   14648: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   14649: GNU C compiler tries to keep simple variables like @code{TOS} in
                   14650: registers, and it usually succeeds, if there are enough registers.
                   14651: 
                   14652: @cindex -DUSE_FTOS
                   14653: @cindex -DUSE_NO_FTOS
                   14654: The primitive generator performs the TOS optimization for the
                   14655: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   14656: operations the benefit of this optimization is even larger:
                   14657: floating-point operations take quite long on most processors, but can be
                   14658: performed in parallel with other operations as long as their results are
                   14659: not used. If the FP-TOS is kept in a register, this works. If
                   14660: it is kept on the stack, i.e., in memory, the store into memory has to
                   14661: wait for the result of the floating-point operation, lengthening the
                   14662: execution time of the primitive considerably.
                   14663: 
                   14664: The TOS optimization makes the automatic generation of primitives a
                   14665: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   14666: @code{TOS} is not sufficient. There are some special cases to
                   14667: consider:
                   14668: @itemize @bullet
                   14669: @item In the case of @code{dup ( w -- w w )} the generator must not
                   14670: eliminate the store to the original location of the item on the stack,
                   14671: if the TOS optimization is turned on.
                   14672: @item Primitives with stack effects of the form @code{--}
1.29      crook    14673: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   14674: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    14675: must load the TOS from the stack at the end. But for the null stack
                   14676: effect @code{--} no stores or loads should be generated.
                   14677: @end itemize
                   14678: 
                   14679: @node Produced code,  , TOS Optimization, Primitives
                   14680: @subsection Produced code
                   14681: @cindex primitives, assembly code listing
                   14682: 
                   14683: @cindex @file{engine.s}
                   14684: To see what assembly code is produced for the primitives on your machine
                   14685: with your compiler and your flag settings, type @code{make engine.s} and
1.81      anton    14686: look at the resulting file @file{engine.s}.  Alternatively, you can also
                   14687: disassemble the code of primitives with @code{see} on some architectures.
1.1       anton    14688: 
                   14689: @node  Performance,  , Primitives, Engine
                   14690: @section Performance
                   14691: @cindex performance of some Forth interpreters
                   14692: @cindex engine performance
                   14693: @cindex benchmarking Forth systems
                   14694: @cindex Gforth performance
                   14695: 
                   14696: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
                   14697: impossible to write a significantly faster engine.
                   14698: 
                   14699: On register-starved machines like the 386 architecture processors
                   14700: improvements are possible, because @code{gcc} does not utilize the
                   14701: registers as well as a human, even with explicit register declarations;
                   14702: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   14703: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   14704: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40      anton    14705: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
                   14706: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
                   14707: registers fit in real registers (and we can even afford to use the TOS
                   14708: optimization), resulting in a speedup of 1.14 on the sieve over the
                   14709: earlier results.
1.1       anton    14710: 
                   14711: @cindex Win32Forth performance
                   14712: @cindex NT Forth performance
                   14713: @cindex eforth performance
                   14714: @cindex ThisForth performance
                   14715: @cindex PFE performance
                   14716: @cindex TILE performance
1.81      anton    14717: The potential advantage of assembly language implementations is not
                   14718: necessarily realized in complete Forth systems: We compared Gforth-0.4.9
                   14719: (direct threaded, compiled with @code{gcc-2.95.1} and
                   14720: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
                   14721: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
                   14722: (with and without peephole (aka pinhole) optimization of the threaded
                   14723: code); all these systems were written in assembly language. We also
                   14724: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
                   14725: with @code{gcc-2.6.3} with the default configuration for Linux:
                   14726: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
                   14727: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
                   14728: employs peephole optimization of the threaded code) and TILE (compiled
                   14729: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
                   14730: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
                   14731: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
                   14732: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
                   14733: then extended it to run the benchmarks, added the peephole optimizer,
                   14734: ran the benchmarks and reported the results.
1.40      anton    14735: 
1.1       anton    14736: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   14737: matrix multiplication come from the Stanford integer benchmarks and have
                   14738: been translated into Forth by Martin Fraeman; we used the versions
                   14739: included in the TILE Forth package, but with bigger data set sizes; and
                   14740: a recursive Fibonacci number computation for benchmarking calling
                   14741: performance. The following table shows the time taken for the benchmarks
                   14742: scaled by the time taken by Gforth (in other words, it shows the speedup
                   14743: factor that Gforth achieved over the other systems).
                   14744: 
                   14745: @example
1.40      anton    14746: relative      Win32-    NT       eforth       This-      
1.1       anton    14747:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
1.81      anton    14748: sieve     1.00  1.60  1.32   1.60  0.98  1.82  3.67  9.91
                   14749: bubble    1.00  1.55  1.66   1.75  1.04  1.78        4.58
                   14750: matmul    1.00  1.71  1.57   1.69  0.86  1.83        4.74
                   14751: fib       1.00  1.76  1.54   1.41  1.00  2.01  3.45  4.96
1.1       anton    14752: @end example
                   14753: 
1.26      crook    14754: You may be quite surprised by the good performance of Gforth when
                   14755: compared with systems written in assembly language. One important reason
                   14756: for the disappointing performance of these other systems is probably
                   14757: that they are not written optimally for the 486 (e.g., they use the
                   14758: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   14759: but costly method for relocating the Forth image: like @code{cforth}, it
                   14760: computes the actual addresses at run time, resulting in two address
                   14761: computations per @code{NEXT} (@pxref{Image File Background}).
                   14762: 
1.40      anton    14763: Only Eforth with the peephole optimizer performs comparable to
                   14764: Gforth. The speedups achieved with peephole optimization of threaded
                   14765: code are quite remarkable. Adding a peephole optimizer to Gforth should
                   14766: cause similar speedups.
1.1       anton    14767: 
                   14768: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   14769: explained with the self-imposed restriction of the latter systems to
                   14770: standard C, which makes efficient threading impossible (however, the
1.4       anton    14771: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    14772: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   14773: Moreover, current C compilers have a hard time optimizing other aspects
                   14774: of the ThisForth and the TILE source.
                   14775: 
1.26      crook    14776: The performance of Gforth on 386 architecture processors varies widely
                   14777: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   14778: allocate any of the virtual machine registers into real machine
                   14779: registers by itself and would not work correctly with explicit register
1.40      anton    14780: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26      crook    14781: the Sieve) than the one measured above.
1.1       anton    14782: 
1.26      crook    14783: Note that there have been several releases of Win32Forth since the
                   14784: release presented here, so the results presented above may have little
1.40      anton    14785: predictive value for the performance of Win32Forth today (results for
                   14786: the current release on an i486DX2/66 are welcome).
1.1       anton    14787: 
                   14788: @cindex @file{Benchres}
1.66      anton    14789: In
                   14790: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
                   14791: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1       anton    14792: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66      anton    14793: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
                   14794: several native code systems; that version of Gforth is slower on a 486
                   14795: than the direct threaded version used here. You can find a newer version
                   14796: of these measurements at
1.47      crook    14797: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1       anton    14798: find numbers for Gforth on various machines in @file{Benchres}.
                   14799: 
1.26      crook    14800: @c ******************************************************************
1.13      pazsan   14801: @node Binding to System Library, Cross Compiler, Engine, Top
1.14      pazsan   14802: @chapter Binding to System Library
1.13      pazsan   14803: 
                   14804: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14      pazsan   14805: @chapter Cross Compiler
1.47      crook    14806: @cindex @file{cross.fs}
                   14807: @cindex cross-compiler
                   14808: @cindex metacompiler
                   14809: @cindex target compiler
1.13      pazsan   14810: 
1.46      pazsan   14811: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
                   14812: mostly written in Forth, including crucial parts like the outer
                   14813: interpreter and compiler, it needs compiled Forth code to get
                   14814: started. The cross compiler allows to create new images for other
                   14815: architectures, even running under another Forth system.
1.13      pazsan   14816: 
                   14817: @menu
1.67      anton    14818: * Using the Cross Compiler::    
                   14819: * How the Cross Compiler Works::  
1.13      pazsan   14820: @end menu
                   14821: 
1.21      crook    14822: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   14823: @section Using the Cross Compiler
1.46      pazsan   14824: 
                   14825: The cross compiler uses a language that resembles Forth, but isn't. The
                   14826: main difference is that you can execute Forth code after definition,
                   14827: while you usually can't execute the code compiled by cross, because the
                   14828: code you are compiling is typically for a different computer than the
                   14829: one you are compiling on.
                   14830: 
1.81      anton    14831: @c anton: This chapter is somewhat different from waht I would expect: I
                   14832: @c would expect an explanation of the cross language and how to create an
                   14833: @c application image with it.  The section explains some aspects of
                   14834: @c creating a Gforth kernel.
                   14835: 
1.46      pazsan   14836: The Makefile is already set up to allow you to create kernels for new
                   14837: architectures with a simple make command. The generic kernels using the
                   14838: GCC compiled virtual machine are created in the normal build process
                   14839: with @code{make}. To create a embedded Gforth executable for e.g. the
                   14840: 8086 processor (running on a DOS machine), type
                   14841: 
                   14842: @example
                   14843: make kernl-8086.fi
                   14844: @end example
                   14845: 
                   14846: This will use the machine description from the @file{arch/8086}
                   14847: directory to create a new kernel. A machine file may look like that:
                   14848: 
                   14849: @example
                   14850: \ Parameter for target systems                         06oct92py
                   14851: 
                   14852:     4 Constant cell             \ cell size in bytes
                   14853:     2 Constant cell<<           \ cell shift to bytes
                   14854:     5 Constant cell>bit         \ cell shift to bits
                   14855:     8 Constant bits/char        \ bits per character
                   14856:     8 Constant bits/byte        \ bits per byte [default: 8]
                   14857:     8 Constant float            \ bytes per float
                   14858:     8 Constant /maxalign        \ maximum alignment in bytes
                   14859: false Constant bigendian        \ byte order
                   14860: ( true=big, false=little )
                   14861: 
                   14862: include machpc.fs               \ feature list
                   14863: @end example
                   14864: 
                   14865: This part is obligatory for the cross compiler itself, the feature list
                   14866: is used by the kernel to conditionally compile some features in and out,
                   14867: depending on whether the target supports these features.
                   14868: 
                   14869: There are some optional features, if you define your own primitives,
                   14870: have an assembler, or need special, nonstandard preparation to make the
1.81      anton    14871: boot process work. @code{asm-include} includes an assembler,
1.46      pazsan   14872: @code{prims-include} includes primitives, and @code{>boot} prepares for
                   14873: booting.
                   14874: 
                   14875: @example
                   14876: : asm-include    ." Include assembler" cr
                   14877:   s" arch/8086/asm.fs" included ;
                   14878: 
                   14879: : prims-include  ." Include primitives" cr
                   14880:   s" arch/8086/prim.fs" included ;
                   14881: 
                   14882: : >boot          ." Prepare booting" cr
                   14883:   s" ' boot >body into-forth 1+ !" evaluate ;
                   14884: @end example
                   14885: 
                   14886: These words are used as sort of macro during the cross compilation in
1.81      anton    14887: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46      pazsan   14888: be possible --- but more complicated --- to write a new kernel project
                   14889: file, too.
                   14890: 
                   14891: @file{kernel/main.fs} expects the machine description file name on the
                   14892: stack; the cross compiler itself (@file{cross.fs}) assumes that either
                   14893: @code{mach-file} leaves a counted string on the stack, or
                   14894: @code{machine-file} leaves an address, count pair of the filename on the
                   14895: stack.
                   14896: 
                   14897: The feature list is typically controlled using @code{SetValue}, generic
                   14898: files that are used by several projects can use @code{DefaultValue}
                   14899: instead. Both functions work like @code{Value}, when the value isn't
                   14900: defined, but @code{SetValue} works like @code{to} if the value is
                   14901: defined, and @code{DefaultValue} doesn't set anything, if the value is
                   14902: defined.
                   14903: 
                   14904: @example
                   14905: \ generic mach file for pc gforth                       03sep97jaw
                   14906: 
                   14907: true DefaultValue NIL  \ relocating
                   14908: 
                   14909: >ENVIRON
                   14910: 
                   14911: true DefaultValue file          \ controls the presence of the
                   14912:                                 \ file access wordset
                   14913: true DefaultValue OS            \ flag to indicate a operating system
                   14914: 
                   14915: true DefaultValue prims         \ true: primitives are c-code
                   14916: 
                   14917: true DefaultValue floating      \ floating point wordset is present
                   14918: 
                   14919: true DefaultValue glocals       \ gforth locals are present
                   14920:                                 \ will be loaded
                   14921: true DefaultValue dcomps        \ double number comparisons
                   14922: 
                   14923: true DefaultValue hash          \ hashing primitives are loaded/present
                   14924: 
                   14925: true DefaultValue xconds        \ used together with glocals,
                   14926:                                 \ special conditionals supporting gforths'
                   14927:                                 \ local variables
                   14928: true DefaultValue header        \ save a header information
                   14929: 
                   14930: true DefaultValue backtrace     \ enables backtrace code
                   14931: 
                   14932: false DefaultValue ec
                   14933: false DefaultValue crlf
                   14934: 
                   14935: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
                   14936: 
                   14937: &16 KB          DefaultValue stack-size
                   14938: &15 KB &512 +   DefaultValue fstack-size
                   14939: &15 KB          DefaultValue rstack-size
                   14940: &14 KB &512 +   DefaultValue lstack-size
                   14941: @end example
1.13      pazsan   14942: 
1.48      anton    14943: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
1.14      pazsan   14944: @section How the Cross Compiler Works
1.13      pazsan   14945: 
                   14946: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    14947: @appendix Bugs
1.1       anton    14948: @cindex bug reporting
                   14949: 
1.21      crook    14950: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    14951: 
                   14952: If you find a bug, please send a bug report to
1.33      anton    14953: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21      crook    14954: information:
                   14955: 
                   14956: @itemize @bullet
                   14957: @item
1.81      anton    14958: A program (or a sequence of keyboard commands) that reproduces the bug.
                   14959: @item
                   14960: A description of what you think constitutes the buggy behaviour.
                   14961: @item
1.21      crook    14962: The Gforth version used (it is announced at the start of an
                   14963: interactive Gforth session).
                   14964: @item
                   14965: The machine and operating system (on Unix
                   14966: systems @code{uname -a} will report this information).
                   14967: @item
1.81      anton    14968: The installation options (you can find the configure options at the
                   14969: start of @file{config.status}) and configuration (@code{configure}
                   14970: output or @file{config.cache}).
1.21      crook    14971: @item
                   14972: A complete list of changes (if any) you (or your installer) have made to the
                   14973: Gforth sources.
                   14974: @end itemize
1.1       anton    14975: 
                   14976: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   14977: to Report Bugs, gcc.info, GNU C Manual}.
                   14978: 
                   14979: 
1.21      crook    14980: @node Origin, Forth-related information, Bugs, Top
                   14981: @appendix Authors and Ancestors of Gforth
1.1       anton    14982: 
                   14983: @section Authors and Contributors
                   14984: @cindex authors of Gforth
                   14985: @cindex contributors to Gforth
                   14986: 
                   14987: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81      anton    14988: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
                   14989: lot to the manual.  Assemblers and disassemblers were contributed by
                   14990: Andrew McKewan, Christian Pirker, and Bernd Thallner.  Lennart Benschop
                   14991: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
                   14992: inspired us with their continuous feedback. Lennart Benshop contributed
1.1       anton    14993: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
                   14994: support for calling C libraries. Helpful comments also came from Paul
                   14995: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.58      anton    14996: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
                   14997: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
                   14998: helpful comments from many others; thank you all, sorry for not listing
                   14999: you here (but digging through my mailbox to extract your names is on my
1.81      anton    15000: to-do list).
1.1       anton    15001: 
                   15002: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   15003: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    15004: was developed across the Internet, and its authors did not meet
1.20      pazsan   15005: physically for the first 4 years of development.
1.1       anton    15006: 
                   15007: @section Pedigree
1.26      crook    15008: @cindex pedigree of Gforth
1.1       anton    15009: 
1.81      anton    15010: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
                   15011: significant part of the design of Gforth was prescribed by ANS Forth.
1.1       anton    15012: 
1.20      pazsan   15013: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    15014: 32 bit native code version of VolksForth for the Atari ST, written
                   15015: mostly by Dietrich Weineck.
                   15016: 
1.81      anton    15017: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
                   15018: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
                   15019: the mid-80s and ported to the Atari ST in 1986.  It descends from F83.
1.1       anton    15020: 
                   15021: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   15022: Forth-83 standard. !! Pedigree? When?
                   15023: 
                   15024: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   15025: 1979. Robert Selzer and Bill Ragsdale developed the original
                   15026: implementation of fig-Forth for the 6502 based on microForth.
                   15027: 
                   15028: The principal architect of microForth was Dean Sanderson. microForth was
                   15029: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   15030: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   15031: Z80.
                   15032: 
                   15033: All earlier Forth systems were custom-made, usually by Charles Moore,
                   15034: who discovered (as he puts it) Forth during the late 60s. The first full
                   15035: Forth existed in 1971.
                   15036: 
1.81      anton    15037: A part of the information in this section comes from
                   15038: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
                   15039: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
                   15040: Charles H. Moore, presented at the HOPL-II conference and preprinted in
                   15041: SIGPLAN Notices 28(3), 1993.  You can find more historical and
                   15042: genealogical information about Forth there.
1.1       anton    15043: 
1.81      anton    15044: @c ------------------------------------------------------------------
1.21      crook    15045: @node Forth-related information, Word Index, Origin, Top
                   15046: @appendix Other Forth-related information
                   15047: @cindex Forth-related information
                   15048: 
1.81      anton    15049: @c anton: I threw most of this stuff out, because it can be found through
                   15050: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21      crook    15051: 
                   15052: @cindex comp.lang.forth
                   15053: @cindex frequently asked questions
1.81      anton    15054: There is an active news group (comp.lang.forth) discussing Forth
                   15055: (including Gforth) and Forth-related issues. Its
                   15056: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
                   15057: (frequently asked questions and their answers) contains a lot of
                   15058: information on Forth.  You should read it before posting to
                   15059: comp.lang.forth.
1.21      crook    15060: 
1.81      anton    15061: The ANS Forth standard is most usable in its
                   15062: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21      crook    15063: 
1.81      anton    15064: @c ------------------------------------------------------------------
                   15065: @node Word Index, Concept Index, Forth-related information, Top
1.1       anton    15066: @unnumbered Word Index
                   15067: 
1.26      crook    15068: This index is a list of Forth words that have ``glossary'' entries
                   15069: within this manual. Each word is listed with its stack effect and
                   15070: wordset.
1.1       anton    15071: 
                   15072: @printindex fn
                   15073: 
1.81      anton    15074: @c anton: the name index seems superfluous given the word and concept indices.
                   15075: 
                   15076: @c @node Name Index, Concept Index, Word Index, Top
                   15077: @c @unnumbered Name Index
1.41      anton    15078: 
1.81      anton    15079: @c This index is a list of Forth words that have ``glossary'' entries
                   15080: @c within this manual.
1.41      anton    15081: 
1.81      anton    15082: @c @printindex ky
1.41      anton    15083: 
1.81      anton    15084: @node Concept Index,  , Word Index, Top
1.1       anton    15085: @unnumbered Concept and Word Index
                   15086: 
1.26      crook    15087: Not all entries listed in this index are present verbatim in the
                   15088: text. This index also duplicates, in abbreviated form, all of the words
                   15089: listed in the Word Index (only the names are listed for the words here).
1.1       anton    15090: 
                   15091: @printindex cp
                   15092: 
                   15093: @contents
                   15094: @bye
1.81      anton    15095: 
                   15096: 
1.1       anton    15097: 

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