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

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.78      anton     172: @detailmenu --- The Detailed Node Listing ---
1.12      anton     173: 
1.29      crook     174: Gforth Environment
                    175: 
1.32      anton     176: * Invoking Gforth::             Getting in
                    177: * Leaving Gforth::              Getting out
                    178: * Command-line editing::        
1.48      anton     179: * Environment variables::       that affect how Gforth starts up
1.32      anton     180: * Gforth Files::                What gets installed and where
1.48      anton     181: * Startup speed::               When 35ms is not fast enough ...
                    182: 
                    183: Forth Tutorial
                    184: 
                    185: * Starting Gforth Tutorial::    
                    186: * Syntax Tutorial::             
                    187: * Crash Course Tutorial::       
                    188: * Stack Tutorial::              
                    189: * Arithmetics Tutorial::        
                    190: * Stack Manipulation Tutorial::  
                    191: * Using files for Forth code Tutorial::  
                    192: * Comments Tutorial::           
                    193: * Colon Definitions Tutorial::  
                    194: * Decompilation Tutorial::      
                    195: * Stack-Effect Comments Tutorial::  
                    196: * Types Tutorial::              
                    197: * Factoring Tutorial::          
                    198: * Designing the stack effect Tutorial::  
                    199: * Local Variables Tutorial::    
                    200: * Conditional execution Tutorial::  
                    201: * Flags and Comparisons Tutorial::  
                    202: * General Loops Tutorial::      
                    203: * Counted loops Tutorial::      
                    204: * Recursion Tutorial::          
                    205: * Leaving definitions or loops Tutorial::  
                    206: * Return Stack Tutorial::       
                    207: * Memory Tutorial::             
                    208: * Characters and Strings Tutorial::  
                    209: * Alignment Tutorial::          
                    210: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                    211: * Execution Tokens Tutorial::   
                    212: * Exceptions Tutorial::         
                    213: * Defining Words Tutorial::     
                    214: * Arrays and Records Tutorial::  
                    215: * POSTPONE Tutorial::           
                    216: * Literal Tutorial::            
                    217: * Advanced macros Tutorial::    
                    218: * Compilation Tokens Tutorial::  
                    219: * Wordlists and Search Order Tutorial::  
1.29      crook     220: 
1.24      anton     221: An Introduction to ANS Forth
                    222: 
1.67      anton     223: * Introducing the Text Interpreter::  
                    224: * Stacks and Postfix notation::  
                    225: * Your first definition::       
                    226: * How does that work?::         
                    227: * Forth is written in Forth::   
                    228: * Review - elements of a Forth system::  
                    229: * Where to go next::            
                    230: * Exercises::                   
1.24      anton     231: 
1.12      anton     232: Forth Words
                    233: 
                    234: * Notation::                    
1.65      anton     235: * Case insensitivity::          
                    236: * Comments::                    
                    237: * Boolean Flags::               
1.12      anton     238: * Arithmetic::                  
                    239: * Stack Manipulation::          
                    240: * Memory::                      
                    241: * Control Structures::          
                    242: * Defining Words::              
1.65      anton     243: * Interpretation and Compilation Semantics::  
1.47      crook     244: * Tokens for Words::            
1.81    ! anton     245: * Compiling words::             
1.65      anton     246: * The Text Interpreter::        
                    247: * Word Lists::                  
                    248: * Environmental Queries::       
1.12      anton     249: * Files::                       
                    250: * Blocks::                      
                    251: * Other I/O::                   
1.78      anton     252: * Locals::                      
                    253: * Structures::                  
                    254: * Object-oriented Forth::       
1.12      anton     255: * Programming Tools::           
                    256: * Assembler and Code Words::    
                    257: * Threading Words::             
1.65      anton     258: * Passing Commands to the OS::  
                    259: * Keeping track of Time::       
                    260: * Miscellaneous Words::         
1.12      anton     261: 
                    262: Arithmetic
                    263: 
                    264: * Single precision::            
1.67      anton     265: * Double precision::            Double-cell integer arithmetic
1.12      anton     266: * Bitwise operations::          
1.67      anton     267: * Numeric comparison::          
1.32      anton     268: * Mixed precision::             Operations with single and double-cell integers
1.12      anton     269: * Floating Point::              
                    270: 
                    271: Stack Manipulation
                    272: 
                    273: * Data stack::                  
                    274: * Floating point stack::        
                    275: * Return stack::                
                    276: * Locals stack::                
                    277: * Stack pointer manipulation::  
                    278: 
                    279: Memory
                    280: 
1.32      anton     281: * Memory model::                
                    282: * Dictionary allocation::       
                    283: * Heap Allocation::             
                    284: * Memory Access::               
                    285: * Address arithmetic::          
                    286: * Memory Blocks::               
1.12      anton     287: 
                    288: Control Structures
                    289: 
1.41      anton     290: * Selection::                   IF ... ELSE ... ENDIF
                    291: * Simple Loops::                BEGIN ...
1.32      anton     292: * Counted Loops::               DO
1.67      anton     293: * Arbitrary control structures::  
                    294: * Calls and returns::           
1.12      anton     295: * Exception Handling::          
                    296: 
                    297: Defining Words
                    298: 
1.67      anton     299: * CREATE::                      
1.44      crook     300: * Variables::                   Variables and user variables
1.67      anton     301: * Constants::                   
1.44      crook     302: * Values::                      Initialised variables
1.67      anton     303: * Colon Definitions::           
1.44      crook     304: * Anonymous Definitions::       Definitions without names
1.71      anton     305: * Supplying names::             Passing definition names as strings
1.67      anton     306: * User-defined Defining Words::  
1.44      crook     307: * Deferred words::              Allow forward references
1.67      anton     308: * Aliases::                     
1.47      crook     309: 
1.63      anton     310: User-defined Defining Words
                    311: 
                    312: * CREATE..DOES> applications::  
                    313: * CREATE..DOES> details::       
                    314: * Advanced does> usage example::  
                    315: 
1.47      crook     316: Interpretation and Compilation Semantics
                    317: 
1.67      anton     318: * Combined words::              
1.12      anton     319: 
1.71      anton     320: Tokens for Words
                    321: 
                    322: * Execution token::             represents execution/interpretation semantics
                    323: * Compilation token::           represents compilation semantics
                    324: * Name token::                  represents named words
                    325: 
1.21      crook     326: The Text Interpreter
                    327: 
1.67      anton     328: * Input Sources::               
                    329: * Number Conversion::           
                    330: * Interpret/Compile states::    
                    331: * Literals::                    
                    332: * Interpreter Directives::      
1.21      crook     333: 
1.26      crook     334: Word Lists
                    335: 
1.75      anton     336: * Vocabularies::                
1.67      anton     337: * Why use word lists?::         
1.75      anton     338: * Word list example::           
1.26      crook     339: 
                    340: Files
                    341: 
1.48      anton     342: * Forth source files::          
                    343: * General files::               
                    344: * Search Paths::                
                    345: 
                    346: Search Paths
                    347: 
1.75      anton     348: * Source Search Paths::         
1.26      crook     349: * General Search Paths::        
                    350: 
                    351: Other I/O
                    352: 
1.32      anton     353: * Simple numeric output::       Predefined formats
                    354: * Formatted numeric output::    Formatted (pictured) output
                    355: * String Formats::              How Forth stores strings in memory
1.67      anton     356: * Displaying characters and strings::  Other stuff
1.32      anton     357: * Input::                       Input
1.26      crook     358: 
                    359: Locals
                    360: 
                    361: * Gforth locals::               
                    362: * ANS Forth locals::            
                    363: 
                    364: Gforth locals
                    365: 
                    366: * Where are locals visible by name?::  
                    367: * How long do locals live?::    
1.78      anton     368: * Locals programming style::    
                    369: * Locals implementation::       
1.26      crook     370: 
1.12      anton     371: Structures
                    372: 
                    373: * Why explicit structure support?::  
                    374: * Structure Usage::             
                    375: * Structure Naming Convention::  
                    376: * Structure Implementation::    
                    377: * Structure Glossary::          
                    378: 
                    379: Object-oriented Forth
                    380: 
1.48      anton     381: * Why object-oriented programming?::  
                    382: * Object-Oriented Terminology::  
                    383: * Objects::                     
                    384: * OOF::                         
                    385: * Mini-OOF::                    
1.23      crook     386: * Comparison with other object models::  
1.12      anton     387: 
1.24      anton     388: The @file{objects.fs} model
1.12      anton     389: 
                    390: * Properties of the Objects model::  
                    391: * Basic Objects Usage::         
1.41      anton     392: * The Objects base class::      
1.12      anton     393: * Creating objects::            
                    394: * Object-Oriented Programming Style::  
                    395: * Class Binding::               
                    396: * Method conveniences::         
                    397: * Classes and Scoping::         
1.41      anton     398: * Dividing classes::            
1.12      anton     399: * Object Interfaces::           
                    400: * Objects Implementation::      
                    401: * Objects Glossary::            
                    402: 
1.24      anton     403: The @file{oof.fs} model
1.12      anton     404: 
1.67      anton     405: * Properties of the OOF model::  
                    406: * Basic OOF Usage::             
                    407: * The OOF base class::          
                    408: * Class Declaration::           
                    409: * Class Implementation::        
1.12      anton     410: 
1.24      anton     411: The @file{mini-oof.fs} model
1.23      crook     412: 
1.48      anton     413: * Basic Mini-OOF Usage::        
                    414: * Mini-OOF Example::            
                    415: * Mini-OOF Implementation::     
1.23      crook     416: 
1.78      anton     417: Programming Tools
                    418: 
                    419: * Examining::                   
                    420: * Forgetting words::            
                    421: * Debugging::                   Simple and quick.
                    422: * Assertions::                  Making your programs self-checking.
                    423: * Singlestep Debugger::         Executing your program word by word.
                    424: 
                    425: Assembler and Code Words
                    426: 
                    427: * Code and ;code::              
                    428: * Common Assembler::            Assembler Syntax
                    429: * Common Disassembler::         
                    430: * 386 Assembler::               Deviations and special cases
                    431: * Alpha Assembler::             Deviations and special cases
                    432: * MIPS assembler::              Deviations and special cases
                    433: * Other assemblers::            How to write them
                    434: 
1.12      anton     435: Tools
                    436: 
                    437: * ANS Report::                  Report the words used, sorted by wordset.
                    438: 
                    439: ANS conformance
                    440: 
                    441: * The Core Words::              
                    442: * The optional Block word set::  
                    443: * The optional Double Number word set::  
                    444: * The optional Exception word set::  
                    445: * The optional Facility word set::  
                    446: * The optional File-Access word set::  
                    447: * The optional Floating-Point word set::  
                    448: * The optional Locals word set::  
                    449: * The optional Memory-Allocation word set::  
                    450: * The optional Programming-Tools word set::  
                    451: * The optional Search-Order word set::  
                    452: 
                    453: The Core Words
                    454: 
                    455: * core-idef::                   Implementation Defined Options                   
                    456: * core-ambcond::                Ambiguous Conditions                
                    457: * core-other::                  Other System Documentation                  
                    458: 
                    459: The optional Block word set
                    460: 
                    461: * block-idef::                  Implementation Defined Options
                    462: * block-ambcond::               Ambiguous Conditions               
                    463: * block-other::                 Other System Documentation                 
                    464: 
                    465: The optional Double Number word set
                    466: 
                    467: * double-ambcond::              Ambiguous Conditions              
                    468: 
                    469: The optional Exception word set
                    470: 
                    471: * exception-idef::              Implementation Defined Options              
                    472: 
                    473: The optional Facility word set
                    474: 
                    475: * facility-idef::               Implementation Defined Options               
                    476: * facility-ambcond::            Ambiguous Conditions            
                    477: 
                    478: The optional File-Access word set
                    479: 
                    480: * file-idef::                   Implementation Defined Options
                    481: * file-ambcond::                Ambiguous Conditions                
                    482: 
                    483: The optional Floating-Point word set
                    484: 
                    485: * floating-idef::               Implementation Defined Options
                    486: * floating-ambcond::            Ambiguous Conditions            
                    487: 
                    488: The optional Locals word set
                    489: 
                    490: * locals-idef::                 Implementation Defined Options                 
                    491: * locals-ambcond::              Ambiguous Conditions              
                    492: 
                    493: The optional Memory-Allocation word set
                    494: 
                    495: * memory-idef::                 Implementation Defined Options                 
                    496: 
                    497: The optional Programming-Tools word set
                    498: 
                    499: * programming-idef::            Implementation Defined Options            
                    500: * programming-ambcond::         Ambiguous Conditions         
                    501: 
                    502: The optional Search-Order word set
                    503: 
                    504: * search-idef::                 Implementation Defined Options                 
                    505: * search-ambcond::              Ambiguous Conditions              
                    506: 
                    507: Image Files
                    508: 
1.24      anton     509: * Image Licensing Issues::      Distribution terms for images.
                    510: * Image File Background::       Why have image files?
1.67      anton     511: * Non-Relocatable Image Files::  don't always work.
1.24      anton     512: * Data-Relocatable Image Files::  are better.
1.67      anton     513: * Fully Relocatable Image Files::  better yet.
1.24      anton     514: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     515: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     516: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     517: 
                    518: Fully Relocatable Image Files
                    519: 
1.27      crook     520: * gforthmi::                    The normal way
1.12      anton     521: * cross.fs::                    The hard way
                    522: 
                    523: Engine
                    524: 
                    525: * Portability::                 
                    526: * Threading::                   
                    527: * Primitives::                  
                    528: * Performance::                 
                    529: 
                    530: Threading
                    531: 
                    532: * Scheduling::                  
                    533: * Direct or Indirect Threaded?::  
                    534: * DOES>::                       
                    535: 
                    536: Primitives
                    537: 
                    538: * Automatic Generation::        
                    539: * TOS Optimization::            
                    540: * Produced code::               
1.13      pazsan    541: 
                    542: Cross Compiler
                    543: 
1.67      anton     544: * Using the Cross Compiler::    
                    545: * How the Cross Compiler Works::  
1.13      pazsan    546: 
1.24      anton     547: @end detailmenu
1.1       anton     548: @end menu
                    549: 
1.26      crook     550: @node License, Goals, Top, Top
1.1       anton     551: @unnumbered GNU GENERAL PUBLIC LICENSE
                    552: @center Version 2, June 1991
                    553: 
                    554: @display
                    555: Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc.
                    556: 675 Mass Ave, Cambridge, MA 02139, USA
                    557: 
                    558: Everyone is permitted to copy and distribute verbatim copies
                    559: of this license document, but changing it is not allowed.
                    560: @end display
                    561: 
                    562: @unnumberedsec Preamble
                    563: 
                    564:   The licenses for most software are designed to take away your
                    565: freedom to share and change it.  By contrast, the GNU General Public
                    566: License is intended to guarantee your freedom to share and change free
                    567: software---to make sure the software is free for all its users.  This
                    568: General Public License applies to most of the Free Software
                    569: Foundation's software and to any other program whose authors commit to
                    570: using it.  (Some other Free Software Foundation software is covered by
                    571: the GNU Library General Public License instead.)  You can apply it to
                    572: your programs, too.
                    573: 
                    574:   When we speak of free software, we are referring to freedom, not
                    575: price.  Our General Public Licenses are designed to make sure that you
                    576: have the freedom to distribute copies of free software (and charge for
                    577: this service if you wish), that you receive source code or can get it
                    578: if you want it, that you can change the software or use pieces of it
                    579: in new free programs; and that you know you can do these things.
                    580: 
                    581:   To protect your rights, we need to make restrictions that forbid
                    582: anyone to deny you these rights or to ask you to surrender the rights.
                    583: These restrictions translate to certain responsibilities for you if you
                    584: distribute copies of the software, or if you modify it.
                    585: 
                    586:   For example, if you distribute copies of such a program, whether
                    587: gratis or for a fee, you must give the recipients all the rights that
                    588: you have.  You must make sure that they, too, receive or can get the
                    589: source code.  And you must show them these terms so they know their
                    590: rights.
                    591: 
                    592:   We protect your rights with two steps: (1) copyright the software, and
                    593: (2) offer you this license which gives you legal permission to copy,
                    594: distribute and/or modify the software.
                    595: 
                    596:   Also, for each author's protection and ours, we want to make certain
                    597: that everyone understands that there is no warranty for this free
                    598: software.  If the software is modified by someone else and passed on, we
                    599: want its recipients to know that what they have is not the original, so
                    600: that any problems introduced by others will not reflect on the original
                    601: authors' reputations.
                    602: 
                    603:   Finally, any free program is threatened constantly by software
                    604: patents.  We wish to avoid the danger that redistributors of a free
                    605: program will individually obtain patent licenses, in effect making the
                    606: program proprietary.  To prevent this, we have made it clear that any
                    607: patent must be licensed for everyone's free use or not licensed at all.
                    608: 
                    609:   The precise terms and conditions for copying, distribution and
                    610: modification follow.
                    611: 
                    612: @iftex
                    613: @unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
                    614: @end iftex
1.49      anton     615: @ifnottex
1.1       anton     616: @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
1.49      anton     617: @end ifnottex
1.1       anton     618: 
                    619: @enumerate 0
                    620: @item
                    621: This License applies to any program or other work which contains
                    622: a notice placed by the copyright holder saying it may be distributed
                    623: under the terms of this General Public License.  The ``Program'', below,
                    624: refers to any such program or work, and a ``work based on the Program''
                    625: means either the Program or any derivative work under copyright law:
                    626: that is to say, a work containing the Program or a portion of it,
                    627: either verbatim or with modifications and/or translated into another
                    628: language.  (Hereinafter, translation is included without limitation in
                    629: the term ``modification''.)  Each licensee is addressed as ``you''.
                    630: 
                    631: Activities other than copying, distribution and modification are not
                    632: covered by this License; they are outside its scope.  The act of
                    633: running the Program is not restricted, and the output from the Program
                    634: is covered only if its contents constitute a work based on the
                    635: Program (independent of having been made by running the Program).
                    636: Whether that is true depends on what the Program does.
                    637: 
                    638: @item
                    639: You may copy and distribute verbatim copies of the Program's
                    640: source code as you receive it, in any medium, provided that you
                    641: conspicuously and appropriately publish on each copy an appropriate
                    642: copyright notice and disclaimer of warranty; keep intact all the
                    643: notices that refer to this License and to the absence of any warranty;
                    644: and give any other recipients of the Program a copy of this License
                    645: along with the Program.
                    646: 
                    647: You may charge a fee for the physical act of transferring a copy, and
                    648: you may at your option offer warranty protection in exchange for a fee.
                    649: 
                    650: @item
                    651: You may modify your copy or copies of the Program or any portion
                    652: of it, thus forming a work based on the Program, and copy and
                    653: distribute such modifications or work under the terms of Section 1
                    654: above, provided that you also meet all of these conditions:
                    655: 
                    656: @enumerate a
                    657: @item
                    658: You must cause the modified files to carry prominent notices
                    659: stating that you changed the files and the date of any change.
                    660: 
                    661: @item
                    662: You must cause any work that you distribute or publish, that in
                    663: whole or in part contains or is derived from the Program or any
                    664: part thereof, to be licensed as a whole at no charge to all third
                    665: parties under the terms of this License.
                    666: 
                    667: @item
                    668: If the modified program normally reads commands interactively
                    669: when run, you must cause it, when started running for such
                    670: interactive use in the most ordinary way, to print or display an
                    671: announcement including an appropriate copyright notice and a
                    672: notice that there is no warranty (or else, saying that you provide
                    673: a warranty) and that users may redistribute the program under
                    674: these conditions, and telling the user how to view a copy of this
                    675: License.  (Exception: if the Program itself is interactive but
                    676: does not normally print such an announcement, your work based on
                    677: the Program is not required to print an announcement.)
                    678: @end enumerate
                    679: 
                    680: These requirements apply to the modified work as a whole.  If
                    681: identifiable sections of that work are not derived from the Program,
                    682: and can be reasonably considered independent and separate works in
                    683: themselves, then this License, and its terms, do not apply to those
                    684: sections when you distribute them as separate works.  But when you
                    685: distribute the same sections as part of a whole which is a work based
                    686: on the Program, the distribution of the whole must be on the terms of
                    687: this License, whose permissions for other licensees extend to the
                    688: entire whole, and thus to each and every part regardless of who wrote it.
                    689: 
                    690: Thus, it is not the intent of this section to claim rights or contest
                    691: your rights to work written entirely by you; rather, the intent is to
                    692: exercise the right to control the distribution of derivative or
                    693: collective works based on the Program.
                    694: 
                    695: In addition, mere aggregation of another work not based on the Program
                    696: with the Program (or with a work based on the Program) on a volume of
                    697: a storage or distribution medium does not bring the other work under
                    698: the scope of this License.
                    699: 
                    700: @item
                    701: You may copy and distribute the Program (or a work based on it,
                    702: under Section 2) in object code or executable form under the terms of
                    703: Sections 1 and 2 above provided that you also do one of the following:
                    704: 
                    705: @enumerate a
                    706: @item
                    707: Accompany it with the complete corresponding machine-readable
                    708: source code, which must be distributed under the terms of Sections
                    709: 1 and 2 above on a medium customarily used for software interchange; or,
                    710: 
                    711: @item
                    712: Accompany it with a written offer, valid for at least three
                    713: years, to give any third party, for a charge no more than your
                    714: cost of physically performing source distribution, a complete
                    715: machine-readable copy of the corresponding source code, to be
                    716: distributed under the terms of Sections 1 and 2 above on a medium
                    717: customarily used for software interchange; or,
                    718: 
                    719: @item
                    720: Accompany it with the information you received as to the offer
                    721: to distribute corresponding source code.  (This alternative is
                    722: allowed only for noncommercial distribution and only if you
                    723: received the program in object code or executable form with such
                    724: an offer, in accord with Subsection b above.)
                    725: @end enumerate
                    726: 
                    727: The source code for a work means the preferred form of the work for
                    728: making modifications to it.  For an executable work, complete source
                    729: code means all the source code for all modules it contains, plus any
                    730: associated interface definition files, plus the scripts used to
                    731: control compilation and installation of the executable.  However, as a
                    732: special exception, the source code distributed need not include
                    733: anything that is normally distributed (in either source or binary
                    734: form) with the major components (compiler, kernel, and so on) of the
                    735: operating system on which the executable runs, unless that component
                    736: itself accompanies the executable.
                    737: 
                    738: If distribution of executable or object code is made by offering
                    739: access to copy from a designated place, then offering equivalent
                    740: access to copy the source code from the same place counts as
                    741: distribution of the source code, even though third parties are not
                    742: compelled to copy the source along with the object code.
                    743: 
                    744: @item
                    745: You may not copy, modify, sublicense, or distribute the Program
                    746: except as expressly provided under this License.  Any attempt
                    747: otherwise to copy, modify, sublicense or distribute the Program is
                    748: void, and will automatically terminate your rights under this License.
                    749: However, parties who have received copies, or rights, from you under
                    750: this License will not have their licenses terminated so long as such
                    751: parties remain in full compliance.
                    752: 
                    753: @item
                    754: You are not required to accept this License, since you have not
                    755: signed it.  However, nothing else grants you permission to modify or
                    756: distribute the Program or its derivative works.  These actions are
                    757: prohibited by law if you do not accept this License.  Therefore, by
                    758: modifying or distributing the Program (or any work based on the
                    759: Program), you indicate your acceptance of this License to do so, and
                    760: all its terms and conditions for copying, distributing or modifying
                    761: the Program or works based on it.
                    762: 
                    763: @item
                    764: Each time you redistribute the Program (or any work based on the
                    765: Program), the recipient automatically receives a license from the
                    766: original licensor to copy, distribute or modify the Program subject to
                    767: these terms and conditions.  You may not impose any further
                    768: restrictions on the recipients' exercise of the rights granted herein.
                    769: You are not responsible for enforcing compliance by third parties to
                    770: this License.
                    771: 
                    772: @item
                    773: If, as a consequence of a court judgment or allegation of patent
                    774: infringement or for any other reason (not limited to patent issues),
                    775: conditions are imposed on you (whether by court order, agreement or
                    776: otherwise) that contradict the conditions of this License, they do not
                    777: excuse you from the conditions of this License.  If you cannot
                    778: distribute so as to satisfy simultaneously your obligations under this
                    779: License and any other pertinent obligations, then as a consequence you
                    780: may not distribute the Program at all.  For example, if a patent
                    781: license would not permit royalty-free redistribution of the Program by
                    782: all those who receive copies directly or indirectly through you, then
                    783: the only way you could satisfy both it and this License would be to
                    784: refrain entirely from distribution of the Program.
                    785: 
                    786: If any portion of this section is held invalid or unenforceable under
                    787: any particular circumstance, the balance of the section is intended to
                    788: apply and the section as a whole is intended to apply in other
                    789: circumstances.
                    790: 
                    791: It is not the purpose of this section to induce you to infringe any
                    792: patents or other property right claims or to contest validity of any
                    793: such claims; this section has the sole purpose of protecting the
                    794: integrity of the free software distribution system, which is
                    795: implemented by public license practices.  Many people have made
                    796: generous contributions to the wide range of software distributed
                    797: through that system in reliance on consistent application of that
                    798: system; it is up to the author/donor to decide if he or she is willing
                    799: to distribute software through any other system and a licensee cannot
                    800: impose that choice.
                    801: 
                    802: This section is intended to make thoroughly clear what is believed to
                    803: be a consequence of the rest of this License.
                    804: 
                    805: @item
                    806: If the distribution and/or use of the Program is restricted in
                    807: certain countries either by patents or by copyrighted interfaces, the
                    808: original copyright holder who places the Program under this License
                    809: may add an explicit geographical distribution limitation excluding
                    810: those countries, so that distribution is permitted only in or among
                    811: countries not thus excluded.  In such case, this License incorporates
                    812: the limitation as if written in the body of this License.
                    813: 
                    814: @item
                    815: The Free Software Foundation may publish revised and/or new versions
                    816: of the General Public License from time to time.  Such new versions will
                    817: be similar in spirit to the present version, but may differ in detail to
                    818: address new problems or concerns.
                    819: 
                    820: Each version is given a distinguishing version number.  If the Program
                    821: specifies a version number of this License which applies to it and ``any
                    822: later version'', you have the option of following the terms and conditions
                    823: either of that version or of any later version published by the Free
                    824: Software Foundation.  If the Program does not specify a version number of
                    825: this License, you may choose any version ever published by the Free Software
                    826: Foundation.
                    827: 
                    828: @item
                    829: If you wish to incorporate parts of the Program into other free
                    830: programs whose distribution conditions are different, write to the author
                    831: to ask for permission.  For software which is copyrighted by the Free
                    832: Software Foundation, write to the Free Software Foundation; we sometimes
                    833: make exceptions for this.  Our decision will be guided by the two goals
                    834: of preserving the free status of all derivatives of our free software and
                    835: of promoting the sharing and reuse of software generally.
                    836: 
                    837: @iftex
                    838: @heading NO WARRANTY
                    839: @end iftex
1.49      anton     840: @ifnottex
1.1       anton     841: @center NO WARRANTY
1.49      anton     842: @end ifnottex
1.1       anton     843: 
                    844: @item
                    845: BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
                    846: FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
                    847: OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
                    848: PROVIDE THE PROGRAM ``AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
                    849: OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
                    850: MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
                    851: TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
                    852: PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
                    853: REPAIR OR CORRECTION.
                    854: 
                    855: @item
                    856: IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
                    857: WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
                    858: REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
                    859: INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
                    860: OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
                    861: TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
                    862: YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
                    863: PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
                    864: POSSIBILITY OF SUCH DAMAGES.
                    865: @end enumerate
                    866: 
                    867: @iftex
                    868: @heading END OF TERMS AND CONDITIONS
                    869: @end iftex
1.49      anton     870: @ifnottex
1.1       anton     871: @center END OF TERMS AND CONDITIONS
1.49      anton     872: @end ifnottex
1.1       anton     873: 
                    874: @page
                    875: @unnumberedsec How to Apply These Terms to Your New Programs
                    876: 
                    877:   If you develop a new program, and you want it to be of the greatest
                    878: possible use to the public, the best way to achieve this is to make it
                    879: free software which everyone can redistribute and change under these terms.
                    880: 
                    881:   To do so, attach the following notices to the program.  It is safest
                    882: to attach them to the start of each source file to most effectively
                    883: convey the exclusion of warranty; and each file should have at least
                    884: the ``copyright'' line and a pointer to where the full notice is found.
                    885: 
                    886: @smallexample
                    887: @var{one line to give the program's name and a brief idea of what it does.}
                    888: Copyright (C) 19@var{yy}  @var{name of author}
                    889: 
                    890: This program is free software; you can redistribute it and/or modify 
                    891: it under the terms of the GNU General Public License as published by 
                    892: the Free Software Foundation; either version 2 of the License, or 
                    893: (at your option) any later version.
                    894: 
                    895: This program is distributed in the hope that it will be useful,
                    896: but WITHOUT ANY WARRANTY; without even the implied warranty of
                    897: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                    898: GNU General Public License for more details.
                    899: 
                    900: You should have received a copy of the GNU General Public License
                    901: along with this program; if not, write to the Free Software
                    902: Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
                    903: @end smallexample
                    904: 
                    905: Also add information on how to contact you by electronic and paper mail.
                    906: 
                    907: If the program is interactive, make it output a short notice like this
                    908: when it starts in an interactive mode:
                    909: 
                    910: @smallexample
                    911: Gnomovision version 69, Copyright (C) 19@var{yy} @var{name of author}
                    912: Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
                    913: type `show w'.  
                    914: This is free software, and you are welcome to redistribute it 
                    915: under certain conditions; type `show c' for details.
                    916: @end smallexample
                    917: 
                    918: The hypothetical commands @samp{show w} and @samp{show c} should show
                    919: the appropriate parts of the General Public License.  Of course, the
                    920: commands you use may be called something other than @samp{show w} and
                    921: @samp{show c}; they could even be mouse-clicks or menu items---whatever
                    922: suits your program.
                    923: 
                    924: You should also get your employer (if you work as a programmer) or your
                    925: school, if any, to sign a ``copyright disclaimer'' for the program, if
                    926: necessary.  Here is a sample; alter the names:
                    927: 
                    928: @smallexample
                    929: Yoyodyne, Inc., hereby disclaims all copyright interest in the program
                    930: `Gnomovision' (which makes passes at compilers) written by James Hacker.
                    931: 
                    932: @var{signature of Ty Coon}, 1 April 1989
                    933: Ty Coon, President of Vice
                    934: @end smallexample
                    935: 
                    936: This General Public License does not permit incorporating your program into
                    937: proprietary programs.  If your program is a subroutine library, you may
                    938: consider it more useful to permit linking proprietary applications with the
                    939: library.  If this is what you want to do, use the GNU Library General
                    940: Public License instead of this License.
                    941: 
                    942: @iftex
                    943: @unnumbered Preface
                    944: @cindex Preface
1.21      crook     945: This manual documents Gforth. Some introductory material is provided for
                    946: readers who are unfamiliar with Forth or who are migrating to Gforth
                    947: from other Forth compilers. However, this manual is primarily a
                    948: reference manual.
1.1       anton     949: @end iftex
                    950: 
1.28      crook     951: @comment TODO much more blurb here.
1.26      crook     952: 
                    953: @c ******************************************************************
1.29      crook     954: @node Goals, Gforth Environment, License, Top
1.26      crook     955: @comment node-name,     next,           previous, up
                    956: @chapter Goals of Gforth
                    957: @cindex goals of the Gforth project
                    958: The goal of the Gforth Project is to develop a standard model for
                    959: ANS Forth. This can be split into several subgoals:
                    960: 
                    961: @itemize @bullet
                    962: @item
                    963: Gforth should conform to the ANS Forth Standard.
                    964: @item
                    965: It should be a model, i.e. it should define all the
                    966: implementation-dependent things.
                    967: @item
                    968: It should become standard, i.e. widely accepted and used. This goal
                    969: is the most difficult one.
                    970: @end itemize
                    971: 
                    972: To achieve these goals Gforth should be
                    973: @itemize @bullet
                    974: @item
                    975: Similar to previous models (fig-Forth, F83)
                    976: @item
                    977: Powerful. It should provide for all the things that are considered
                    978: necessary today and even some that are not yet considered necessary.
                    979: @item
                    980: Efficient. It should not get the reputation of being exceptionally
                    981: slow.
                    982: @item
                    983: Free.
                    984: @item
                    985: Available on many machines/easy to port.
                    986: @end itemize
                    987: 
                    988: Have we achieved these goals? Gforth conforms to the ANS Forth
                    989: standard. It may be considered a model, but we have not yet documented
                    990: which parts of the model are stable and which parts we are likely to
                    991: change. It certainly has not yet become a de facto standard, but it
                    992: appears to be quite popular. It has some similarities to and some
                    993: differences from previous models. It has some powerful features, but not
                    994: yet everything that we envisioned. We certainly have achieved our
1.65      anton     995: execution speed goals (@pxref{Performance})@footnote{However, in 1998
                    996: the bar was raised when the major commercial Forth vendors switched to
                    997: native code compilers.}.  It is free and available on many machines.
1.29      crook     998: 
1.26      crook     999: @c ******************************************************************
1.48      anton    1000: @node Gforth Environment, Tutorial, Goals, Top
1.29      crook    1001: @chapter Gforth Environment
                   1002: @cindex Gforth environment
1.21      crook    1003: 
1.45      crook    1004: Note: ultimately, the Gforth man page will be auto-generated from the
1.29      crook    1005: material in this chapter.
1.21      crook    1006: 
                   1007: @menu
1.29      crook    1008: * Invoking Gforth::             Getting in
                   1009: * Leaving Gforth::              Getting out
                   1010: * Command-line editing::        
1.48      anton    1011: * Environment variables::       that affect how Gforth starts up
1.29      crook    1012: * Gforth Files::                What gets installed and where
1.48      anton    1013: * Startup speed::               When 35ms is not fast enough ...
1.21      crook    1014: @end menu
                   1015: 
1.49      anton    1016: For related information about the creation of images see @ref{Image Files}.
1.29      crook    1017: 
1.21      crook    1018: @comment ----------------------------------------------
1.48      anton    1019: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29      crook    1020: @section Invoking Gforth
                   1021: @cindex invoking Gforth
                   1022: @cindex running Gforth
                   1023: @cindex command-line options
                   1024: @cindex options on the command line
                   1025: @cindex flags on the command line
1.21      crook    1026: 
1.30      anton    1027: Gforth is made up of two parts; an executable ``engine'' (named
                   1028: @file{gforth} or @file{gforth-fast}) and an image file. To start it, you
                   1029: will usually just say @code{gforth} -- this automatically loads the
                   1030: default image file @file{gforth.fi}. In many other cases the default
                   1031: Gforth image will be invoked like this:
1.21      crook    1032: @example
1.30      anton    1033: gforth [file | -e forth-code] ...
1.21      crook    1034: @end example
1.29      crook    1035: @noindent
                   1036: This interprets the contents of the files and the Forth code in the order they
                   1037: are given.
1.21      crook    1038: 
1.30      anton    1039: In addition to the @file{gforth} engine, there is also an engine called
                   1040: @file{gforth-fast}, which is faster, but gives less informative error
                   1041: messages (@pxref{Error messages}).
                   1042: 
1.29      crook    1043: In general, the command line looks like this:
1.21      crook    1044: 
                   1045: @example
1.30      anton    1046: gforth[-fast] [engine options] [image options]
1.21      crook    1047: @end example
                   1048: 
1.30      anton    1049: The engine options must come before the rest of the command
1.29      crook    1050: line. They are:
1.26      crook    1051: 
1.29      crook    1052: @table @code
                   1053: @cindex -i, command-line option
                   1054: @cindex --image-file, command-line option
                   1055: @item --image-file @i{file}
                   1056: @itemx -i @i{file}
                   1057: Loads the Forth image @i{file} instead of the default
                   1058: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook    1059: 
1.39      anton    1060: @cindex --appl-image, command-line option
                   1061: @item --appl-image @i{file}
                   1062: Loads the image @i{file} and leaves all further command-line arguments
1.65      anton    1063: to the image (instead of processing them as engine options).  This is
                   1064: useful for building executable application images on Unix, built with
1.39      anton    1065: @code{gforthmi --application ...}.
                   1066: 
1.29      crook    1067: @cindex --path, command-line option
                   1068: @cindex -p, command-line option
                   1069: @item --path @i{path}
                   1070: @itemx -p @i{path}
                   1071: Uses @i{path} for searching the image file and Forth source code files
                   1072: instead of the default in the environment variable @code{GFORTHPATH} or
                   1073: the path specified at installation time (e.g.,
                   1074: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                   1075: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook    1076: 
1.29      crook    1077: @cindex --dictionary-size, command-line option
                   1078: @cindex -m, command-line option
                   1079: @cindex @i{size} parameters for command-line options
                   1080: @cindex size of the dictionary and the stacks
                   1081: @item --dictionary-size @i{size}
                   1082: @itemx -m @i{size}
                   1083: Allocate @i{size} space for the Forth dictionary space instead of
                   1084: using the default specified in the image (typically 256K). The
                   1085: @i{size} specification for this and subsequent options consists of
                   1086: an integer and a unit (e.g.,
                   1087: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                   1088: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                   1089: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                   1090: @code{e} is used.
1.21      crook    1091: 
1.29      crook    1092: @cindex --data-stack-size, command-line option
                   1093: @cindex -d, command-line option
                   1094: @item --data-stack-size @i{size}
                   1095: @itemx -d @i{size}
                   1096: Allocate @i{size} space for the data stack instead of using the
                   1097: default specified in the image (typically 16K).
1.21      crook    1098: 
1.29      crook    1099: @cindex --return-stack-size, command-line option
                   1100: @cindex -r, command-line option
                   1101: @item --return-stack-size @i{size}
                   1102: @itemx -r @i{size}
                   1103: Allocate @i{size} space for the return stack instead of using the
                   1104: default specified in the image (typically 15K).
1.21      crook    1105: 
1.29      crook    1106: @cindex --fp-stack-size, command-line option
                   1107: @cindex -f, command-line option
                   1108: @item --fp-stack-size @i{size}
                   1109: @itemx -f @i{size}
                   1110: Allocate @i{size} space for the floating point stack instead of
                   1111: using the default specified in the image (typically 15.5K). In this case
                   1112: the unit specifier @code{e} refers to floating point numbers.
1.21      crook    1113: 
1.48      anton    1114: @cindex --locals-stack-size, command-line option
                   1115: @cindex -l, command-line option
                   1116: @item --locals-stack-size @i{size}
                   1117: @itemx -l @i{size}
                   1118: Allocate @i{size} space for the locals stack instead of using the
                   1119: default specified in the image (typically 14.5K).
                   1120: 
                   1121: @cindex -h, command-line option
                   1122: @cindex --help, command-line option
                   1123: @item --help
                   1124: @itemx -h
                   1125: Print a message about the command-line options
                   1126: 
                   1127: @cindex -v, command-line option
                   1128: @cindex --version, command-line option
                   1129: @item --version
                   1130: @itemx -v
                   1131: Print version and exit
                   1132: 
                   1133: @cindex --debug, command-line option
                   1134: @item --debug
                   1135: Print some information useful for debugging on startup.
                   1136: 
                   1137: @cindex --offset-image, command-line option
                   1138: @item --offset-image
                   1139: Start the dictionary at a slightly different position than would be used
                   1140: otherwise (useful for creating data-relocatable images,
                   1141: @pxref{Data-Relocatable Image Files}).
                   1142: 
                   1143: @cindex --no-offset-im, command-line option
                   1144: @item --no-offset-im
                   1145: Start the dictionary at the normal position.
                   1146: 
                   1147: @cindex --clear-dictionary, command-line option
                   1148: @item --clear-dictionary
                   1149: Initialize all bytes in the dictionary to 0 before loading the image
                   1150: (@pxref{Data-Relocatable Image Files}).
                   1151: 
                   1152: @cindex --die-on-signal, command-line-option
                   1153: @item --die-on-signal
                   1154: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                   1155: or the segmentation violation SIGSEGV) by translating it into a Forth
                   1156: @code{THROW}. With this option, Gforth exits if it receives such a
                   1157: signal. This option is useful when the engine and/or the image might be
                   1158: severely broken (such that it causes another signal before recovering
                   1159: from the first); this option avoids endless loops in such cases.
                   1160: @end table
                   1161: 
                   1162: @cindex loading files at startup
                   1163: @cindex executing code on startup
                   1164: @cindex batch processing with Gforth
                   1165: As explained above, the image-specific command-line arguments for the
                   1166: default image @file{gforth.fi} consist of a sequence of filenames and
                   1167: @code{-e @var{forth-code}} options that are interpreted in the sequence
                   1168: in which they are given. The @code{-e @var{forth-code}} or
                   1169: @code{--evaluate @var{forth-code}} option evaluates the Forth
                   1170: code. This option takes only one argument; if you want to evaluate more
                   1171: Forth words, you have to quote them or use @code{-e} several times. To exit
                   1172: after processing the command line (instead of entering interactive mode)
                   1173: append @code{-e bye} to the command line.
                   1174: 
                   1175: @cindex versions, invoking other versions of Gforth
                   1176: If you have several versions of Gforth installed, @code{gforth} will
                   1177: invoke the version that was installed last. @code{gforth-@i{version}}
                   1178: invokes a specific version. If your environment contains the variable
                   1179: @code{GFORTHPATH}, you may want to override it by using the
                   1180: @code{--path} option.
                   1181: 
                   1182: Not yet implemented:
                   1183: On startup the system first executes the system initialization file
                   1184: (unless the option @code{--no-init-file} is given; note that the system
                   1185: resulting from using this option may not be ANS Forth conformant). Then
                   1186: the user initialization file @file{.gforth.fs} is executed, unless the
1.62      crook    1187: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48      anton    1188: then in @file{~}, then in the normal path (see above).
                   1189: 
                   1190: 
                   1191: 
                   1192: @comment ----------------------------------------------
                   1193: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                   1194: @section Leaving Gforth
                   1195: @cindex Gforth - leaving
                   1196: @cindex leaving Gforth
                   1197: 
                   1198: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                   1199: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                   1200: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49      anton    1201: data are discarded.  For ways of saving the state of the system before
                   1202: leaving Gforth see @ref{Image Files}.
1.48      anton    1203: 
                   1204: doc-bye
                   1205: 
                   1206: 
                   1207: @comment ----------------------------------------------
1.65      anton    1208: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48      anton    1209: @section Command-line editing
                   1210: @cindex command-line editing
                   1211: 
                   1212: Gforth maintains a history file that records every line that you type to
                   1213: the text interpreter. This file is preserved between sessions, and is
                   1214: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
                   1215: repeatedly you can recall successively older commands from this (or
                   1216: previous) session(s). The full list of command-line editing facilities is:
                   1217: 
                   1218: @itemize @bullet
                   1219: @item
                   1220: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
                   1221: commands from the history buffer.
                   1222: @item
                   1223: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
                   1224: from the history buffer.
                   1225: @item
                   1226: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
                   1227: @item
                   1228: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
                   1229: @item
                   1230: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
                   1231: closing up the line.
                   1232: @item
                   1233: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
                   1234: @item
                   1235: @kbd{Ctrl-a} to move the cursor to the start of the line.
                   1236: @item
                   1237: @kbd{Ctrl-e} to move the cursor to the end of the line.
                   1238: @item
                   1239: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
                   1240: line.
                   1241: @item
                   1242: @key{TAB} to step through all possible full-word completions of the word
                   1243: currently being typed.
                   1244: @item
1.65      anton    1245: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
                   1246: using @code{bye}). 
                   1247: @item
                   1248: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
                   1249: character under the cursor.
1.48      anton    1250: @end itemize
                   1251: 
                   1252: When editing, displayable characters are inserted to the left of the
                   1253: cursor position; the line is always in ``insert'' (as opposed to
                   1254: ``overstrike'') mode.
                   1255: 
                   1256: @cindex history file
                   1257: @cindex @file{.gforth-history}
                   1258: On Unix systems, the history file is @file{~/.gforth-history} by
                   1259: default@footnote{i.e. it is stored in the user's home directory.}. You
                   1260: can find out the name and location of your history file using:
                   1261: 
                   1262: @example 
                   1263: history-file type \ Unix-class systems
                   1264: 
                   1265: history-file type \ Other systems
                   1266: history-dir  type
                   1267: @end example
                   1268: 
                   1269: If you enter long definitions by hand, you can use a text editor to
                   1270: paste them out of the history file into a Forth source file for reuse at
                   1271: a later time.
                   1272: 
                   1273: Gforth never trims the size of the history file, so you should do this
                   1274: periodically, if necessary.
                   1275: 
                   1276: @comment this is all defined in history.fs
                   1277: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
                   1278: @comment chosen?
                   1279: 
                   1280: 
                   1281: @comment ----------------------------------------------
1.65      anton    1282: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48      anton    1283: @section Environment variables
                   1284: @cindex environment variables
                   1285: 
                   1286: Gforth uses these environment variables:
                   1287: 
                   1288: @itemize @bullet
                   1289: @item
                   1290: @cindex @code{GFORTHHIST} -- environment variable
                   1291: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
                   1292: open/create the history file, @file{.gforth-history}. Default:
                   1293: @code{$HOME}.
                   1294: 
                   1295: @item
                   1296: @cindex @code{GFORTHPATH} -- environment variable
                   1297: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
                   1298: for Forth source-code files.
                   1299: 
                   1300: @item
                   1301: @cindex @code{GFORTH} -- environment variable
1.49      anton    1302: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1303: 
                   1304: @item
                   1305: @cindex @code{GFORTHD} -- environment variable
1.62      crook    1306: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1307: 
                   1308: @item
                   1309: @cindex @code{TMP}, @code{TEMP} - environment variable
                   1310: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
                   1311: location for the history file.
                   1312: @end itemize
                   1313: 
                   1314: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1315: @comment mentioning these.
                   1316: 
                   1317: All the Gforth environment variables default to sensible values if they
                   1318: are not set.
                   1319: 
                   1320: 
                   1321: @comment ----------------------------------------------
                   1322: @node Gforth Files, Startup speed, Environment variables, Gforth Environment
                   1323: @section Gforth files
                   1324: @cindex Gforth files
                   1325: 
                   1326: When you install Gforth on a Unix system, it installs files in these
                   1327: locations by default:
                   1328: 
                   1329: @itemize @bullet
                   1330: @item
                   1331: @file{/usr/local/bin/gforth}
                   1332: @item
                   1333: @file{/usr/local/bin/gforthmi}
                   1334: @item
                   1335: @file{/usr/local/man/man1/gforth.1} - man page.
                   1336: @item
                   1337: @file{/usr/local/info} - the Info version of this manual.
                   1338: @item
                   1339: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
                   1340: @item
                   1341: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
                   1342: @item
                   1343: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
                   1344: @item
                   1345: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
                   1346: @end itemize
                   1347: 
                   1348: You can select different places for installation by using
                   1349: @code{configure} options (listed with @code{configure --help}).
                   1350: 
                   1351: @comment ----------------------------------------------
                   1352: @node Startup speed,  , Gforth Files, Gforth Environment
                   1353: @section Startup speed
                   1354: @cindex Startup speed
                   1355: @cindex speed, startup
                   1356: 
                   1357: If Gforth is used for CGI scripts or in shell scripts, its startup
                   1358: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
                   1359: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
                   1360: system time.
                   1361: 
                   1362: If startup speed is a problem, you may consider the following ways to
                   1363: improve it; or you may consider ways to reduce the number of startups
1.62      crook    1364: (for example, by using Fast-CGI).
1.48      anton    1365: 
                   1366: The first step to improve startup speed is to statically link Gforth, by
                   1367: building it with @code{XLDFLAGS=-static}.  This requires more memory for
                   1368: the code and will therefore slow down the first invocation, but
                   1369: subsequent invocations avoid the dynamic linking overhead.  Another
                   1370: disadvantage is that Gforth won't profit from library upgrades.  As a
                   1371: result, @code{gforth-static -e bye} takes about 17.1ms user and
                   1372: 8.2ms system time.
                   1373: 
                   1374: The next step to improve startup speed is to use a non-relocatable image
1.65      anton    1375: (@pxref{Non-Relocatable Image Files}).  You can create this image with
1.48      anton    1376: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
                   1377: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
                   1378: and a part of the copy-on-write overhead.  The disadvantage is that the
1.62      crook    1379: non-relocatable image does not work if the OS gives Gforth a different
1.48      anton    1380: address for the dictionary, for whatever reason; so you better provide a
                   1381: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
                   1382: bye} takes about 15.3ms user and 7.5ms system time.
                   1383: 
                   1384: The final step is to disable dictionary hashing in Gforth.  Gforth
                   1385: builds the hash table on startup, which takes much of the startup
                   1386: overhead. You can do this by commenting out the @code{include hash.fs}
                   1387: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
                   1388: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
                   1389: The disadvantages are that functionality like @code{table} and
                   1390: @code{ekey} is missing and that text interpretation (e.g., compiling)
                   1391: now takes much longer. So, you should only use this method if there is
                   1392: no significant text interpretation to perform (the script should be
1.62      crook    1393: compiled into the image, amongst other things).  @code{gforth-static -i
1.48      anton    1394: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
                   1395: 
                   1396: @c ******************************************************************
                   1397: @node Tutorial, Introduction, Gforth Environment, Top
                   1398: @chapter Forth Tutorial
                   1399: @cindex Tutorial
                   1400: @cindex Forth Tutorial
                   1401: 
1.67      anton    1402: @c Topics from nac's Introduction that could be mentioned:
                   1403: @c press <ret> after each line
                   1404: @c Prompt
                   1405: @c numbers vs. words in dictionary on text interpretation
                   1406: @c what happens on redefinition
                   1407: @c parsing words (in particular, defining words)
                   1408: 
1.62      crook    1409: This tutorial can be used with any ANS-compliant Forth; any
                   1410: Gforth-specific features are marked as such and you can skip them if you
                   1411: work with another Forth.  This tutorial does not explain all features of
                   1412: Forth, just enough to get you started and give you some ideas about the
                   1413: facilities available in Forth.  Read the rest of the manual and the
                   1414: standard when you are through this.
1.48      anton    1415: 
                   1416: The intended way to use this tutorial is that you work through it while
                   1417: sitting in front of the console, take a look at the examples and predict
                   1418: what they will do, then try them out; if the outcome is not as expected,
                   1419: find out why (e.g., by trying out variations of the example), so you
                   1420: understand what's going on.  There are also some assignments that you
                   1421: should solve.
                   1422: 
                   1423: This tutorial assumes that you have programmed before and know what,
                   1424: e.g., a loop is.
                   1425: 
                   1426: @c !! explain compat library
                   1427: 
                   1428: @menu
                   1429: * Starting Gforth Tutorial::    
                   1430: * Syntax Tutorial::             
                   1431: * Crash Course Tutorial::       
                   1432: * Stack Tutorial::              
                   1433: * Arithmetics Tutorial::        
                   1434: * Stack Manipulation Tutorial::  
                   1435: * Using files for Forth code Tutorial::  
                   1436: * Comments Tutorial::           
                   1437: * Colon Definitions Tutorial::  
                   1438: * Decompilation Tutorial::      
                   1439: * Stack-Effect Comments Tutorial::  
                   1440: * Types Tutorial::              
                   1441: * Factoring Tutorial::          
                   1442: * Designing the stack effect Tutorial::  
                   1443: * Local Variables Tutorial::    
                   1444: * Conditional execution Tutorial::  
                   1445: * Flags and Comparisons Tutorial::  
                   1446: * General Loops Tutorial::      
                   1447: * Counted loops Tutorial::      
                   1448: * Recursion Tutorial::          
                   1449: * Leaving definitions or loops Tutorial::  
                   1450: * Return Stack Tutorial::       
                   1451: * Memory Tutorial::             
                   1452: * Characters and Strings Tutorial::  
                   1453: * Alignment Tutorial::          
                   1454: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1455: * Execution Tokens Tutorial::   
                   1456: * Exceptions Tutorial::         
                   1457: * Defining Words Tutorial::     
                   1458: * Arrays and Records Tutorial::  
                   1459: * POSTPONE Tutorial::           
                   1460: * Literal Tutorial::            
                   1461: * Advanced macros Tutorial::    
                   1462: * Compilation Tokens Tutorial::  
                   1463: * Wordlists and Search Order Tutorial::  
                   1464: @end menu
                   1465: 
                   1466: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1467: @section Starting Gforth
1.66      anton    1468: @cindex starting Gforth tutorial
1.48      anton    1469: You can start Gforth by typing its name:
                   1470: 
                   1471: @example
                   1472: gforth
                   1473: @end example
                   1474: 
                   1475: That puts you into interactive mode; you can leave Gforth by typing
                   1476: @code{bye}.  While in Gforth, you can edit the command line and access
                   1477: the command line history with cursor keys, similar to bash.
                   1478: 
                   1479: 
                   1480: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1481: @section Syntax
1.66      anton    1482: @cindex syntax tutorial
1.48      anton    1483: 
                   1484: A @dfn{word} is a sequence of arbitrary characters (expcept white
                   1485: space).  Words are separated by white space.  E.g., each of the
                   1486: following lines contains exactly one word:
                   1487: 
                   1488: @example
                   1489: word
                   1490: !@@#$%^&*()
                   1491: 1234567890
                   1492: 5!a
                   1493: @end example
                   1494: 
                   1495: A frequent beginner's error is to leave away necessary white space,
                   1496: resulting in an error like @samp{Undefined word}; so if you see such an
                   1497: error, check if you have put spaces wherever necessary.
                   1498: 
                   1499: @example
                   1500: ." hello, world" \ correct
                   1501: ."hello, world"  \ gives an "Undefined word" error
                   1502: @end example
                   1503: 
1.65      anton    1504: Gforth and most other Forth systems ignore differences in case (they are
1.48      anton    1505: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1506: your system is case-sensitive, you may have to type all the examples
                   1507: given here in upper case.
                   1508: 
                   1509: 
                   1510: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1511: @section Crash Course
                   1512: 
                   1513: Type
                   1514: 
                   1515: @example
                   1516: 0 0 !
                   1517: here execute
                   1518: ' catch >body 20 erase abort
                   1519: ' (quit) >body 20 erase
                   1520: @end example
                   1521: 
                   1522: The last two examples are guaranteed to destroy parts of Gforth (and
                   1523: most other systems), so you better leave Gforth afterwards (if it has
                   1524: not finished by itself).  On some systems you may have to kill gforth
                   1525: from outside (e.g., in Unix with @code{kill}).
                   1526: 
                   1527: Now that you know how to produce crashes (and that there's not much to
                   1528: them), let's learn how to produce meaningful programs.
                   1529: 
                   1530: 
                   1531: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1532: @section Stack
1.66      anton    1533: @cindex stack tutorial
1.48      anton    1534: 
                   1535: The most obvious feature of Forth is the stack.  When you type in a
                   1536: number, it is pushed on the stack.  You can display the content of the
                   1537: stack with @code{.s}.
                   1538: 
                   1539: @example
                   1540: 1 2 .s
                   1541: 3 .s
                   1542: @end example
                   1543: 
                   1544: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1545: appear in @code{.s} output as they appeared in the input.
                   1546: 
                   1547: You can print the top of stack element with @code{.}.
                   1548: 
                   1549: @example
                   1550: 1 2 3 . . .
                   1551: @end example
                   1552: 
                   1553: In general, words consume their stack arguments (@code{.s} is an
                   1554: exception).
                   1555: 
                   1556: @assignment
                   1557: What does the stack contain after @code{5 6 7 .}?
                   1558: @endassignment
                   1559: 
                   1560: 
                   1561: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1562: @section Arithmetics
1.66      anton    1563: @cindex arithmetics tutorial
1.48      anton    1564: 
                   1565: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1566: operate on the top two stack items:
                   1567: 
                   1568: @example
1.67      anton    1569: 2 2 .s
                   1570: + .s
                   1571: .
1.48      anton    1572: 2 1 - .
                   1573: 7 3 mod .
                   1574: @end example
                   1575: 
                   1576: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1577: as in the corresponding infix expression (this is generally the case in
                   1578: Forth).
                   1579: 
                   1580: Parentheses are superfluous (and not available), because the order of
                   1581: the words unambiguously determines the order of evaluation and the
                   1582: operands:
                   1583: 
                   1584: @example
                   1585: 3 4 + 5 * .
                   1586: 3 4 5 * + .
                   1587: @end example
                   1588: 
                   1589: @assignment
                   1590: What are the infix expressions corresponding to the Forth code above?
                   1591: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1592: known as Postfix or RPN (Reverse Polish Notation).}.
                   1593: @endassignment
                   1594: 
                   1595: To change the sign, use @code{negate}:
                   1596: 
                   1597: @example
                   1598: 2 negate .
                   1599: @end example
                   1600: 
                   1601: @assignment
                   1602: Convert -(-3)*4-5 to Forth.
                   1603: @endassignment
                   1604: 
                   1605: @code{/mod} performs both @code{/} and @code{mod}.
                   1606: 
                   1607: @example
                   1608: 7 3 /mod . .
                   1609: @end example
                   1610: 
1.66      anton    1611: Reference: @ref{Arithmetic}.
                   1612: 
                   1613: 
1.48      anton    1614: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1615: @section Stack Manipulation
1.66      anton    1616: @cindex stack manipulation tutorial
1.48      anton    1617: 
                   1618: Stack manipulation words rearrange the data on the stack.
                   1619: 
                   1620: @example
                   1621: 1 .s drop .s
                   1622: 1 .s dup .s drop drop .s
                   1623: 1 2 .s over .s drop drop drop
                   1624: 1 2 .s swap .s drop drop
                   1625: 1 2 3 .s rot .s drop drop drop
                   1626: @end example
                   1627: 
                   1628: These are the most important stack manipulation words.  There are also
                   1629: variants that manipulate twice as many stack items:
                   1630: 
                   1631: @example
                   1632: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1633: @end example
                   1634: 
                   1635: Two more stack manipulation words are:
                   1636: 
                   1637: @example
                   1638: 1 2 .s nip .s drop
                   1639: 1 2 .s tuck .s 2drop drop
                   1640: @end example
                   1641: 
                   1642: @assignment
                   1643: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1644: manipulation words.
                   1645: 
                   1646: @example
                   1647: Given:          How do you get:
                   1648: 1 2 3           3 2 1           
                   1649: 1 2 3           1 2 3 2                 
                   1650: 1 2 3           1 2 3 3                 
                   1651: 1 2 3           1 3 3           
                   1652: 1 2 3           2 1 3           
                   1653: 1 2 3 4         4 3 2 1         
                   1654: 1 2 3           1 2 3 1 2 3             
                   1655: 1 2 3 4         1 2 3 4 1 2             
                   1656: 1 2 3
                   1657: 1 2 3           1 2 3 4                 
                   1658: 1 2 3           1 3             
                   1659: @end example
                   1660: @endassignment
                   1661: 
                   1662: @example
                   1663: 5 dup * .
                   1664: @end example
                   1665: 
                   1666: @assignment
                   1667: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1668: Write a piece of Forth code that expects two numbers on the stack
                   1669: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1670: @code{(a-b)(a+1)}.
                   1671: @endassignment
                   1672: 
1.66      anton    1673: Reference: @ref{Stack Manipulation}.
                   1674: 
                   1675: 
1.48      anton    1676: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1677: @section Using files for Forth code
1.66      anton    1678: @cindex loading Forth code, tutorial
                   1679: @cindex files containing Forth code, tutorial
1.48      anton    1680: 
                   1681: While working at the Forth command line is convenient for one-line
                   1682: examples and short one-off code, you probably want to store your source
                   1683: code in files for convenient editing and persistence.  You can use your
                   1684: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
                   1685: Gforth}) to create @var{file} and use
                   1686: 
                   1687: @example
                   1688: s" @var{file}" included
                   1689: @end example
                   1690: 
                   1691: to load it into your Forth system.  The file name extension I use for
                   1692: Forth files is @samp{.fs}.
                   1693: 
                   1694: You can easily start Gforth with some files loaded like this:
                   1695: 
                   1696: @example
                   1697: gforth @var{file1} @var{file2}
                   1698: @end example
                   1699: 
                   1700: If an error occurs during loading these files, Gforth terminates,
                   1701: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1702: a Gforth command line.  Starting the Forth system every time gives you a
                   1703: clean start every time, without interference from the results of earlier
                   1704: tries.
                   1705: 
                   1706: I often put all the tests in a file, then load the code and run the
                   1707: tests with
                   1708: 
                   1709: @example
                   1710: gforth @var{code} @var{tests} -e bye
                   1711: @end example
                   1712: 
                   1713: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1714: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1715: restart this command without ado.
                   1716: 
                   1717: The advantage of this approach is that the tests can be repeated easily
                   1718: every time the program ist changed, making it easy to catch bugs
                   1719: introduced by the change.
                   1720: 
1.66      anton    1721: Reference: @ref{Forth source files}.
                   1722: 
1.48      anton    1723: 
                   1724: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1725: @section Comments
1.66      anton    1726: @cindex comments tutorial
1.48      anton    1727: 
                   1728: @example
                   1729: \ That's a comment; it ends at the end of the line
                   1730: ( Another comment; it ends here: )  .s
                   1731: @end example
                   1732: 
                   1733: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1734: separated with white space from the following text.
                   1735: 
                   1736: @example
                   1737: \This gives an "Undefined word" error
                   1738: @end example
                   1739: 
                   1740: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1741: nest @code{(}-comments; and you cannot comment out text containing a
                   1742: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1743: avoid @code{)} in word names.}.
                   1744: 
                   1745: I use @code{\}-comments for descriptive text and for commenting out code
                   1746: of one or more line; I use @code{(}-comments for describing the stack
                   1747: effect, the stack contents, or for commenting out sub-line pieces of
                   1748: code.
                   1749: 
                   1750: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1751: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1752: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1753: with @kbd{M-q}.
                   1754: 
1.66      anton    1755: Reference: @ref{Comments}.
                   1756: 
1.48      anton    1757: 
                   1758: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1759: @section Colon Definitions
1.66      anton    1760: @cindex colon definitions, tutorial
                   1761: @cindex definitions, tutorial
                   1762: @cindex procedures, tutorial
                   1763: @cindex functions, tutorial
1.48      anton    1764: 
                   1765: are similar to procedures and functions in other programming languages.
                   1766: 
                   1767: @example
                   1768: : squared ( n -- n^2 )
                   1769:    dup * ;
                   1770: 5 squared .
                   1771: 7 squared .
                   1772: @end example
                   1773: 
                   1774: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1775: following comment describes its stack effect.  The words @code{dup *}
                   1776: are not executed, but compiled into the definition.  @code{;} ends the
                   1777: colon definition.
                   1778: 
                   1779: The newly-defined word can be used like any other word, including using
                   1780: it in other definitions:
                   1781: 
                   1782: @example
                   1783: : cubed ( n -- n^3 )
                   1784:    dup squared * ;
                   1785: -5 cubed .
                   1786: : fourth-power ( n -- n^4 )
                   1787:    squared squared ;
                   1788: 3 fourth-power .
                   1789: @end example
                   1790: 
                   1791: @assignment
                   1792: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1793: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1794: test your tests on the originals first).  Don't let the
                   1795: @samp{redefined}-Messages spook you, they are just warnings.
                   1796: @endassignment
                   1797: 
1.66      anton    1798: Reference: @ref{Colon Definitions}.
                   1799: 
1.48      anton    1800: 
                   1801: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1802: @section Decompilation
1.66      anton    1803: @cindex decompilation tutorial
                   1804: @cindex see tutorial
1.48      anton    1805: 
                   1806: You can decompile colon definitions with @code{see}:
                   1807: 
                   1808: @example
                   1809: see squared
                   1810: see cubed
                   1811: @end example
                   1812: 
                   1813: In Gforth @code{see} shows you a reconstruction of the source code from
                   1814: the executable code.  Informations that were present in the source, but
                   1815: not in the executable code, are lost (e.g., comments).
                   1816: 
1.65      anton    1817: You can also decompile the predefined words:
                   1818: 
                   1819: @example
                   1820: see .
                   1821: see +
                   1822: @end example
                   1823: 
                   1824: 
1.48      anton    1825: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1826: @section Stack-Effect Comments
1.66      anton    1827: @cindex stack-effect comments, tutorial
                   1828: @cindex --, tutorial
1.48      anton    1829: By convention the comment after the name of a definition describes the
                   1830: stack effect: The part in from of the @samp{--} describes the state of
                   1831: the stack before the execution of the definition, i.e., the parameters
                   1832: that are passed into the colon definition; the part behind the @samp{--}
                   1833: is the state of the stack after the execution of the definition, i.e.,
                   1834: the results of the definition.  The stack comment only shows the top
                   1835: stack items that the definition accesses and/or changes.
                   1836: 
                   1837: You should put a correct stack effect on every definition, even if it is
                   1838: just @code{( -- )}.  You should also add some descriptive comment to
                   1839: more complicated words (I usually do this in the lines following
                   1840: @code{:}).  If you don't do this, your code becomes unreadable (because
                   1841: you have to work through every definition before you can undertsand
                   1842: any).
                   1843: 
                   1844: @assignment
                   1845: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1846: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1847: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
1.65      anton    1848: are done, you can compare your stack effects to those in this manual
1.48      anton    1849: (@pxref{Word Index}).
                   1850: @endassignment
                   1851: 
                   1852: Sometimes programmers put comments at various places in colon
                   1853: definitions that describe the contents of the stack at that place (stack
                   1854: comments); i.e., they are like the first part of a stack-effect
                   1855: comment. E.g.,
                   1856: 
                   1857: @example
                   1858: : cubed ( n -- n^3 )
                   1859:    dup squared  ( n n^2 ) * ;
                   1860: @end example
                   1861: 
                   1862: In this case the stack comment is pretty superfluous, because the word
                   1863: is simple enough.  If you think it would be a good idea to add such a
                   1864: comment to increase readability, you should also consider factoring the
                   1865: word into several simpler words (@pxref{Factoring Tutorial,,
1.60      anton    1866: Factoring}), which typically eliminates the need for the stack comment;
1.48      anton    1867: however, if you decide not to refactor it, then having such a comment is
                   1868: better than not having it.
                   1869: 
                   1870: The names of the stack items in stack-effect and stack comments in the
                   1871: standard, in this manual, and in many programs specify the type through
                   1872: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1873: frequent prefixes are:
                   1874: 
                   1875: @table @code
                   1876: @item n
                   1877: signed integer
                   1878: @item u
                   1879: unsigned integer
                   1880: @item c
                   1881: character
                   1882: @item f
                   1883: Boolean flags, i.e. @code{false} or @code{true}.
                   1884: @item a-addr,a-
                   1885: Cell-aligned address
                   1886: @item c-addr,c-
                   1887: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1888: @item xt
                   1889: Execution token, same size as Cell
                   1890: @item w,x
                   1891: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1892: 16 bits (depending on your platform and Forth system). A cell is more
                   1893: commonly known as machine word, but the term @emph{word} already means
                   1894: something different in Forth.
                   1895: @item d
                   1896: signed double-cell integer
                   1897: @item ud
                   1898: unsigned double-cell integer
                   1899: @item r
                   1900: Float (on the FP stack)
                   1901: @end table
                   1902: 
                   1903: You can find a more complete list in @ref{Notation}.
                   1904: 
                   1905: @assignment
                   1906: Write stack-effect comments for all definitions you have written up to
                   1907: now.
                   1908: @endassignment
                   1909: 
                   1910: 
                   1911: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1912: @section Types
1.66      anton    1913: @cindex types tutorial
1.48      anton    1914: 
                   1915: In Forth the names of the operations are not overloaded; so similar
                   1916: operations on different types need different names; e.g., @code{+} adds
                   1917: integers, and you have to use @code{f+} to add floating-point numbers.
                   1918: The following prefixes are often used for related operations on
                   1919: different types:
                   1920: 
                   1921: @table @code
                   1922: @item (none)
                   1923: signed integer
                   1924: @item u
                   1925: unsigned integer
                   1926: @item c
                   1927: character
                   1928: @item d
                   1929: signed double-cell integer
                   1930: @item ud, du
                   1931: unsigned double-cell integer
                   1932: @item 2
                   1933: two cells (not-necessarily double-cell numbers)
                   1934: @item m, um
                   1935: mixed single-cell and double-cell operations
                   1936: @item f
                   1937: floating-point (note that in stack comments @samp{f} represents flags,
1.66      anton    1938: and @samp{r} represents FP numbers).
1.48      anton    1939: @end table
                   1940: 
                   1941: If there are no differences between the signed and the unsigned variant
                   1942: (e.g., for @code{+}), there is only the prefix-less variant.
                   1943: 
                   1944: Forth does not perform type checking, neither at compile time, nor at
                   1945: run time.  If you use the wrong oeration, the data are interpreted
                   1946: incorrectly:
                   1947: 
                   1948: @example
                   1949: -1 u.
                   1950: @end example
                   1951: 
                   1952: If you have only experience with type-checked languages until now, and
                   1953: have heard how important type-checking is, don't panic!  In my
                   1954: experience (and that of other Forthers), type errors in Forth code are
                   1955: usually easy to find (once you get used to it), the increased vigilance
                   1956: of the programmer tends to catch some harder errors in addition to most
                   1957: type errors, and you never have to work around the type system, so in
                   1958: most situations the lack of type-checking seems to be a win (projects to
                   1959: add type checking to Forth have not caught on).
                   1960: 
                   1961: 
                   1962: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   1963: @section Factoring
1.66      anton    1964: @cindex factoring tutorial
1.48      anton    1965: 
                   1966: If you try to write longer definitions, you will soon find it hard to
                   1967: keep track of the stack contents.  Therefore, good Forth programmers
                   1968: tend to write only short definitions (e.g., three lines).  The art of
                   1969: finding meaningful short definitions is known as factoring (as in
                   1970: factoring polynomials).
                   1971: 
                   1972: Well-factored programs offer additional advantages: smaller, more
                   1973: general words, are easier to test and debug and can be reused more and
                   1974: better than larger, specialized words.
                   1975: 
                   1976: So, if you run into difficulties with stack management, when writing
                   1977: code, try to define meaningful factors for the word, and define the word
                   1978: in terms of those.  Even if a factor contains only two words, it is
                   1979: often helpful.
                   1980: 
1.65      anton    1981: Good factoring is not easy, and it takes some practice to get the knack
                   1982: for it; but even experienced Forth programmers often don't find the
                   1983: right solution right away, but only when rewriting the program.  So, if
                   1984: you don't come up with a good solution immediately, keep trying, don't
                   1985: despair.
1.48      anton    1986: 
                   1987: @c example !!
                   1988: 
                   1989: 
                   1990: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   1991: @section Designing the stack effect
1.66      anton    1992: @cindex Stack effect design, tutorial
                   1993: @cindex design of stack effects, tutorial
1.48      anton    1994: 
                   1995: In other languages you can use an arbitrary order of parameters for a
1.65      anton    1996: function; and since there is only one result, you don't have to deal with
1.48      anton    1997: the order of results, either.
                   1998: 
                   1999: In Forth (and other stack-based languages, e.g., Postscript) the
                   2000: parameter and result order of a definition is important and should be
                   2001: designed well.  The general guideline is to design the stack effect such
                   2002: that the word is simple to use in most cases, even if that complicates
                   2003: the implementation of the word.  Some concrete rules are:
                   2004: 
                   2005: @itemize @bullet
                   2006: 
                   2007: @item
                   2008: Words consume all of their parameters (e.g., @code{.}).
                   2009: 
                   2010: @item
                   2011: If there is a convention on the order of parameters (e.g., from
                   2012: mathematics or another programming language), stick with it (e.g.,
                   2013: @code{-}).
                   2014: 
                   2015: @item
                   2016: If one parameter usually requires only a short computation (e.g., it is
                   2017: a constant), pass it on the top of the stack.  Conversely, parameters
                   2018: that usually require a long sequence of code to compute should be passed
                   2019: as the bottom (i.e., first) parameter.  This makes the code easier to
                   2020: read, because reader does not need to keep track of the bottom item
                   2021: through a long sequence of code (or, alternatively, through stack
1.49      anton    2022: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    2023: address on top of the stack because it is usually simpler to compute
                   2024: than the stored value (often the address is just a variable).
                   2025: 
                   2026: @item
                   2027: Similarly, results that are usually consumed quickly should be returned
                   2028: on the top of stack, whereas a result that is often used in long
                   2029: computations should be passed as bottom result.  E.g., the file words
                   2030: like @code{open-file} return the error code on the top of stack, because
                   2031: it is usually consumed quickly by @code{throw}; moreover, the error code
                   2032: has to be checked before doing anything with the other results.
                   2033: 
                   2034: @end itemize
                   2035: 
                   2036: These rules are just general guidelines, don't lose sight of the overall
                   2037: goal to make the words easy to use.  E.g., if the convention rule
                   2038: conflicts with the computation-length rule, you might decide in favour
                   2039: of the convention if the word will be used rarely, and in favour of the
                   2040: computation-length rule if the word will be used frequently (because
                   2041: with frequent use the cost of breaking the computation-length rule would
                   2042: be quite high, and frequent use makes it easier to remember an
                   2043: unconventional order).
                   2044: 
                   2045: @c example !! structure package
                   2046: 
1.65      anton    2047: 
1.48      anton    2048: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   2049: @section Local Variables
1.66      anton    2050: @cindex local variables, tutorial
1.48      anton    2051: 
                   2052: You can define local variables (@emph{locals}) in a colon definition:
                   2053: 
                   2054: @example
                   2055: : swap @{ a b -- b a @}
                   2056:   b a ;
                   2057: 1 2 swap .s 2drop
                   2058: @end example
                   2059: 
                   2060: (If your Forth system does not support this syntax, include
                   2061: @file{compat/anslocals.fs} first).
                   2062: 
                   2063: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   2064: takes two cells from the stack, puts the top of stack in @code{b} and
                   2065: the next stack element in @code{a}.  @code{--} starts a comment ending
                   2066: with @code{@}}.  After the locals definition, using the name of the
                   2067: local will push its value on the stack.  You can leave the comment
                   2068: part (@code{-- b a}) away:
                   2069: 
                   2070: @example
                   2071: : swap ( x1 x2 -- x2 x1 )
                   2072:   @{ a b @} b a ;
                   2073: @end example
                   2074: 
                   2075: In Gforth you can have several locals definitions, anywhere in a colon
                   2076: definition; in contrast, in a standard program you can have only one
                   2077: locals definition per colon definition, and that locals definition must
                   2078: be outside any controll structure.
                   2079: 
                   2080: With locals you can write slightly longer definitions without running
                   2081: into stack trouble.  However, I recommend trying to write colon
                   2082: definitions without locals for exercise purposes to help you gain the
                   2083: essential factoring skills.
                   2084: 
                   2085: @assignment
                   2086: Rewrite your definitions until now with locals
                   2087: @endassignment
                   2088: 
1.66      anton    2089: Reference: @ref{Locals}.
                   2090: 
1.48      anton    2091: 
                   2092: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   2093: @section Conditional execution
1.66      anton    2094: @cindex conditionals, tutorial
                   2095: @cindex if, tutorial
1.48      anton    2096: 
                   2097: In Forth you can use control structures only inside colon definitions.
                   2098: An @code{if}-structure looks like this:
                   2099: 
                   2100: @example
                   2101: : abs ( n1 -- +n2 )
                   2102:     dup 0 < if
                   2103:         negate
                   2104:     endif ;
                   2105: 5 abs .
                   2106: -5 abs .
                   2107: @end example
                   2108: 
                   2109: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   2110: the following code is performed, otherwise execution continues after the
1.51      pazsan   2111: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.48      anton    2112: elements and prioduces a flag:
                   2113: 
                   2114: @example
                   2115: 1 2 < .
                   2116: 2 1 < .
                   2117: 1 1 < .
                   2118: @end example
                   2119: 
                   2120: Actually the standard name for @code{endif} is @code{then}.  This
                   2121: tutorial presents the examples using @code{endif}, because this is often
                   2122: less confusing for people familiar with other programming languages
                   2123: where @code{then} has a different meaning.  If your system does not have
                   2124: @code{endif}, define it with
                   2125: 
                   2126: @example
                   2127: : endif postpone then ; immediate
                   2128: @end example
                   2129: 
                   2130: You can optionally use an @code{else}-part:
                   2131: 
                   2132: @example
                   2133: : min ( n1 n2 -- n )
                   2134:   2dup < if
                   2135:     drop
                   2136:   else
                   2137:     nip
                   2138:   endif ;
                   2139: 2 3 min .
                   2140: 3 2 min .
                   2141: @end example
                   2142: 
                   2143: @assignment
                   2144: Write @code{min} without @code{else}-part (hint: what's the definition
                   2145: of @code{nip}?).
                   2146: @endassignment
                   2147: 
1.66      anton    2148: Reference: @ref{Selection}.
                   2149: 
1.48      anton    2150: 
                   2151: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   2152: @section Flags and Comparisons
1.66      anton    2153: @cindex flags tutorial
                   2154: @cindex comparison tutorial
1.48      anton    2155: 
                   2156: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   2157: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   2158: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   2159: treated as true flag.
                   2160: 
                   2161: @example
                   2162: false .
                   2163: true .
                   2164: true hex u. decimal
                   2165: @end example
                   2166: 
                   2167: Comparison words produce canonical flags:
                   2168: 
                   2169: @example
                   2170: 1 1 = .
                   2171: 1 0= .
                   2172: 0 1 < .
                   2173: 0 0 < .
                   2174: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   2175: -1 1 < .
                   2176: @end example
                   2177: 
1.66      anton    2178: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
                   2179: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
                   2180: these combinations are standard (for details see the standard,
                   2181: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48      anton    2182: 
                   2183: You can use @code{and or xor invert} can be used as operations on
                   2184: canonical flags.  Actually they are bitwise operations:
                   2185: 
                   2186: @example
                   2187: 1 2 and .
                   2188: 1 2 or .
                   2189: 1 3 xor .
                   2190: 1 invert .
                   2191: @end example
                   2192: 
                   2193: You can convert a zero/non-zero flag into a canonical flag with
                   2194: @code{0<>} (and complement it on the way with @code{0=}).
                   2195: 
                   2196: @example
                   2197: 1 0= .
                   2198: 1 0<> .
                   2199: @end example
                   2200: 
1.65      anton    2201: You can use the all-bits-set feature of canonical flags and the bitwise
1.48      anton    2202: operation of the Boolean operations to avoid @code{if}s:
                   2203: 
                   2204: @example
                   2205: : foo ( n1 -- n2 )
                   2206:   0= if
                   2207:     14
                   2208:   else
                   2209:     0
                   2210:   endif ;
                   2211: 0 foo .
                   2212: 1 foo .
                   2213: 
                   2214: : foo ( n1 -- n2 )
                   2215:   0= 14 and ;
                   2216: 0 foo .
                   2217: 1 foo .
                   2218: @end example
                   2219: 
                   2220: @assignment
                   2221: Write @code{min} without @code{if}.
                   2222: @endassignment
                   2223: 
1.66      anton    2224: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
                   2225: @ref{Bitwise operations}.
                   2226: 
1.48      anton    2227: 
                   2228: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   2229: @section General Loops
1.66      anton    2230: @cindex loops, indefinite, tutorial
1.48      anton    2231: 
                   2232: The endless loop is the most simple one:
                   2233: 
                   2234: @example
                   2235: : endless ( -- )
                   2236:   0 begin
                   2237:     dup . 1+
                   2238:   again ;
                   2239: endless
                   2240: @end example
                   2241: 
                   2242: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   2243: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   2244: 
                   2245: A loop with one exit at any place looks like this:
                   2246: 
                   2247: @example
                   2248: : log2 ( +n1 -- n2 )
                   2249: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2250:   assert( dup 0> )
                   2251:   2/ 0 begin
                   2252:     over 0> while
                   2253:       1+ swap 2/ swap
                   2254:   repeat
                   2255:   nip ;
                   2256: 7 log2 .
                   2257: 8 log2 .
                   2258: @end example
                   2259: 
                   2260: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   2261: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    2262: continues behind the @code{while}.  @code{Repeat} jumps back to
                   2263: @code{begin}, just like @code{again}.
                   2264: 
                   2265: In Forth there are many combinations/abbreviations, like @code{1+}.
                   2266: However, @code{2/} is not one of them; it shifts it's argument right by
                   2267: one bit (arithmetic shift right):
                   2268: 
                   2269: @example
                   2270: -5 2 / .
                   2271: -5 2/ .
                   2272: @end example
                   2273: 
                   2274: @code{assert(} is no standard word, but you can get it on systems other
                   2275: then Gforth by including @file{compat/assert.fs}.  You can see what it
                   2276: does by trying
                   2277: 
                   2278: @example
                   2279: 0 log2 .
                   2280: @end example
                   2281: 
                   2282: Here's a loop with an exit at the end:
                   2283: 
                   2284: @example
                   2285: : log2 ( +n1 -- n2 )
                   2286: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2287:   assert( dup 0 > )
                   2288:   -1 begin
                   2289:     1+ swap 2/ swap
                   2290:     over 0 <=
                   2291:   until
                   2292:   nip ;
                   2293: @end example
                   2294: 
                   2295: @code{Until} consumes a flag; if it is non-zero, execution continues at
                   2296: the @code{begin}, otherwise after the @code{until}.
                   2297: 
                   2298: @assignment
                   2299: Write a definition for computing the greatest common divisor.
                   2300: @endassignment
                   2301: 
1.66      anton    2302: Reference: @ref{Simple Loops}.
                   2303: 
1.48      anton    2304: 
                   2305: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   2306: @section Counted loops
1.66      anton    2307: @cindex loops, counted, tutorial
1.48      anton    2308: 
                   2309: @example
                   2310: : ^ ( n1 u -- n )
                   2311: \ n = the uth power of u1
                   2312:   1 swap 0 u+do
                   2313:     over *
                   2314:   loop
                   2315:   nip ;
                   2316: 3 2 ^ .
                   2317: 4 3 ^ .
                   2318: @end example
                   2319: 
                   2320: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   2321: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   2322: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2323: times (or not at all, if @code{u3-u4<0}).
                   2324: 
                   2325: You can see the stack effect design rules at work in the stack effect of
                   2326: the loop start words: Since the start value of the loop is more
                   2327: frequently constant than the end value, the start value is passed on
                   2328: the top-of-stack.
                   2329: 
                   2330: You can access the counter of a counted loop with @code{i}:
                   2331: 
                   2332: @example
                   2333: : fac ( u -- u! )
                   2334:   1 swap 1+ 1 u+do
                   2335:     i *
                   2336:   loop ;
                   2337: 5 fac .
                   2338: 7 fac .
                   2339: @end example
                   2340: 
                   2341: There is also @code{+do}, which expects signed numbers (important for
                   2342: deciding whether to enter the loop).
                   2343: 
                   2344: @assignment
                   2345: Write a definition for computing the nth Fibonacci number.
                   2346: @endassignment
                   2347: 
1.65      anton    2348: You can also use increments other than 1:
                   2349: 
                   2350: @example
                   2351: : up2 ( n1 n2 -- )
                   2352:   +do
                   2353:     i .
                   2354:   2 +loop ;
                   2355: 10 0 up2
                   2356: 
                   2357: : down2 ( n1 n2 -- )
                   2358:   -do
                   2359:     i .
                   2360:   2 -loop ;
                   2361: 0 10 down2
                   2362: @end example
1.48      anton    2363: 
1.66      anton    2364: Reference: @ref{Counted Loops}.
                   2365: 
1.48      anton    2366: 
                   2367: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2368: @section Recursion
1.66      anton    2369: @cindex recursion tutorial
1.48      anton    2370: 
                   2371: Usually the name of a definition is not visible in the definition; but
                   2372: earlier definitions are usually visible:
                   2373: 
                   2374: @example
                   2375: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
                   2376: : / ( n1 n2 -- n )
                   2377:   dup 0= if
                   2378:     -10 throw \ report division by zero
                   2379:   endif
                   2380:   /           \ old version
                   2381: ;
                   2382: 1 0 /
                   2383: @end example
                   2384: 
                   2385: For recursive definitions you can use @code{recursive} (non-standard) or
                   2386: @code{recurse}:
                   2387: 
                   2388: @example
                   2389: : fac1 ( n -- n! ) recursive
                   2390:  dup 0> if
                   2391:    dup 1- fac1 *
                   2392:  else
                   2393:    drop 1
                   2394:  endif ;
                   2395: 7 fac1 .
                   2396: 
                   2397: : fac2 ( n -- n! )
                   2398:  dup 0> if
                   2399:    dup 1- recurse *
                   2400:  else
                   2401:    drop 1
                   2402:  endif ;
                   2403: 8 fac2 .
                   2404: @end example
                   2405: 
                   2406: @assignment
                   2407: Write a recursive definition for computing the nth Fibonacci number.
                   2408: @endassignment
                   2409: 
1.66      anton    2410: Reference (including indirect recursion): @xref{Calls and returns}.
                   2411: 
1.48      anton    2412: 
                   2413: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2414: @section Leaving definitions or loops
1.66      anton    2415: @cindex leaving definitions, tutorial
                   2416: @cindex leaving loops, tutorial
1.48      anton    2417: 
                   2418: @code{EXIT} exits the current definition right away.  For every counted
                   2419: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2420: before the @code{EXIT}:
                   2421: 
                   2422: @c !! real examples
                   2423: @example
                   2424: : ...
                   2425:  ... u+do
                   2426:    ... if
                   2427:      ... unloop exit
                   2428:    endif
                   2429:    ...
                   2430:  loop
                   2431:  ... ;
                   2432: @end example
                   2433: 
                   2434: @code{LEAVE} leaves the innermost counted loop right away:
                   2435: 
                   2436: @example
                   2437: : ...
                   2438:  ... u+do
                   2439:    ... if
                   2440:      ... leave
                   2441:    endif
                   2442:    ...
                   2443:  loop
                   2444:  ... ;
                   2445: @end example
                   2446: 
1.65      anton    2447: @c !! example
1.48      anton    2448: 
1.66      anton    2449: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
                   2450: 
                   2451: 
1.48      anton    2452: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2453: @section Return Stack
1.66      anton    2454: @cindex return stack tutorial
1.48      anton    2455: 
                   2456: In addition to the data stack Forth also has a second stack, the return
                   2457: stack; most Forth systems store the return addresses of procedure calls
                   2458: there (thus its name).  Programmers can also use this stack:
                   2459: 
                   2460: @example
                   2461: : foo ( n1 n2 -- )
                   2462:  .s
                   2463:  >r .s
1.50      anton    2464:  r@@ .
1.48      anton    2465:  >r .s
1.50      anton    2466:  r@@ .
1.48      anton    2467:  r> .
1.50      anton    2468:  r@@ .
1.48      anton    2469:  r> . ;
                   2470: 1 2 foo
                   2471: @end example
                   2472: 
                   2473: @code{>r} takes an element from the data stack and pushes it onto the
                   2474: return stack; conversely, @code{r>} moves an elementm from the return to
                   2475: the data stack; @code{r@@} pushes a copy of the top of the return stack
                   2476: on the return stack.
                   2477: 
                   2478: Forth programmers usually use the return stack for storing data
                   2479: temporarily, if using the data stack alone would be too complex, and
                   2480: factoring and locals are not an option:
                   2481: 
                   2482: @example
                   2483: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2484:  rot >r rot r> ;
                   2485: @end example
                   2486: 
                   2487: The return address of the definition and the loop control parameters of
                   2488: counted loops usually reside on the return stack, so you have to take
                   2489: all items, that you have pushed on the return stack in a colon
                   2490: definition or counted loop, from the return stack before the definition
                   2491: or loop ends.  You cannot access items that you pushed on the return
                   2492: stack outside some definition or loop within the definition of loop.
                   2493: 
                   2494: If you miscount the return stack items, this usually ends in a crash:
                   2495: 
                   2496: @example
                   2497: : crash ( n -- )
                   2498:   >r ;
                   2499: 5 crash
                   2500: @end example
                   2501: 
                   2502: You cannot mix using locals and using the return stack (according to the
                   2503: standard; Gforth has no problem).  However, they solve the same
                   2504: problems, so this shouldn't be an issue.
                   2505: 
                   2506: @assignment
                   2507: Can you rewrite any of the definitions you wrote until now in a better
                   2508: way using the return stack?
                   2509: @endassignment
                   2510: 
1.66      anton    2511: Reference: @ref{Return stack}.
                   2512: 
1.48      anton    2513: 
                   2514: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2515: @section Memory
1.66      anton    2516: @cindex memory access/allocation tutorial
1.48      anton    2517: 
                   2518: You can create a global variable @code{v} with
                   2519: 
                   2520: @example
                   2521: variable v ( -- addr )
                   2522: @end example
                   2523: 
                   2524: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2525: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2526: values into this cell and @code{@@} (fetch) to load the value from the
                   2527: stack into memory:
                   2528: 
                   2529: @example
                   2530: v .
                   2531: 5 v ! .s
1.50      anton    2532: v @@ .
1.48      anton    2533: @end example
                   2534: 
1.65      anton    2535: You can see a raw dump of memory with @code{dump}:
                   2536: 
                   2537: @example
                   2538: v 1 cells .s dump
                   2539: @end example
                   2540: 
                   2541: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
                   2542: generally, address units (aus)) that @code{n1 cells} occupy.  You can
                   2543: also reserve more memory:
1.48      anton    2544: 
                   2545: @example
                   2546: create v2 20 cells allot
1.65      anton    2547: v2 20 cells dump
1.48      anton    2548: @end example
                   2549: 
1.65      anton    2550: creates a word @code{v2} and reserves 20 uninitialized cells; the
                   2551: address pushed by @code{v2} points to the start of these 20 cells.  You
                   2552: can use address arithmetic to access these cells:
1.48      anton    2553: 
                   2554: @example
                   2555: 3 v2 5 cells + !
1.65      anton    2556: v2 20 cells dump
1.48      anton    2557: @end example
                   2558: 
                   2559: You can reserve and initialize memory with @code{,}:
                   2560: 
                   2561: @example
                   2562: create v3
                   2563:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2564: v3 @@ .
                   2565: v3 cell+ @@ .
                   2566: v3 2 cells + @@ .
1.65      anton    2567: v3 5 cells dump
1.48      anton    2568: @end example
                   2569: 
                   2570: @assignment
                   2571: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2572: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2573: one at @code{addr cell+} etc.
                   2574: @endassignment
                   2575: 
                   2576: You can also reserve memory without creating a new word:
                   2577: 
                   2578: @example
1.60      anton    2579: here 10 cells allot .
                   2580: here .
1.48      anton    2581: @end example
                   2582: 
                   2583: @code{Here} pushes the start address of the memory area.  You should
                   2584: store it somewhere, or you will have a hard time finding the memory area
                   2585: again.
                   2586: 
                   2587: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2588: the system's data structures for words etc. on Gforth and most other
                   2589: Forth systems.  It is managed like a stack: You can free the memory that
                   2590: you have just @code{allot}ed with
                   2591: 
                   2592: @example
                   2593: -10 cells allot
1.60      anton    2594: here .
1.48      anton    2595: @end example
                   2596: 
                   2597: Note that you cannot do this if you have created a new word in the
                   2598: meantime (because then your @code{allot}ed memory is no longer on the
                   2599: top of the dictionary ``stack'').
                   2600: 
                   2601: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2602: freeing memory in any order:
                   2603: 
                   2604: @example
                   2605: 10 cells allocate throw .s
                   2606: 20 cells allocate throw .s
                   2607: swap
                   2608: free throw
                   2609: free throw
                   2610: @end example
                   2611: 
                   2612: The @code{throw}s deal with errors (e.g., out of memory).
                   2613: 
1.65      anton    2614: And there is also a
                   2615: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   2616: garbage collector}, which eliminates the need to @code{free} memory
                   2617: explicitly.
1.48      anton    2618: 
1.66      anton    2619: Reference: @ref{Memory}.
                   2620: 
1.48      anton    2621: 
                   2622: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2623: @section Characters and Strings
1.66      anton    2624: @cindex strings tutorial
                   2625: @cindex characters tutorial
1.48      anton    2626: 
                   2627: On the stack characters take up a cell, like numbers.  In memory they
                   2628: have their own size (one 8-bit byte on most systems), and therefore
                   2629: require their own words for memory access:
                   2630: 
                   2631: @example
                   2632: create v4 
                   2633:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2634: v4 4 chars + c@@ .
1.65      anton    2635: v4 5 chars dump
1.48      anton    2636: @end example
                   2637: 
                   2638: The preferred representation of strings on the stack is @code{addr
                   2639: u-count}, where @code{addr} is the address of the first character and
                   2640: @code{u-count} is the number of characters in the string.
                   2641: 
                   2642: @example
                   2643: v4 5 type
                   2644: @end example
                   2645: 
                   2646: You get a string constant with
                   2647: 
                   2648: @example
                   2649: s" hello, world" .s
                   2650: type
                   2651: @end example
                   2652: 
                   2653: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2654: is a normal Forth word and must be delimited with white space (try what
                   2655: happens when you remove the space).
                   2656: 
                   2657: However, this interpretive use of @code{s"} is quite restricted: the
                   2658: string exists only until the next call of @code{s"} (some Forth systems
                   2659: keep more than one of these strings, but usually they still have a
1.62      crook    2660: limited lifetime).
1.48      anton    2661: 
                   2662: @example
                   2663: s" hello," s" world" .s
                   2664: type
                   2665: type
                   2666: @end example
                   2667: 
1.62      crook    2668: You can also use @code{s"} in a definition, and the resulting
                   2669: strings then live forever (well, for as long as the definition):
1.48      anton    2670: 
                   2671: @example
                   2672: : foo s" hello," s" world" ;
                   2673: foo .s
                   2674: type
                   2675: type
                   2676: @end example
                   2677: 
                   2678: @assignment
                   2679: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2680: Implement @code{type ( addr u -- )}.
                   2681: @endassignment
                   2682: 
1.66      anton    2683: Reference: @ref{Memory Blocks}.
                   2684: 
                   2685: 
1.48      anton    2686: @node Alignment Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Characters and Strings Tutorial, Tutorial
                   2687: @section Alignment
1.66      anton    2688: @cindex alignment tutorial
                   2689: @cindex memory alignment tutorial
1.48      anton    2690: 
                   2691: On many processors cells have to be aligned in memory, if you want to
                   2692: access them with @code{@@} and @code{!} (and even if the processor does
1.62      crook    2693: not require alignment, access to aligned cells is faster).
1.48      anton    2694: 
                   2695: @code{Create} aligns @code{here} (i.e., the place where the next
                   2696: allocation will occur, and that the @code{create}d word points to).
                   2697: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2698: address.  Adding a number of @code{cells} to an aligned address produces
                   2699: another aligned address.
                   2700: 
                   2701: However, address arithmetic involving @code{char+} and @code{chars} can
                   2702: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2703: a-addr )} produces the next aligned address:
                   2704: 
                   2705: @example
1.50      anton    2706: v3 char+ aligned .s @@ .
                   2707: v3 char+ .s @@ .
1.48      anton    2708: @end example
                   2709: 
                   2710: Similarly, @code{align} advances @code{here} to the next aligned
                   2711: address:
                   2712: 
                   2713: @example
                   2714: create v5 97 c,
                   2715: here .
                   2716: align here .
                   2717: 1000 ,
                   2718: @end example
                   2719: 
                   2720: Note that you should use aligned addresses even if your processor does
                   2721: not require them, if you want your program to be portable.
                   2722: 
1.66      anton    2723: Reference: @ref{Address arithmetic}.
                   2724: 
1.48      anton    2725: 
                   2726: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Alignment Tutorial, Tutorial
                   2727: @section Interpretation and Compilation Semantics and Immediacy
1.66      anton    2728: @cindex semantics tutorial
                   2729: @cindex interpretation semantics tutorial
                   2730: @cindex compilation semantics tutorial
                   2731: @cindex immediate, tutorial
1.48      anton    2732: 
                   2733: When a word is compiled, it behaves differently from being interpreted.
                   2734: E.g., consider @code{+}:
                   2735: 
                   2736: @example
                   2737: 1 2 + .
                   2738: : foo + ;
                   2739: @end example
                   2740: 
                   2741: These two behaviours are known as compilation and interpretation
                   2742: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2743: is to append the interpretation semantics to the currently defined word
                   2744: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2745: later, the interpretation semantics of @code{+} (i.e., adding two
                   2746: numbers) will be performed.
                   2747: 
                   2748: However, there are words with non-default compilation semantics, e.g.,
                   2749: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2750: change the compilation semantics of the last defined word to be equal to
                   2751: the interpretation semantics:
                   2752: 
                   2753: @example
                   2754: : [FOO] ( -- )
                   2755:  5 . ; immediate
                   2756: 
                   2757: [FOO]
                   2758: : bar ( -- )
                   2759:   [FOO] ;
                   2760: bar
                   2761: see bar
                   2762: @end example
                   2763: 
                   2764: Two conventions to mark words with non-default compilation semnatics are
                   2765: names with brackets (more frequently used) and to write them all in
                   2766: upper case (less frequently used).
                   2767: 
                   2768: In Gforth (and many other systems) you can also remove the
                   2769: interpretation semantics with @code{compile-only} (the compilation
                   2770: semantics is derived from the original interpretation semantics):
                   2771: 
                   2772: @example
                   2773: : flip ( -- )
                   2774:  6 . ; compile-only \ but not immediate
                   2775: flip
                   2776: 
                   2777: : flop ( -- )
                   2778:  flip ;
                   2779: flop
                   2780: @end example
                   2781: 
                   2782: In this example the interpretation semantics of @code{flop} is equal to
                   2783: the original interpretation semantics of @code{flip}.
                   2784: 
                   2785: The text interpreter has two states: in interpret state, it performs the
                   2786: interpretation semantics of words it encounters; in compile state, it
                   2787: performs the compilation semantics of these words.
                   2788: 
                   2789: Among other things, @code{:} switches into compile state, and @code{;}
                   2790: switches back to interpret state.  They contain the factors @code{]}
                   2791: (switch to compile state) and @code{[} (switch to interpret state), that
                   2792: do nothing but switch the state.
                   2793: 
                   2794: @example
                   2795: : xxx ( -- )
                   2796:   [ 5 . ]
                   2797: ;
                   2798: 
                   2799: xxx
                   2800: see xxx
                   2801: @end example
                   2802: 
                   2803: These brackets are also the source of the naming convention mentioned
                   2804: above.
                   2805: 
1.66      anton    2806: Reference: @ref{Interpretation and Compilation Semantics}.
                   2807: 
1.48      anton    2808: 
                   2809: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2810: @section Execution Tokens
1.66      anton    2811: @cindex execution tokens tutorial
                   2812: @cindex XT tutorial
1.48      anton    2813: 
                   2814: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2815: cell representing the interpretation semantics of a word.  You can
                   2816: execute this semantics with @code{execute}:
                   2817: 
                   2818: @example
                   2819: ' + .s
                   2820: 1 2 rot execute .
                   2821: @end example
                   2822: 
                   2823: The XT is similar to a function pointer in C.  However, parameter
                   2824: passing through the stack makes it a little more flexible:
                   2825: 
                   2826: @example
                   2827: : map-array ( ... addr u xt -- ... )
1.50      anton    2828: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2829: \ at addr and containing u elements
1.48      anton    2830:   @{ xt @}
                   2831:   cells over + swap ?do
1.50      anton    2832:     i @@ xt execute
1.48      anton    2833:   1 cells +loop ;
                   2834: 
                   2835: create a 3 , 4 , 2 , -1 , 4 ,
                   2836: a 5 ' . map-array .s
                   2837: 0 a 5 ' + map-array .
                   2838: s" max-n" environment? drop .s
                   2839: a 5 ' min map-array .
                   2840: @end example
                   2841: 
                   2842: You can use map-array with the XTs of words that consume one element
                   2843: more than they produce.  In theory you can also use it with other XTs,
                   2844: but the stack effect then depends on the size of the array, which is
                   2845: hard to understand.
                   2846: 
1.51      pazsan   2847: Since XTs are cell-sized, you can store them in memory and manipulate
                   2848: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2849: word with @code{compile,}:
                   2850: 
                   2851: @example
                   2852: : foo1 ( n1 n2 -- n )
                   2853:    [ ' + compile, ] ;
                   2854: see foo
                   2855: @end example
                   2856: 
                   2857: This is non-standard, because @code{compile,} has no compilation
                   2858: semantics in the standard, but it works in good Forth systems.  For the
                   2859: broken ones, use
                   2860: 
                   2861: @example
                   2862: : [compile,] compile, ; immediate
                   2863: 
                   2864: : foo1 ( n1 n2 -- n )
                   2865:    [ ' + ] [compile,] ;
                   2866: see foo
                   2867: @end example
                   2868: 
                   2869: @code{'} is a word with default compilation semantics; it parses the
                   2870: next word when its interpretation semantics are executed, not during
                   2871: compilation:
                   2872: 
                   2873: @example
                   2874: : foo ( -- xt )
                   2875:   ' ;
                   2876: see foo
                   2877: : bar ( ... "word" -- ... )
                   2878:   ' execute ;
                   2879: see bar
1.60      anton    2880: 1 2 bar + .
1.48      anton    2881: @end example
                   2882: 
                   2883: You often want to parse a word during compilation and compile its XT so
                   2884: it will be pushed on the stack at run-time.  @code{[']} does this:
                   2885: 
                   2886: @example
                   2887: : xt-+ ( -- xt )
                   2888:   ['] + ;
                   2889: see xt-+
                   2890: 1 2 xt-+ execute .
                   2891: @end example
                   2892: 
                   2893: Many programmers tend to see @code{'} and the word it parses as one
                   2894: unit, and expect it to behave like @code{[']} when compiled, and are
                   2895: confused by the actual behaviour.  If you are, just remember that the
                   2896: Forth system just takes @code{'} as one unit and has no idea that it is
                   2897: a parsing word (attempts to convenience programmers in this issue have
                   2898: usually resulted in even worse pitfalls, see
1.66      anton    2899: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
                   2900: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48      anton    2901: 
                   2902: Note that the state of the interpreter does not come into play when
1.51      pazsan   2903: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    2904: compile state, it still gives you the interpretation semantics.  And
                   2905: whatever that state is, @code{execute} performs the semantics
1.66      anton    2906: represented by the XT (i.e., for XTs produced with @code{'} the
                   2907: interpretation semantics).
                   2908: 
                   2909: Reference: @ref{Tokens for Words}.
1.48      anton    2910: 
                   2911: 
                   2912: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   2913: @section Exceptions
1.66      anton    2914: @cindex exceptions tutorial
1.48      anton    2915: 
                   2916: @code{throw ( n -- )} causes an exception unless n is zero.
                   2917: 
                   2918: @example
                   2919: 100 throw .s
                   2920: 0 throw .s
                   2921: @end example
                   2922: 
                   2923: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   2924: it catches exceptions and pushes the number of the exception on the
                   2925: stack (or 0, if the xt executed without exception).  If there was an
                   2926: exception, the stacks have the same depth as when entering @code{catch}:
                   2927: 
                   2928: @example
                   2929: .s
                   2930: 3 0 ' / catch .s
                   2931: 3 2 ' / catch .s
                   2932: @end example
                   2933: 
                   2934: @assignment
                   2935: Try the same with @code{execute} instead of @code{catch}.
                   2936: @endassignment
                   2937: 
                   2938: @code{Throw} always jumps to the dynamically next enclosing
                   2939: @code{catch}, even if it has to leave several call levels to achieve
                   2940: this:
                   2941: 
                   2942: @example
                   2943: : foo 100 throw ;
                   2944: : foo1 foo ." after foo" ;
1.51      pazsan   2945: : bar ['] foo1 catch ;
1.60      anton    2946: bar .
1.48      anton    2947: @end example
                   2948: 
                   2949: It is often important to restore a value upon leaving a definition, even
                   2950: if the definition is left through an exception.  You can ensure this
                   2951: like this:
                   2952: 
                   2953: @example
                   2954: : ...
                   2955:    save-x
1.51      pazsan   2956:    ['] word-changing-x catch ( ... n )
1.48      anton    2957:    restore-x
                   2958:    ( ... n ) throw ;
                   2959: @end example
                   2960: 
1.55      anton    2961: Gforth provides an alternative syntax in addition to @code{catch}:
1.48      anton    2962: @code{try ... recover ... endtry}.  If the code between @code{try} and
                   2963: @code{recover} has an exception, the stack depths are restored, the
                   2964: exception number is pushed on the stack, and the code between
                   2965: @code{recover} and @code{endtry} is performed.  E.g., the definition for
                   2966: @code{catch} is
                   2967: 
                   2968: @example
                   2969: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
                   2970:   try
                   2971:     execute 0
                   2972:   recover
                   2973:     nip
                   2974:   endtry ;
                   2975: @end example
                   2976: 
                   2977: The equivalent to the restoration code above is
                   2978: 
                   2979: @example
                   2980: : ...
                   2981:   save-x
                   2982:   try
                   2983:     word-changing-x
                   2984:   end-try
                   2985:   restore-x
                   2986:   throw ;
                   2987: @end example
                   2988: 
                   2989: As you can see, the @code{recover} part is optional.
                   2990: 
1.66      anton    2991: Reference: @ref{Exception Handling}.
                   2992: 
1.48      anton    2993: 
                   2994: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   2995: @section Defining Words
1.66      anton    2996: @cindex defining words tutorial
                   2997: @cindex does> tutorial
                   2998: @cindex create...does> tutorial
                   2999: 
                   3000: @c before semantics?
1.48      anton    3001: 
                   3002: @code{:}, @code{create}, and @code{variable} are definition words: They
                   3003: define other words.  @code{Constant} is another definition word:
                   3004: 
                   3005: @example
                   3006: 5 constant foo
                   3007: foo .
                   3008: @end example
                   3009: 
                   3010: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   3011: (floating point) with @code{variable} and @code{constant}.
                   3012: 
                   3013: You can also define your own defining words.  E.g.:
                   3014: 
                   3015: @example
                   3016: : variable ( "name" -- )
                   3017:   create 0 , ;
                   3018: @end example
                   3019: 
                   3020: You can also define defining words that create words that do something
                   3021: other than just producing their address:
                   3022: 
                   3023: @example
                   3024: : constant ( n "name" -- )
                   3025:   create ,
                   3026: does> ( -- n )
1.50      anton    3027:   ( addr ) @@ ;
1.48      anton    3028: 
                   3029: 5 constant foo
                   3030: foo .
                   3031: @end example
                   3032: 
                   3033: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   3034: @code{does>} replaces @code{;}, but it also does something else: It
                   3035: changes the last defined word such that it pushes the address of the
                   3036: body of the word and then performs the code after the @code{does>}
                   3037: whenever it is called.
                   3038: 
                   3039: In the example above, @code{constant} uses @code{,} to store 5 into the
                   3040: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   3041: the body onto the stack, then (in the code after the @code{does>})
                   3042: fetches the 5 from there.
                   3043: 
                   3044: The stack comment near the @code{does>} reflects the stack effect of the
                   3045: defined word, not the stack effect of the code after the @code{does>}
                   3046: (the difference is that the code expects the address of the body that
                   3047: the stack comment does not show).
                   3048: 
                   3049: You can use these definition words to do factoring in cases that involve
                   3050: (other) definition words.  E.g., a field offset is always added to an
                   3051: address.  Instead of defining
                   3052: 
                   3053: @example
                   3054: 2 cells constant offset-field1
                   3055: @end example
                   3056: 
                   3057: and using this like
                   3058: 
                   3059: @example
                   3060: ( addr ) offset-field1 +
                   3061: @end example
                   3062: 
                   3063: you can define a definition word
                   3064: 
                   3065: @example
                   3066: : simple-field ( n "name" -- )
                   3067:   create ,
                   3068: does> ( n1 -- n1+n )
1.50      anton    3069:   ( addr ) @@ + ;
1.48      anton    3070: @end example
1.21      crook    3071: 
1.48      anton    3072: Definition and use of field offsets now look like this:
1.21      crook    3073: 
1.48      anton    3074: @example
                   3075: 2 cells simple-field field1
1.60      anton    3076: create mystruct 4 cells allot
                   3077: mystruct .s field1 .s drop
1.48      anton    3078: @end example
1.21      crook    3079: 
1.48      anton    3080: If you want to do something with the word without performing the code
                   3081: after the @code{does>}, you can access the body of a @code{create}d word
                   3082: with @code{>body ( xt -- addr )}:
1.21      crook    3083: 
1.48      anton    3084: @example
                   3085: : value ( n "name" -- )
                   3086:   create ,
                   3087: does> ( -- n1 )
1.50      anton    3088:   @@ ;
1.48      anton    3089: : to ( n "name" -- )
                   3090:   ' >body ! ;
1.21      crook    3091: 
1.48      anton    3092: 5 value foo
                   3093: foo .
                   3094: 7 to foo
                   3095: foo .
                   3096: @end example
1.21      crook    3097: 
1.48      anton    3098: @assignment
                   3099: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   3100: XT (at the start the XT of @code{abort}), and upon execution
                   3101: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   3102: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   3103: recursion is one application of @code{defer}.
                   3104: @endassignment
1.29      crook    3105: 
1.66      anton    3106: Reference: @ref{User-defined Defining Words}.
                   3107: 
                   3108: 
1.48      anton    3109: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   3110: @section Arrays and Records
1.66      anton    3111: @cindex arrays tutorial
                   3112: @cindex records tutorial
                   3113: @cindex structs tutorial
1.29      crook    3114: 
1.48      anton    3115: Forth has no standard words for defining data structures such as arrays
                   3116: and records (structs in C terminology), but you can build them yourself
                   3117: based on address arithmetic.  You can also define words for defining
                   3118: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    3119: 
1.48      anton    3120: One of the first projects a Forth newcomer sets out upon when learning
                   3121: about defining words is an array defining word (possibly for
                   3122: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   3123: learn something from it.  However, don't be disappointed when you later
                   3124: learn that you have little use for these words (inappropriate use would
                   3125: be even worse).  I have not yet found a set of useful array words yet;
                   3126: the needs are just too diverse, and named, global arrays (the result of
                   3127: naive use of defining words) are often not flexible enough (e.g.,
1.66      anton    3128: consider how to pass them as parameters).  Another such project is a set
                   3129: of words to help dealing with strings.
1.29      crook    3130: 
1.48      anton    3131: On the other hand, there is a useful set of record words, and it has
                   3132: been defined in @file{compat/struct.fs}; these words are predefined in
                   3133: Gforth.  They are explained in depth elsewhere in this manual (see
                   3134: @pxref{Structures}).  The @code{simple-field} example above is
                   3135: simplified variant of fields in this package.
1.21      crook    3136: 
                   3137: 
1.48      anton    3138: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   3139: @section @code{POSTPONE}
1.66      anton    3140: @cindex postpone tutorial
1.21      crook    3141: 
1.48      anton    3142: You can compile the compilation semantics (instead of compiling the
                   3143: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    3144: 
1.48      anton    3145: @example
                   3146: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   3147:  POSTPONE + ; immediate
1.48      anton    3148: : foo ( n1 n2 -- n )
                   3149:  MY-+ ;
                   3150: 1 2 foo .
                   3151: see foo
                   3152: @end example
1.21      crook    3153: 
1.48      anton    3154: During the definition of @code{foo} the text interpreter performs the
                   3155: compilation semantics of @code{MY-+}, which performs the compilation
                   3156: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   3157: 
                   3158: This example also displays separate stack comments for the compilation
                   3159: semantics and for the stack effect of the compiled code.  For words with
                   3160: default compilation semantics these stack effects are usually not
                   3161: displayed; the stack effect of the compilation semantics is always
                   3162: @code{( -- )} for these words, the stack effect for the compiled code is
                   3163: the stack effect of the interpretation semantics.
                   3164: 
                   3165: Note that the state of the interpreter does not come into play when
                   3166: performing the compilation semantics in this way.  You can also perform
                   3167: it interpretively, e.g.:
                   3168: 
                   3169: @example
                   3170: : foo2 ( n1 n2 -- n )
                   3171:  [ MY-+ ] ;
                   3172: 1 2 foo .
                   3173: see foo
                   3174: @end example
1.21      crook    3175: 
1.48      anton    3176: However, there are some broken Forth systems where this does not always
1.62      crook    3177: work, and therefore this practice was been declared non-standard in
1.48      anton    3178: 1999.
                   3179: @c !! repair.fs
                   3180: 
                   3181: Here is another example for using @code{POSTPONE}:
1.44      crook    3182: 
1.48      anton    3183: @example
                   3184: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   3185:  POSTPONE negate POSTPONE + ; immediate compile-only
                   3186: : bar ( n1 n2 -- n )
                   3187:   MY-- ;
                   3188: 2 1 bar .
                   3189: see bar
                   3190: @end example
1.21      crook    3191: 
1.48      anton    3192: You can define @code{ENDIF} in this way:
1.21      crook    3193: 
1.48      anton    3194: @example
                   3195: : ENDIF ( Compilation: orig -- )
                   3196:   POSTPONE then ; immediate
                   3197: @end example
1.21      crook    3198: 
1.48      anton    3199: @assignment
                   3200: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   3201: @code{2dup}, but compiles @code{over over}.
                   3202: @endassignment
1.29      crook    3203: 
1.66      anton    3204: @c !! @xref{Macros} for reference
                   3205: 
                   3206: 
1.48      anton    3207: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3208: @section @code{Literal}
1.66      anton    3209: @cindex literal tutorial
1.29      crook    3210: 
1.48      anton    3211: You cannot @code{POSTPONE} numbers:
1.21      crook    3212: 
1.48      anton    3213: @example
                   3214: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3215: @end example
                   3216: 
1.48      anton    3217: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3218: 
1.48      anton    3219: @example
                   3220: : [FOO] ( compilation: --; run-time: -- n )
                   3221:   500 POSTPONE literal ; immediate
1.29      crook    3222: 
1.60      anton    3223: : flip [FOO] ;
1.48      anton    3224: flip .
                   3225: see flip
                   3226: @end example
1.29      crook    3227: 
1.48      anton    3228: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3229: semantics are executed) and pushes it at run-time (when the code it
                   3230: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3231: number computed at compile time into the current word:
1.29      crook    3232: 
1.48      anton    3233: @example
                   3234: : bar ( -- n )
                   3235:   [ 2 2 + ] literal ;
                   3236: see bar
                   3237: @end example
1.29      crook    3238: 
1.48      anton    3239: @assignment
                   3240: Write @code{]L} which allows writing the example above as @code{: bar (
                   3241: -- n ) [ 2 2 + ]L ;}
                   3242: @endassignment
                   3243: 
1.66      anton    3244: @c !! @xref{Macros} for reference
                   3245: 
1.48      anton    3246: 
                   3247: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3248: @section Advanced macros
1.66      anton    3249: @cindex macros, advanced tutorial
                   3250: @cindex run-time code generation, tutorial
1.48      anton    3251: 
1.66      anton    3252: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
                   3253: Execution Tokens}.  It frequently performs @code{execute}, a relatively
                   3254: expensive operation in some Forth implementations.  You can use
1.48      anton    3255: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3256: and produce a word that contains the word to be performed directly:
                   3257: 
                   3258: @c use ]] ... [[
                   3259: @example
                   3260: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3261: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3262: \ array beginning at addr and containing u elements
                   3263:   @{ xt @}
                   3264:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3265:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3266:   1 cells POSTPONE literal POSTPONE +loop ;
                   3267: 
                   3268: : sum-array ( addr u -- n )
                   3269:  0 rot rot [ ' + compile-map-array ] ;
                   3270: see sum-array
                   3271: a 5 sum-array .
                   3272: @end example
                   3273: 
                   3274: You can use the full power of Forth for generating the code; here's an
                   3275: example where the code is generated in a loop:
                   3276: 
                   3277: @example
                   3278: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3279: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3280:   POSTPONE tuck POSTPONE @@
1.48      anton    3281:   POSTPONE literal POSTPONE * POSTPONE +
                   3282:   POSTPONE swap POSTPONE cell+ ;
                   3283: 
                   3284: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3285: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3286:   0 postpone literal postpone swap
                   3287:   [ ' compile-vmul-step compile-map-array ]
                   3288:   postpone drop ;
                   3289: see compile-vmul
                   3290: 
                   3291: : a-vmul ( addr -- n )
1.51      pazsan   3292: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3293:  [ a 5 compile-vmul ] ;
                   3294: see a-vmul
                   3295: a a-vmul .
                   3296: @end example
                   3297: 
                   3298: This example uses @code{compile-map-array} to show off, but you could
1.66      anton    3299: also use @code{map-array} instead (try it now!).
1.48      anton    3300: 
                   3301: You can use this technique for efficient multiplication of large
                   3302: matrices.  In matrix multiplication, you multiply every line of one
                   3303: matrix with every column of the other matrix.  You can generate the code
                   3304: for one line once, and use it for every column.  The only downside of
                   3305: this technique is that it is cumbersome to recover the memory consumed
                   3306: by the generated code when you are done (and in more complicated cases
                   3307: it is not possible portably).
                   3308: 
1.66      anton    3309: @c !! @xref{Macros} for reference
                   3310: 
                   3311: 
1.48      anton    3312: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3313: @section Compilation Tokens
1.66      anton    3314: @cindex compilation tokens, tutorial
                   3315: @cindex CT, tutorial
1.48      anton    3316: 
                   3317: This section is Gforth-specific.  You can skip it.
                   3318: 
                   3319: @code{' word compile,} compiles the interpretation semantics.  For words
                   3320: with default compilation semantics this is the same as performing the
                   3321: compilation semantics.  To represent the compilation semantics of other
                   3322: words (e.g., words like @code{if} that have no interpretation
                   3323: semantics), Gforth has the concept of a compilation token (CT,
                   3324: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3325: You can perform the compilation semantics represented by a CT with
                   3326: @code{execute}:
1.29      crook    3327: 
1.48      anton    3328: @example
                   3329: : foo2 ( n1 n2 -- n )
                   3330:    [ comp' + execute ] ;
                   3331: see foo
                   3332: @end example
1.29      crook    3333: 
1.48      anton    3334: You can compile the compilation semantics represented by a CT with
                   3335: @code{postpone,}:
1.30      anton    3336: 
1.48      anton    3337: @example
                   3338: : foo3 ( -- )
                   3339:   [ comp' + postpone, ] ;
                   3340: see foo3
                   3341: @end example
1.30      anton    3342: 
1.51      pazsan   3343: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3344: @code{comp'} is particularly useful for words that have no
                   3345: interpretation semantics:
1.29      crook    3346: 
1.30      anton    3347: @example
1.48      anton    3348: ' if
1.60      anton    3349: comp' if .s 2drop
1.30      anton    3350: @end example
                   3351: 
1.66      anton    3352: Reference: @ref{Tokens for Words}.
                   3353: 
1.29      crook    3354: 
1.48      anton    3355: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3356: @section Wordlists and Search Order
1.66      anton    3357: @cindex wordlists tutorial
                   3358: @cindex search order, tutorial
1.48      anton    3359: 
                   3360: The dictionary is not just a memory area that allows you to allocate
                   3361: memory with @code{allot}, it also contains the Forth words, arranged in
                   3362: several wordlists.  When searching for a word in a wordlist,
                   3363: conceptually you start searching at the youngest and proceed towards
                   3364: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3365: you define a word with the same name as an older word, the new word
                   3366: shadows the older word.
                   3367: 
                   3368: Which wordlists are searched in which order is determined by the search
                   3369: order.  You can display the search order with @code{order}.  It displays
                   3370: first the search order, starting with the wordlist searched first, then
                   3371: it displays the wordlist that will contain newly defined words.
1.21      crook    3372: 
1.48      anton    3373: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3374: 
1.48      anton    3375: @example
                   3376: wordlist constant mywords
                   3377: @end example
1.21      crook    3378: 
1.48      anton    3379: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3380: defined words (the @emph{current} wordlist):
1.21      crook    3381: 
1.48      anton    3382: @example
                   3383: mywords set-current
                   3384: order
                   3385: @end example
1.26      crook    3386: 
1.48      anton    3387: Gforth does not display a name for the wordlist in @code{mywords}
                   3388: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3389: 
1.48      anton    3390: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3391: you want to put something into a specific wordlist without overall
                   3392: effect on the current wordlist, this typically looks like this:
1.21      crook    3393: 
1.48      anton    3394: @example
                   3395: get-current mywords set-current ( wid )
                   3396: create someword
                   3397: ( wid ) set-current
                   3398: @end example
1.21      crook    3399: 
1.48      anton    3400: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3401: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3402: searched wordlist is topmost.
1.21      crook    3403: 
1.48      anton    3404: @example
                   3405: get-order mywords swap 1+ set-order
                   3406: order
                   3407: @end example
1.21      crook    3408: 
1.48      anton    3409: Yes, the order of wordlists in the output of @code{order} is reversed
                   3410: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3411: 
1.48      anton    3412: @assignment
                   3413: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3414: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3415: removes the first searched wordlist from the search order.  Experiment
                   3416: with boundary conditions (you will see some crashes or situations that
                   3417: are hard or impossible to leave).
                   3418: @endassignment
1.21      crook    3419: 
1.48      anton    3420: The search order is a powerful foundation for providing features similar
                   3421: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3422: programs in this way has disadvantages for debugging and reuse/factoring
                   3423: that overcome the advantages in my experience (I don't do huge projects,
1.55      anton    3424: though).  These disadvantages are not so clear in other
1.48      anton    3425: languages/programming environments, because these langauges are not so
                   3426: strong in debugging and reuse.
1.21      crook    3427: 
1.66      anton    3428: @c !! example
                   3429: 
                   3430: Reference: @ref{Word Lists}.
1.21      crook    3431: 
1.29      crook    3432: @c ******************************************************************
1.48      anton    3433: @node Introduction, Words, Tutorial, Top
1.29      crook    3434: @comment node-name,     next,           previous, up
                   3435: @chapter An Introduction to ANS Forth
                   3436: @cindex Forth - an introduction
1.21      crook    3437: 
1.29      crook    3438: The primary purpose of this manual is to document Gforth. However, since
                   3439: Forth is not a widely-known language and there is a lack of up-to-date
                   3440: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3441: material.  For other sources of Forth-related
                   3442: information, see @ref{Forth-related information}.
1.21      crook    3443: 
1.29      crook    3444: The examples in this section should work on any ANS Forth; the
                   3445: output shown was produced using Gforth. Each example attempts to
                   3446: reproduce the exact output that Gforth produces. If you try out the
                   3447: examples (and you should), what you should type is shown @kbd{like this}
                   3448: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3449: that, where the example shows @key{RET} it means that you should
1.29      crook    3450: press the ``carriage return'' key. Unfortunately, some output formats for
                   3451: this manual cannot show the difference between @kbd{this} and
                   3452: @code{this} which will make trying out the examples harder (but not
                   3453: impossible).
1.21      crook    3454: 
1.29      crook    3455: Forth is an unusual language. It provides an interactive development
                   3456: environment which includes both an interpreter and compiler. Forth
                   3457: programming style encourages you to break a problem down into many
                   3458: @cindex factoring
                   3459: small fragments (@dfn{factoring}), and then to develop and test each
                   3460: fragment interactively. Forth advocates assert that breaking the
                   3461: edit-compile-test cycle used by conventional programming languages can
                   3462: lead to great productivity improvements.
1.21      crook    3463: 
1.29      crook    3464: @menu
1.67      anton    3465: * Introducing the Text Interpreter::  
                   3466: * Stacks and Postfix notation::  
                   3467: * Your first definition::       
                   3468: * How does that work?::         
                   3469: * Forth is written in Forth::   
                   3470: * Review - elements of a Forth system::  
                   3471: * Where to go next::            
                   3472: * Exercises::                   
1.29      crook    3473: @end menu
1.21      crook    3474: 
1.29      crook    3475: @comment ----------------------------------------------
                   3476: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3477: @section Introducing the Text Interpreter
                   3478: @cindex text interpreter
                   3479: @cindex outer interpreter
1.21      crook    3480: 
1.30      anton    3481: @c IMO this is too detailed and the pace is too slow for
                   3482: @c an introduction.  If you know German, take a look at
                   3483: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3484: @c to see how I do it - anton 
                   3485: 
1.44      crook    3486: @c nac-> Where I have accepted your comments 100% and modified the text
                   3487: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3488: @c response like this to attempt to rationalise what I have done. Of
                   3489: @c course, this is a very clumsy mechanism for something that would be
                   3490: @c done far more efficiently over a beer. Please delete any dialogue
                   3491: @c you consider closed.
                   3492: 
1.29      crook    3493: When you invoke the Forth image, you will see a startup banner printed
                   3494: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3495: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3496: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3497: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3498: about the text interpreter as you read through this chapter, for more
                   3499: detail @pxref{The Text Interpreter}).
1.21      crook    3500: 
1.29      crook    3501: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3502: input. Type a number and press the @key{RET} key:
1.21      crook    3503: 
1.26      crook    3504: @example
1.30      anton    3505: @kbd{45@key{RET}}  ok
1.26      crook    3506: @end example
1.21      crook    3507: 
1.29      crook    3508: Rather than give you a prompt to invite you to input something, the text
                   3509: interpreter prints a status message @i{after} it has processed a line
                   3510: of input. The status message in this case (``@code{ ok}'' followed by
                   3511: carriage-return) indicates that the text interpreter was able to process
                   3512: all of your input successfully. Now type something illegal:
                   3513: 
                   3514: @example
1.30      anton    3515: @kbd{qwer341@key{RET}}
1.29      crook    3516: :1: Undefined word
                   3517: qwer341
                   3518: ^^^^^^^
                   3519: $400D2BA8 Bounce
                   3520: $400DBDA8 no.extensions
                   3521: @end example
1.23      crook    3522: 
1.29      crook    3523: The exact text, other than the ``Undefined word'' may differ slightly on
                   3524: your system, but the effect is the same; when the text interpreter
                   3525: detects an error, it discards any remaining text on a line, resets
1.49      anton    3526: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
                   3527: messages}.
1.23      crook    3528: 
1.29      crook    3529: The text interpreter waits for you to press carriage-return, and then
                   3530: processes your input line. Starting at the beginning of the line, it
                   3531: breaks the line into groups of characters separated by spaces. For each
                   3532: group of characters in turn, it makes two attempts to do something:
1.23      crook    3533: 
1.29      crook    3534: @itemize @bullet
                   3535: @item
1.44      crook    3536: @cindex name dictionary
1.29      crook    3537: It tries to treat it as a command. It does this by searching a @dfn{name
                   3538: dictionary}. If the group of characters matches an entry in the name
                   3539: dictionary, the name dictionary provides the text interpreter with
                   3540: information that allows the text interpreter perform some actions. In
                   3541: Forth jargon, we say that the group
                   3542: @cindex word
                   3543: @cindex definition
                   3544: @cindex execution token
                   3545: @cindex xt
                   3546: of characters names a @dfn{word}, that the dictionary search returns an
                   3547: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3548: word, and that the text interpreter executes the xt. Often, the terms
                   3549: @dfn{word} and @dfn{definition} are used interchangeably.
                   3550: @item
                   3551: If the text interpreter fails to find a match in the name dictionary, it
                   3552: tries to treat the group of characters as a number in the current number
                   3553: base (when you start up Forth, the current number base is base 10). If
                   3554: the group of characters legitimately represents a number, the text
                   3555: interpreter pushes the number onto a stack (we'll learn more about that
                   3556: in the next section).
                   3557: @end itemize
1.23      crook    3558: 
1.29      crook    3559: If the text interpreter is unable to do either of these things with any
                   3560: group of characters, it discards the group of characters and the rest of
                   3561: the line, then prints an error message. If the text interpreter reaches
                   3562: the end of the line without error, it prints the status message ``@code{ ok}''
                   3563: followed by carriage-return.
1.21      crook    3564: 
1.29      crook    3565: This is the simplest command we can give to the text interpreter:
1.23      crook    3566: 
                   3567: @example
1.30      anton    3568: @key{RET}  ok
1.23      crook    3569: @end example
1.21      crook    3570: 
1.29      crook    3571: The text interpreter did everything we asked it to do (nothing) without
                   3572: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3573: command:
1.21      crook    3574: 
1.23      crook    3575: @example
1.30      anton    3576: @kbd{12 dup fred dup@key{RET}}
1.29      crook    3577: :1: Undefined word
                   3578: 12 dup fred dup
                   3579:        ^^^^
                   3580: $400D2BA8 Bounce
                   3581: $400DBDA8 no.extensions
1.23      crook    3582: @end example
1.21      crook    3583: 
1.29      crook    3584: When you press the carriage-return key, the text interpreter starts to
                   3585: work its way along the line:
1.21      crook    3586: 
1.29      crook    3587: @itemize @bullet
                   3588: @item
                   3589: When it gets to the space after the @code{2}, it takes the group of
                   3590: characters @code{12} and looks them up in the name
                   3591: dictionary@footnote{We can't tell if it found them or not, but assume
                   3592: for now that it did not}. There is no match for this group of characters
                   3593: in the name dictionary, so it tries to treat them as a number. It is
                   3594: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3595: (whatever that means).
                   3596: @item
                   3597: The text interpreter resumes scanning the line and gets the next group
                   3598: of characters, @code{dup}. It looks it up in the name dictionary and
                   3599: (you'll have to take my word for this) finds it, and executes the word
                   3600: @code{dup} (whatever that means).
                   3601: @item
                   3602: Once again, the text interpreter resumes scanning the line and gets the
                   3603: group of characters @code{fred}. It looks them up in the name
                   3604: dictionary, but can't find them. It tries to treat them as a number, but
                   3605: they don't represent any legal number.
                   3606: @end itemize
1.21      crook    3607: 
1.29      crook    3608: At this point, the text interpreter gives up and prints an error
                   3609: message. The error message shows exactly how far the text interpreter
                   3610: got in processing the line. In particular, it shows that the text
                   3611: interpreter made no attempt to do anything with the final character
                   3612: group, @code{dup}, even though we have good reason to believe that the
                   3613: text interpreter would have no problem looking that word up and
                   3614: executing it a second time.
1.21      crook    3615: 
                   3616: 
1.29      crook    3617: @comment ----------------------------------------------
                   3618: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3619: @section Stacks, postfix notation and parameter passing
                   3620: @cindex text interpreter
                   3621: @cindex outer interpreter
1.21      crook    3622: 
1.29      crook    3623: In procedural programming languages (like C and Pascal), the
                   3624: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3625: functions or procedures are called with @dfn{explicit parameters}. For
                   3626: example, in C we might write:
1.21      crook    3627: 
1.23      crook    3628: @example
1.29      crook    3629: total = total + new_volume(length,height,depth);
1.23      crook    3630: @end example
1.21      crook    3631: 
1.23      crook    3632: @noindent
1.29      crook    3633: where new_volume is a function-call to another piece of code, and total,
                   3634: length, height and depth are all variables. length, height and depth are
                   3635: parameters to the function-call.
1.21      crook    3636: 
1.29      crook    3637: In Forth, the equivalent of the function or procedure is the
                   3638: @dfn{definition} and parameters are implicitly passed between
                   3639: definitions using a shared stack that is visible to the
                   3640: programmer. Although Forth does support variables, the existence of the
                   3641: stack means that they are used far less often than in most other
                   3642: programming languages. When the text interpreter encounters a number, it
                   3643: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3644: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3645: used for any operation is implied unambiguously by the operation being
                   3646: performed. The stack used for all integer operations is called the @dfn{data
                   3647: stack} and, since this is the stack used most commonly, references to
                   3648: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3649: 
1.29      crook    3650: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3651: 
1.23      crook    3652: @example
1.30      anton    3653: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3654: @end example
1.21      crook    3655: 
1.29      crook    3656: Then this instructs the text interpreter to placed three numbers on the
                   3657: (data) stack. An analogy for the behaviour of the stack is to take a
                   3658: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3659: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3660: you take a card off the pile then, unless you're prepared to fiddle a
                   3661: bit, the card that you take off will be the 3 (``first-out''). The
                   3662: number that will be first-out of the stack is called the @dfn{top of
                   3663: stack}, which
                   3664: @cindex TOS definition
                   3665: is often abbreviated to @dfn{TOS}.
1.21      crook    3666: 
1.29      crook    3667: To understand how parameters are passed in Forth, consider the
                   3668: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3669: be surprised to learn that this definition performs addition. More
                   3670: precisely, it adds two number together and produces a result. Where does
                   3671: it get the two numbers from? It takes the top two numbers off the
                   3672: stack. Where does it place the result? On the stack. You can act-out the
                   3673: behaviour of @code{+} with your playing cards like this:
1.21      crook    3674: 
                   3675: @itemize @bullet
                   3676: @item
1.29      crook    3677: Pick up two cards from the stack on the table
1.21      crook    3678: @item
1.29      crook    3679: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3680: numbers''
1.21      crook    3681: @item
1.29      crook    3682: Decide that the answer is 5
1.21      crook    3683: @item
1.29      crook    3684: Shuffle the two cards back into the pack and find a 5
1.21      crook    3685: @item
1.29      crook    3686: Put a 5 on the remaining ace that's on the table.
1.21      crook    3687: @end itemize
                   3688: 
1.29      crook    3689: If you don't have a pack of cards handy but you do have Forth running,
                   3690: you can use the definition @code{.s} to show the current state of the stack,
                   3691: without affecting the stack. Type:
1.21      crook    3692: 
                   3693: @example
1.30      anton    3694: @kbd{clearstack 1 2 3@key{RET}} ok
                   3695: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3696: @end example
                   3697: 
1.29      crook    3698: The text interpreter looks up the word @code{clearstack} and executes
                   3699: it; it tidies up the stack and removes any entries that may have been
                   3700: left on it by earlier examples. The text interpreter pushes each of the
                   3701: three numbers in turn onto the stack. Finally, the text interpreter
                   3702: looks up the word @code{.s} and executes it. The effect of executing
                   3703: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3704: followed by a list of all the items on the stack; the item on the far
                   3705: right-hand side is the TOS.
1.21      crook    3706: 
1.29      crook    3707: You can now type:
1.21      crook    3708: 
1.29      crook    3709: @example
1.30      anton    3710: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3711: @end example
1.21      crook    3712: 
1.29      crook    3713: @noindent
                   3714: which is correct; there are now 2 items on the stack and the result of
                   3715: the addition is 5.
1.23      crook    3716: 
1.29      crook    3717: If you're playing with cards, try doing a second addition: pick up the
                   3718: two cards, work out that their sum is 6, shuffle them into the pack,
                   3719: look for a 6 and place that on the table. You now have just one item on
                   3720: the stack. What happens if you try to do a third addition? Pick up the
                   3721: first card, pick up the second card -- ah! There is no second card. This
                   3722: is called a @dfn{stack underflow} and consitutes an error. If you try to
                   3723: do the same thing with Forth it will report an error (probably a Stack
                   3724: Underflow or an Invalid Memory Address error).
1.23      crook    3725: 
1.29      crook    3726: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3727: which simply accepts that there is a finite amount of storage space
                   3728: reserved for the stack. To stretch the playing card analogy, if you had
                   3729: enough packs of cards and you piled the cards up on the table, you would
                   3730: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3731: allows you to set the maximum size of the stacks. In general, the only
                   3732: time that you will get a stack overflow is because a definition has a
                   3733: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3734: 
1.29      crook    3735: There's one final use for the playing card analogy. If you model your
                   3736: stack using a pack of playing cards, the maximum number of items on
                   3737: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3738: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3739: possible numbers are positive integer numbers 1 through 13; you can't
                   3740: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3741: think about some of the cards, you can accommodate different
                   3742: numbers. For example, you could think of the Jack as representing 0,
                   3743: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3744: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3745: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3746: 
1.29      crook    3747: In that analogy, the limit was the amount of information that a single
                   3748: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3749: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3750: implementation dependent and affects the maximum value that a stack
                   3751: entry can hold. A Standard Forth provides a cell size of at least
                   3752: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3753: 
1.29      crook    3754: Forth does not do any type checking for you, so you are free to
                   3755: manipulate and combine stack items in any way you wish. A convenient way
                   3756: of treating stack items is as 2's complement signed integers, and that
                   3757: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3758: 
1.29      crook    3759: @example
1.30      anton    3760: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3761: @end example
1.21      crook    3762: 
1.29      crook    3763: If you use numbers and definitions like @code{+} in order to turn Forth
                   3764: into a great big pocket calculator, you will realise that it's rather
                   3765: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3766: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3767: result). The terminology used to describe this difference is to say that
                   3768: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3769: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3770: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3771: 
1.29      crook    3772: Whilst postfix notation might look confusing to begin with, it has
                   3773: several important advantages:
1.21      crook    3774: 
1.23      crook    3775: @itemize @bullet
                   3776: @item
1.29      crook    3777: it is unambiguous
1.23      crook    3778: @item
1.29      crook    3779: it is more concise
1.23      crook    3780: @item
1.29      crook    3781: it fits naturally with a stack-based system
1.23      crook    3782: @end itemize
1.21      crook    3783: 
1.29      crook    3784: To examine these claims in more detail, consider these sums:
1.21      crook    3785: 
1.29      crook    3786: @example
                   3787: 6 + 5 * 4 =
                   3788: 4 * 5 + 6 =
                   3789: @end example
1.21      crook    3790: 
1.29      crook    3791: If you're just learning maths or your maths is very rusty, you will
                   3792: probably come up with the answer 44 for the first and 26 for the
                   3793: second. If you are a bit of a whizz at maths you will remember the
                   3794: @i{convention} that multiplication takes precendence over addition, and
                   3795: you'd come up with the answer 26 both times. To explain the answer 26
                   3796: to someone who got the answer 44, you'd probably rewrite the first sum
                   3797: like this:
1.21      crook    3798: 
1.29      crook    3799: @example
                   3800: 6 + (5 * 4) =
                   3801: @end example
1.21      crook    3802: 
1.29      crook    3803: If what you really wanted was to perform the addition before the
                   3804: multiplication, you would have to use parentheses to force it.
1.21      crook    3805: 
1.29      crook    3806: If you did the first two sums on a pocket calculator you would probably
                   3807: get the right answers, unless you were very cautious and entered them using
                   3808: these keystroke sequences:
1.21      crook    3809: 
1.29      crook    3810: 6 + 5 = * 4 =
                   3811: 4 * 5 = + 6 =
1.21      crook    3812: 
1.29      crook    3813: Postfix notation is unambiguous because the order that the operators
                   3814: are applied is always explicit; that also means that parentheses are
                   3815: never required. The operators are @i{active} (the act of quoting the
                   3816: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3817: 
1.29      crook    3818: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3819: equivalent ways:
1.26      crook    3820: 
                   3821: @example
1.29      crook    3822: 6 5 4 * +      or:
                   3823: 5 4 * 6 +
1.26      crook    3824: @end example
1.23      crook    3825: 
1.29      crook    3826: An important thing that you should notice about this notation is that
                   3827: the @i{order} of the numbers does not change; if you want to subtract
                   3828: 2 from 10 you type @code{10 2 -}.
1.1       anton    3829: 
1.29      crook    3830: The reason that Forth uses postfix notation is very simple to explain: it
                   3831: makes the implementation extremely simple, and it follows naturally from
                   3832: using the stack as a mechanism for passing parameters. Another way of
                   3833: thinking about this is to realise that all Forth definitions are
                   3834: @i{active}; they execute as they are encountered by the text
                   3835: interpreter. The result of this is that the syntax of Forth is trivially
                   3836: simple.
1.1       anton    3837: 
                   3838: 
                   3839: 
1.29      crook    3840: @comment ----------------------------------------------
                   3841: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3842: @section Your first Forth definition
                   3843: @cindex first definition
1.1       anton    3844: 
1.29      crook    3845: Until now, the examples we've seen have been trivial; we've just been
                   3846: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3847: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3848: again@footnote{That's not quite true. If you press the up-arrow key on
                   3849: your keyboard you should be able to scroll back to any earlier command,
                   3850: edit it and re-enter it.} In this section we'll see how to add new
                   3851: words to Forth's vocabulary.
1.1       anton    3852: 
1.29      crook    3853: The easiest way to create a new word is to use a @dfn{colon
                   3854: definition}. We'll define a few and try them out before worrying too
                   3855: much about how they work. Try typing in these examples; be careful to
                   3856: copy the spaces accurately:
1.1       anton    3857: 
1.29      crook    3858: @example
                   3859: : add-two 2 + . ;
                   3860: : greet ." Hello and welcome" ;
                   3861: : demo 5 add-two ;
                   3862: @end example
1.1       anton    3863: 
1.29      crook    3864: @noindent
                   3865: Now try them out:
1.1       anton    3866: 
1.29      crook    3867: @example
1.30      anton    3868: @kbd{greet@key{RET}} Hello and welcome  ok
                   3869: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3870: @kbd{4 add-two@key{RET}} 6  ok
                   3871: @kbd{demo@key{RET}} 7  ok
                   3872: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3873: @end example
1.1       anton    3874: 
1.29      crook    3875: The first new thing that we've introduced here is the pair of words
                   3876: @code{:} and @code{;}. These are used to start and terminate a new
                   3877: definition, respectively. The first word after the @code{:} is the name
                   3878: for the new definition.
1.1       anton    3879: 
1.29      crook    3880: As you can see from the examples, a definition is built up of words that
                   3881: have already been defined; Forth makes no distinction between
                   3882: definitions that existed when you started the system up, and those that
                   3883: you define yourself.
1.1       anton    3884: 
1.29      crook    3885: The examples also introduce the words @code{.} (dot), @code{."}
                   3886: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3887: the stack and displays it. It's like @code{.s} except that it only
                   3888: displays the top item of the stack and it is destructive; after it has
                   3889: executed, the number is no longer on the stack. There is always one
                   3890: space printed after the number, and no spaces before it. Dot-quote
                   3891: defines a string (a sequence of characters) that will be printed when
                   3892: the word is executed. The string can contain any printable characters
                   3893: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3894: word but it acts as a delimiter (the way that delimiters work is
                   3895: described in the next section). Finally, @code{dup} duplicates the value
                   3896: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3897: 
1.29      crook    3898: We already know that the text interpreter searches through the
                   3899: dictionary to locate names. If you've followed the examples earlier, you
                   3900: will already have a definition called @code{add-two}. Lets try modifying
                   3901: it by typing in a new definition:
1.1       anton    3902: 
1.29      crook    3903: @example
1.30      anton    3904: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3905: @end example
1.5       anton    3906: 
1.29      crook    3907: Forth recognised that we were defining a word that already exists, and
                   3908: printed a message to warn us of that fact. Let's try out the new
                   3909: definition:
1.5       anton    3910: 
1.29      crook    3911: @example
1.30      anton    3912: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3913: @end example
1.1       anton    3914: 
1.29      crook    3915: @noindent
                   3916: All that we've actually done here, though, is to create a new
                   3917: definition, with a particular name. The fact that there was already a
                   3918: definition with the same name did not make any difference to the way
                   3919: that the new definition was created (except that Forth printed a warning
                   3920: message). The old definition of add-two still exists (try @code{demo}
                   3921: again to see that this is true). Any new definition will use the new
                   3922: definition of @code{add-two}, but old definitions continue to use the
                   3923: version that already existed at the time that they were @code{compiled}.
1.1       anton    3924: 
1.29      crook    3925: Before you go on to the next section, try defining and redefining some
                   3926: words of your own.
1.1       anton    3927: 
1.29      crook    3928: @comment ----------------------------------------------
                   3929: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3930: @section How does that work?
                   3931: @cindex parsing words
1.1       anton    3932: 
1.30      anton    3933: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3934: 
                   3935: @c Is it a good idea to talk about the interpretation semantics of a
                   3936: @c number? We don't have an xt to go along with it. - anton
                   3937: 
                   3938: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3939: @c be better to keep them (or add run-time semantics), to make it easier to
                   3940: @c explain what compilation semantics usually does. - anton
                   3941: 
1.44      crook    3942: @c nac-> I removed the term ``default compilation sematics'' from the
                   3943: @c introductory chapter. Removing ``execution semantics'' was making
                   3944: @c everything simpler to explain, then I think the use of this term made
                   3945: @c everything more complex again. I replaced it with ``default
                   3946: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3947: @c ``a definition that has neither the immediate nor the compile-only
                   3948: @c flag set''. I reworded big chunks of the ``how does that work''
                   3949: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3950: @c what you think -- I know I have not addressed your primary concern
                   3951: @c that it is too heavy-going for an introduction. From what I understood
                   3952: @c of your course notes it looks as though they might be a good framework. 
                   3953: @c Things that I've tried to capture here are some things that came as a
                   3954: @c great revelation here when I first understood them. Also, I like the
                   3955: @c fact that a very simple code example shows up almost all of the issues
                   3956: @c that you need to understand to see how Forth works. That's unique and
                   3957: @c worthwhile to emphasise.
                   3958: 
1.29      crook    3959: Now we're going to take another look at the definition of @code{add-two}
                   3960: from the previous section. From our knowledge of the way that the text
                   3961: interpreter works, we would have expected this result when we tried to
                   3962: define @code{add-two}:
1.21      crook    3963: 
1.29      crook    3964: @example
1.44      crook    3965: @kbd{: add-two 2 + . ;@key{RET}}
1.29      crook    3966:   ^^^^^^^
                   3967: Error: Undefined word
                   3968: @end example
1.28      crook    3969: 
1.29      crook    3970: The reason that this didn't happen is bound up in the way that @code{:}
                   3971: works. The word @code{:} does two special things. The first special
                   3972: thing that it does prevents the text interpreter from ever seeing the
                   3973: characters @code{add-two}. The text interpreter uses a variable called
                   3974: @cindex modifying >IN
1.44      crook    3975: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    3976: input line. When it encounters the word @code{:} it behaves in exactly
                   3977: the same way as it does for any other word; it looks it up in the name
                   3978: dictionary, finds its xt and executes it. When @code{:} executes, it
                   3979: looks at the input buffer, finds the word @code{add-two} and advances the
                   3980: value of @code{>IN} to point past it. It then does some other stuff
                   3981: associated with creating the new definition (including creating an entry
                   3982: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   3983: completes, control returns to the text interpreter, which is oblivious
                   3984: to the fact that it has been tricked into ignoring part of the input
                   3985: line.
1.21      crook    3986: 
1.29      crook    3987: @cindex parsing words
                   3988: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   3989: prevent the text interpreter from acting on the whole of the input line
                   3990: -- are called @dfn{parsing words}.
1.21      crook    3991: 
1.29      crook    3992: @cindex @code{state} - effect on the text interpreter
                   3993: @cindex text interpreter - effect of state
                   3994: The second special thing that @code{:} does is change the value of a
                   3995: variable called @code{state}, which affects the way that the text
                   3996: interpreter behaves. When Gforth starts up, @code{state} has the value
                   3997: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   3998: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    3999: the text interpreter is said to be @dfn{compiling}.
                   4000: 
                   4001: In this example, the text interpreter is compiling when it processes the
                   4002: string ``@code{2 + . ;}''. It still breaks the string down into
                   4003: character sequences in the same way. However, instead of pushing the
                   4004: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   4005: into the definition of @code{add-two} that will make the number @code{2} get
                   4006: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   4007: the behaviours of @code{+} and @code{.} are also compiled into the
                   4008: definition.
                   4009: 
                   4010: One category of words don't get compiled. These so-called @dfn{immediate
                   4011: words} get executed (performed @i{now}) regardless of whether the text
                   4012: interpreter is interpreting or compiling. The word @code{;} is an
                   4013: immediate word. Rather than being compiled into the definition, it
                   4014: executes. Its effect is to terminate the current definition, which
                   4015: includes changing the value of @code{state} back to 0.
                   4016: 
                   4017: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   4018: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   4019: definition.
1.28      crook    4020: 
1.30      anton    4021: In Forth, every word or number can be described in terms of two
1.29      crook    4022: properties:
1.28      crook    4023: 
                   4024: @itemize @bullet
                   4025: @item
1.29      crook    4026: @cindex interpretation semantics
1.44      crook    4027: Its @dfn{interpretation semantics} describe how it will behave when the
                   4028: text interpreter encounters it in @dfn{interpret} state. The
                   4029: interpretation semantics of a word are represented by an @dfn{execution
                   4030: token}.
1.28      crook    4031: @item
1.29      crook    4032: @cindex compilation semantics
1.44      crook    4033: Its @dfn{compilation semantics} describe how it will behave when the
                   4034: text interpreter encounters it in @dfn{compile} state. The compilation
                   4035: semantics of a word are represented in an implementation-dependent way;
                   4036: Gforth uses a @dfn{compilation token}.
1.29      crook    4037: @end itemize
                   4038: 
                   4039: @noindent
                   4040: Numbers are always treated in a fixed way:
                   4041: 
                   4042: @itemize @bullet
1.28      crook    4043: @item
1.44      crook    4044: When the number is @dfn{interpreted}, its behaviour is to push the
                   4045: number onto the stack.
1.28      crook    4046: @item
1.30      anton    4047: When the number is @dfn{compiled}, a piece of code is appended to the
                   4048: current definition that pushes the number when it runs. (In other words,
                   4049: the compilation semantics of a number are to postpone its interpretation
                   4050: semantics until the run-time of the definition that it is being compiled
                   4051: into.)
1.29      crook    4052: @end itemize
                   4053: 
1.44      crook    4054: Words don't behave in such a regular way, but most have @i{default
                   4055: semantics} which means that they behave like this:
1.29      crook    4056: 
                   4057: @itemize @bullet
1.28      crook    4058: @item
1.30      anton    4059: The @dfn{interpretation semantics} of the word are to do something useful.
                   4060: @item
1.29      crook    4061: The @dfn{compilation semantics} of the word are to append its
1.30      anton    4062: @dfn{interpretation semantics} to the current definition (so that its
                   4063: run-time behaviour is to do something useful).
1.28      crook    4064: @end itemize
                   4065: 
1.30      anton    4066: @cindex immediate words
1.44      crook    4067: The actual behaviour of any particular word can be controlled by using
                   4068: the words @code{immediate} and @code{compile-only} when the word is
                   4069: defined. These words set flags in the name dictionary entry of the most
                   4070: recently defined word, and these flags are retrieved by the text
                   4071: interpreter when it finds the word in the name dictionary.
                   4072: 
                   4073: A word that is marked as @dfn{immediate} has compilation semantics that
                   4074: are identical to its interpretation semantics. In other words, it
                   4075: behaves like this:
1.29      crook    4076: 
                   4077: @itemize @bullet
                   4078: @item
1.30      anton    4079: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    4080: @item
1.30      anton    4081: The @dfn{compilation semantics} of the word are to do something useful
                   4082: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    4083: @end itemize
1.28      crook    4084: 
1.44      crook    4085: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   4086: performing the interpretation semantics of the word directly; an attempt
                   4087: to do so will generate an error. It is never necessary to use
                   4088: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   4089: provided by many implementations) but it is good etiquette to apply it
                   4090: to a word that will not behave correctly (and might have unexpected
                   4091: side-effects) in interpret state. For example, it is only legal to use
                   4092: the conditional word @code{IF} within a definition. If you forget this
                   4093: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   4094: @code{compile-only} allows the text interpreter to generate a helpful
                   4095: error message rather than subjecting you to the consequences of your
                   4096: folly.
                   4097: 
1.29      crook    4098: This example shows the difference between an immediate and a
                   4099: non-immediate word:
1.28      crook    4100: 
1.29      crook    4101: @example
                   4102: : show-state state @@ . ;
                   4103: : show-state-now show-state ; immediate
                   4104: : word1 show-state ;
                   4105: : word2 show-state-now ;
1.28      crook    4106: @end example
1.23      crook    4107: 
1.29      crook    4108: The word @code{immediate} after the definition of @code{show-state-now}
                   4109: makes that word an immediate word. These definitions introduce a new
                   4110: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   4111: variable, and leaves it on the stack. Therefore, the behaviour of
                   4112: @code{show-state} is to print a number that represents the current value
                   4113: of @code{state}.
1.28      crook    4114: 
1.29      crook    4115: When you execute @code{word1}, it prints the number 0, indicating that
                   4116: the system is interpreting. When the text interpreter compiled the
                   4117: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    4118: compilation semantics are to append its interpretation semantics to the
1.29      crook    4119: current definition. When you execute @code{word1}, it performs the
1.30      anton    4120: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    4121: (and therefore @code{show-state}) are executed, the system is
                   4122: interpreting.
1.28      crook    4123: 
1.30      anton    4124: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    4125: you should have seen the number -1 printed, followed by ``@code{
                   4126: ok}''. When the text interpreter compiled the definition of
                   4127: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    4128: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4129: semantics. It is executed straight away (even before the text
                   4130: interpreter has moved on to process another group of characters; the
                   4131: @code{;} in this example). The effect of executing it are to display the
                   4132: value of @code{state} @i{at the time that the definition of}
                   4133: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4134: system is compiling at this time. If you execute @code{word2} it does
                   4135: nothing at all.
1.28      crook    4136: 
1.29      crook    4137: @cindex @code{."}, how it works
                   4138: Before leaving the subject of immediate words, consider the behaviour of
                   4139: @code{."} in the definition of @code{greet}, in the previous
                   4140: section. This word is both a parsing word and an immediate word. Notice
                   4141: that there is a space between @code{."} and the start of the text
                   4142: @code{Hello and welcome}, but that there is no space between the last
                   4143: letter of @code{welcome} and the @code{"} character. The reason for this
                   4144: is that @code{."} is a Forth word; it must have a space after it so that
                   4145: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4146: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4147: is displayed, there is neither a space before the @code{H} nor after the
                   4148: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4149: that @code{greet} is defined. When it executes, its behaviour is to
                   4150: search forward in the input line looking for the delimiter. When it
                   4151: finds the delimiter, it updates @code{>IN} to point past the
                   4152: delimiter. It also compiles some magic code into the definition of
                   4153: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4154: compiles the string @code{Hello and welcome} into memory so that it is
                   4155: available to be printed later. When the text interpreter gains control,
                   4156: the next word it finds in the input stream is @code{;} and so it
                   4157: terminates the definition of @code{greet}.
1.28      crook    4158: 
                   4159: 
                   4160: @comment ----------------------------------------------
1.29      crook    4161: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4162: @section Forth is written in Forth
                   4163: @cindex structure of Forth programs
                   4164: 
                   4165: When you start up a Forth compiler, a large number of definitions
                   4166: already exist. In Forth, you develop a new application using bottom-up
                   4167: programming techniques to create new definitions that are defined in
                   4168: terms of existing definitions. As you create each definition you can
                   4169: test and debug it interactively.
                   4170: 
                   4171: If you have tried out the examples in this section, you will probably
                   4172: have typed them in by hand; when you leave Gforth, your definitions will
                   4173: be lost. You can avoid this by using a text editor to enter Forth source
                   4174: code into a file, and then loading code from the file using
1.49      anton    4175: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    4176: processed by the text interpreter, just as though you had typed it in by
                   4177: hand@footnote{Actually, there are some subtle differences -- see
                   4178: @ref{The Text Interpreter}.}.
                   4179: 
                   4180: Gforth also supports the traditional Forth alternative to using text
1.49      anton    4181: files for program entry (@pxref{Blocks}).
1.28      crook    4182: 
1.29      crook    4183: In common with many, if not most, Forth compilers, most of Gforth is
                   4184: actually written in Forth. All of the @file{.fs} files in the
                   4185: installation directory@footnote{For example,
1.30      anton    4186: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4187: study to see examples of Forth programming.
1.28      crook    4188: 
1.29      crook    4189: Gforth maintains a history file that records every line that you type to
                   4190: the text interpreter. This file is preserved between sessions, and is
                   4191: used to provide a command-line recall facility. If you enter long
                   4192: definitions by hand, you can use a text editor to paste them out of the
                   4193: history file into a Forth source file for reuse at a later time
1.49      anton    4194: (for more information @pxref{Command-line editing}).
1.28      crook    4195: 
                   4196: 
                   4197: @comment ----------------------------------------------
1.29      crook    4198: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4199: @section Review - elements of a Forth system
                   4200: @cindex elements of a Forth system
1.28      crook    4201: 
1.29      crook    4202: To summarise this chapter:
1.28      crook    4203: 
                   4204: @itemize @bullet
                   4205: @item
1.29      crook    4206: Forth programs use @dfn{factoring} to break a problem down into small
                   4207: fragments called @dfn{words} or @dfn{definitions}.
                   4208: @item
                   4209: Forth program development is an interactive process.
                   4210: @item
                   4211: The main command loop that accepts input, and controls both
                   4212: interpretation and compilation, is called the @dfn{text interpreter}
                   4213: (also known as the @dfn{outer interpreter}).
                   4214: @item
                   4215: Forth has a very simple syntax, consisting of words and numbers
                   4216: separated by spaces or carriage-return characters. Any additional syntax
                   4217: is imposed by @dfn{parsing words}.
                   4218: @item
                   4219: Forth uses a stack to pass parameters between words. As a result, it
                   4220: uses postfix notation.
                   4221: @item
                   4222: To use a word that has previously been defined, the text interpreter
                   4223: searches for the word in the @dfn{name dictionary}.
                   4224: @item
1.30      anton    4225: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4226: @item
1.29      crook    4227: The text interpreter uses the value of @code{state} to select between
                   4228: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4229: semantics} of a word that it encounters.
1.28      crook    4230: @item
1.30      anton    4231: The relationship between the @dfn{interpretation semantics} and
                   4232: @dfn{compilation semantics} for a word
1.29      crook    4233: depend upon the way in which the word was defined (for example, whether
                   4234: it is an @dfn{immediate} word).
1.28      crook    4235: @item
1.29      crook    4236: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4237: definitions}) or in some other way (usually a lower-level language and
                   4238: as a result often called @dfn{low-level definitions}, @dfn{code
                   4239: definitions} or @dfn{primitives}).
1.28      crook    4240: @item
1.29      crook    4241: Many Forth systems are implemented mainly in Forth.
1.28      crook    4242: @end itemize
                   4243: 
                   4244: 
1.29      crook    4245: @comment ----------------------------------------------
1.48      anton    4246: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4247: @section Where To Go Next
                   4248: @cindex where to go next
1.28      crook    4249: 
1.29      crook    4250: Amazing as it may seem, if you have read (and understood) this far, you
                   4251: know almost all the fundamentals about the inner workings of a Forth
                   4252: system. You certainly know enough to be able to read and understand the
                   4253: rest of this manual and the ANS Forth document, to learn more about the
                   4254: facilities that Forth in general and Gforth in particular provide. Even
                   4255: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4256: However, that's not a good idea just yet... better to try writing some
1.29      crook    4257: programs in Gforth.
1.28      crook    4258: 
1.29      crook    4259: Forth has such a rich vocabulary that it can be hard to know where to
                   4260: start in learning it. This section suggests a few sets of words that are
                   4261: enough to write small but useful programs. Use the word index in this
                   4262: document to learn more about each word, then try it out and try to write
                   4263: small definitions using it. Start by experimenting with these words:
1.28      crook    4264: 
                   4265: @itemize @bullet
                   4266: @item
1.29      crook    4267: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4268: @item
                   4269: Comparison: @code{MIN MAX =}
                   4270: @item
                   4271: Logic: @code{AND OR XOR NOT}
                   4272: @item
                   4273: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4274: @item
1.29      crook    4275: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4276: @item
1.29      crook    4277: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4278: @item
1.29      crook    4279: Defining words: @code{: ; CREATE}
1.28      crook    4280: @item
1.29      crook    4281: Memory allocation words: @code{ALLOT ,}
1.28      crook    4282: @item
1.29      crook    4283: Tools: @code{SEE WORDS .S MARKER}
                   4284: @end itemize
                   4285: 
                   4286: When you have mastered those, go on to:
                   4287: 
                   4288: @itemize @bullet
1.28      crook    4289: @item
1.29      crook    4290: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4291: @item
1.29      crook    4292: Memory access: @code{@@ !}
1.28      crook    4293: @end itemize
1.23      crook    4294: 
1.29      crook    4295: When you have mastered these, there's nothing for it but to read through
                   4296: the whole of this manual and find out what you've missed.
                   4297: 
                   4298: @comment ----------------------------------------------
1.48      anton    4299: @node Exercises,  , Where to go next, Introduction
1.29      crook    4300: @section Exercises
                   4301: @cindex exercises
                   4302: 
                   4303: TODO: provide a set of programming excercises linked into the stuff done
                   4304: already and into other sections of the manual. Provide solutions to all
                   4305: the exercises in a .fs file in the distribution.
                   4306: 
                   4307: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4308: 
                   4309: @c excercises:
                   4310: @c 1. take inches and convert to feet and inches.
                   4311: @c 2. take temperature and convert from fahrenheight to celcius;
                   4312: @c    may need to care about symmetric vs floored??
                   4313: @c 3. take input line and do character substitution
                   4314: @c    to encipher or decipher
                   4315: @c 4. as above but work on a file for in and out
                   4316: @c 5. take input line and convert to pig-latin 
                   4317: @c
                   4318: @c thing of sets of things to exercise then come up with
                   4319: @c problems that need those things.
                   4320: 
                   4321: 
1.26      crook    4322: @c ******************************************************************
1.29      crook    4323: @node Words, Error messages, Introduction, Top
1.1       anton    4324: @chapter Forth Words
1.26      crook    4325: @cindex words
1.1       anton    4326: 
                   4327: @menu
                   4328: * Notation::                    
1.65      anton    4329: * Case insensitivity::          
                   4330: * Comments::                    
                   4331: * Boolean Flags::               
1.1       anton    4332: * Arithmetic::                  
                   4333: * Stack Manipulation::          
1.5       anton    4334: * Memory::                      
1.1       anton    4335: * Control Structures::          
                   4336: * Defining Words::              
1.65      anton    4337: * Interpretation and Compilation Semantics::  
1.47      crook    4338: * Tokens for Words::            
1.81    ! anton    4339: * Compiling words::             
1.65      anton    4340: * The Text Interpreter::        
                   4341: * Word Lists::                  
                   4342: * Environmental Queries::       
1.12      anton    4343: * Files::                       
                   4344: * Blocks::                      
                   4345: * Other I/O::                   
1.78      anton    4346: * Locals::                      
                   4347: * Structures::                  
                   4348: * Object-oriented Forth::       
1.12      anton    4349: * Programming Tools::           
                   4350: * Assembler and Code Words::    
                   4351: * Threading Words::             
1.65      anton    4352: * Passing Commands to the OS::  
                   4353: * Keeping track of Time::       
                   4354: * Miscellaneous Words::         
1.1       anton    4355: @end menu
                   4356: 
1.65      anton    4357: @node Notation, Case insensitivity, Words, Words
1.1       anton    4358: @section Notation
                   4359: @cindex notation of glossary entries
                   4360: @cindex format of glossary entries
                   4361: @cindex glossary notation format
                   4362: @cindex word glossary entry format
                   4363: 
                   4364: The Forth words are described in this section in the glossary notation
1.67      anton    4365: that has become a de-facto standard for Forth texts:
1.1       anton    4366: 
                   4367: @format
1.29      crook    4368: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4369: @end format
1.29      crook    4370: @i{Description}
1.1       anton    4371: 
                   4372: @table @var
                   4373: @item word
1.28      crook    4374: The name of the word.
1.1       anton    4375: 
                   4376: @item Stack effect
                   4377: @cindex stack effect
1.29      crook    4378: The stack effect is written in the notation @code{@i{before} --
                   4379: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4380: stack entries before and after the execution of the word. The rest of
                   4381: the stack is not touched by the word. The top of stack is rightmost,
                   4382: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4383: uses a separate floating point stack, but a unified stack
1.29      crook    4384: notation. Also, return stack effects are not shown in @i{stack
                   4385: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4386: the type and/or the function of the item. See below for a discussion of
                   4387: the types.
                   4388: 
                   4389: All words have two stack effects: A compile-time stack effect and a
                   4390: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4391: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4392: this standard behaviour, or the word does other unusual things at
                   4393: compile time, both stack effects are shown; otherwise only the run-time
                   4394: stack effect is shown.
                   4395: 
                   4396: @cindex pronounciation of words
                   4397: @item pronunciation
                   4398: How the word is pronounced.
                   4399: 
                   4400: @cindex wordset
1.67      anton    4401: @cindex environment wordset
1.1       anton    4402: @item wordset
1.21      crook    4403: The ANS Forth standard is divided into several word sets. A standard
                   4404: system need not support all of them. Therefore, in theory, the fewer
                   4405: word sets your program uses the more portable it will be. However, we
                   4406: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4407: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4408: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4409: describes words that will work in future releases of Gforth;
                   4410: @code{gforth-internal} words are more volatile. Environmental query
                   4411: strings are also displayed like words; you can recognize them by the
1.21      crook    4412: @code{environment} in the word set field.
1.1       anton    4413: 
                   4414: @item Description
                   4415: A description of the behaviour of the word.
                   4416: @end table
                   4417: 
                   4418: @cindex types of stack items
                   4419: @cindex stack item types
                   4420: The type of a stack item is specified by the character(s) the name
                   4421: starts with:
                   4422: 
                   4423: @table @code
                   4424: @item f
                   4425: @cindex @code{f}, stack item type
                   4426: Boolean flags, i.e. @code{false} or @code{true}.
                   4427: @item c
                   4428: @cindex @code{c}, stack item type
                   4429: Char
                   4430: @item w
                   4431: @cindex @code{w}, stack item type
                   4432: Cell, can contain an integer or an address
                   4433: @item n
                   4434: @cindex @code{n}, stack item type
                   4435: signed integer
                   4436: @item u
                   4437: @cindex @code{u}, stack item type
                   4438: unsigned integer
                   4439: @item d
                   4440: @cindex @code{d}, stack item type
                   4441: double sized signed integer
                   4442: @item ud
                   4443: @cindex @code{ud}, stack item type
                   4444: double sized unsigned integer
                   4445: @item r
                   4446: @cindex @code{r}, stack item type
                   4447: Float (on the FP stack)
1.21      crook    4448: @item a-
1.1       anton    4449: @cindex @code{a_}, stack item type
                   4450: Cell-aligned address
1.21      crook    4451: @item c-
1.1       anton    4452: @cindex @code{c_}, stack item type
                   4453: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4454: @item f-
1.1       anton    4455: @cindex @code{f_}, stack item type
                   4456: Float-aligned address
1.21      crook    4457: @item df-
1.1       anton    4458: @cindex @code{df_}, stack item type
                   4459: Address aligned for IEEE double precision float
1.21      crook    4460: @item sf-
1.1       anton    4461: @cindex @code{sf_}, stack item type
                   4462: Address aligned for IEEE single precision float
                   4463: @item xt
                   4464: @cindex @code{xt}, stack item type
                   4465: Execution token, same size as Cell
                   4466: @item wid
                   4467: @cindex @code{wid}, stack item type
1.21      crook    4468: Word list ID, same size as Cell
1.68      anton    4469: @item ior, wior
                   4470: @cindex ior type description
                   4471: @cindex wior type description
                   4472: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
1.1       anton    4473: @item f83name
                   4474: @cindex @code{f83name}, stack item type
                   4475: Pointer to a name structure
                   4476: @item "
                   4477: @cindex @code{"}, stack item type
1.12      anton    4478: string in the input stream (not on the stack). The terminating character
                   4479: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4480: quotes.
                   4481: @end table
                   4482: 
1.65      anton    4483: @comment ----------------------------------------------
                   4484: @node Case insensitivity, Comments, Notation, Words
                   4485: @section Case insensitivity
                   4486: @cindex case sensitivity
                   4487: @cindex upper and lower case
                   4488: 
                   4489: Gforth is case-insensitive; you can enter definitions and invoke
                   4490: Standard words using upper, lower or mixed case (however,
                   4491: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   4492: options}).
                   4493: 
                   4494: ANS Forth only @i{requires} implementations to recognise Standard words
                   4495: when they are typed entirely in upper case. Therefore, a Standard
                   4496: program must use upper case for all Standard words. You can use whatever
                   4497: case you like for words that you define, but in a Standard program you
                   4498: have to use the words in the same case that you defined them.
                   4499: 
                   4500: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   4501: wordlists, @pxref{Word Lists}).
                   4502: 
                   4503: Two people have asked how to convert Gforth to be case-sensitive; while
                   4504: we think this is a bad idea, you can change all wordlists into tables
                   4505: like this:
                   4506: 
                   4507: @example
                   4508: ' table-find forth-wordlist wordlist-map @ !
                   4509: @end example
                   4510: 
                   4511: Note that you now have to type the predefined words in the same case
                   4512: that we defined them, which are varying.  You may want to convert them
                   4513: to your favourite case before doing this operation (I won't explain how,
                   4514: because if you are even contemplating doing this, you'd better have
                   4515: enough knowledge of Forth systems to know this already).
                   4516: 
                   4517: @node Comments, Boolean Flags, Case insensitivity, Words
1.21      crook    4518: @section Comments
1.26      crook    4519: @cindex comments
1.21      crook    4520: 
1.29      crook    4521: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4522: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4523: 
1.44      crook    4524: 
1.23      crook    4525: doc-(
1.21      crook    4526: doc-\
1.23      crook    4527: doc-\G
1.21      crook    4528: 
1.44      crook    4529: 
1.21      crook    4530: @node Boolean Flags, Arithmetic, Comments, Words
                   4531: @section Boolean Flags
1.26      crook    4532: @cindex Boolean flags
1.21      crook    4533: 
                   4534: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4535: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4536: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4537: a cell that has @i{any} bit set as @code{true}.
1.67      anton    4538: @c on and off to Memory? 
                   4539: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44      crook    4540: 
1.21      crook    4541: doc-true
                   4542: doc-false
1.29      crook    4543: doc-on
                   4544: doc-off
1.21      crook    4545: 
1.44      crook    4546: 
1.21      crook    4547: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4548: @section Arithmetic
                   4549: @cindex arithmetic words
                   4550: 
                   4551: @cindex division with potentially negative operands
                   4552: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4553: overflow on addition or multiplication, you may hear about division by
                   4554: zero if you are lucky. The operator is written after the operands, but
                   4555: the operands are still in the original order. I.e., the infix @code{2-1}
                   4556: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4557: operators. If you perform division with potentially negative operands,
                   4558: you do not want to use @code{/} or @code{/mod} with its undefined
                   4559: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4560: former, @pxref{Mixed precision}).
1.26      crook    4561: @comment TODO discuss the different division forms and the std approach
1.1       anton    4562: 
                   4563: @menu
                   4564: * Single precision::            
1.67      anton    4565: * Double precision::            Double-cell integer arithmetic
1.1       anton    4566: * Bitwise operations::          
1.67      anton    4567: * Numeric comparison::          
1.29      crook    4568: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4569: * Floating Point::              
                   4570: @end menu
                   4571: 
1.67      anton    4572: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1       anton    4573: @subsection Single precision
                   4574: @cindex single precision arithmetic words
                   4575: 
1.67      anton    4576: @c !! cell undefined
                   4577: 
                   4578: By default, numbers in Forth are single-precision integers that are one
1.26      crook    4579: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4580: treat them. For the rules used by the text interpreter for recognising
                   4581: single-precision integers see @ref{Number Conversion}.
1.21      crook    4582: 
1.67      anton    4583: These words are all defined for signed operands, but some of them also
                   4584: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
                   4585: @code{*}.
1.44      crook    4586: 
1.1       anton    4587: doc-+
1.21      crook    4588: doc-1+
1.1       anton    4589: doc--
1.21      crook    4590: doc-1-
1.1       anton    4591: doc-*
                   4592: doc-/
                   4593: doc-mod
                   4594: doc-/mod
                   4595: doc-negate
                   4596: doc-abs
                   4597: doc-min
                   4598: doc-max
1.27      crook    4599: doc-floored
1.1       anton    4600: 
1.44      crook    4601: 
1.67      anton    4602: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21      crook    4603: @subsection Double precision
                   4604: @cindex double precision arithmetic words
                   4605: 
1.49      anton    4606: For the rules used by the text interpreter for
                   4607: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4608: 
                   4609: A double precision number is represented by a cell pair, with the most
1.67      anton    4610: significant cell at the TOS. It is trivial to convert an unsigned single
                   4611: to a double: simply push a @code{0} onto the TOS. Since numbers are
                   4612: represented by Gforth using 2's complement arithmetic, converting a
                   4613: signed single to a (signed) double requires sign-extension across the
                   4614: most significant cell. This can be achieved using @code{s>d}. The moral
                   4615: of the story is that you cannot convert a number without knowing whether
                   4616: it represents an unsigned or a signed number.
1.21      crook    4617: 
1.67      anton    4618: These words are all defined for signed operands, but some of them also
                   4619: work for unsigned numbers: @code{d+}, @code{d-}.
1.44      crook    4620: 
1.21      crook    4621: doc-s>d
1.67      anton    4622: doc-d>s
1.21      crook    4623: doc-d+
                   4624: doc-d-
                   4625: doc-dnegate
                   4626: doc-dabs
                   4627: doc-dmin
                   4628: doc-dmax
                   4629: 
1.44      crook    4630: 
1.67      anton    4631: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
                   4632: @subsection Bitwise operations
                   4633: @cindex bitwise operation words
                   4634: 
                   4635: 
                   4636: doc-and
                   4637: doc-or
                   4638: doc-xor
                   4639: doc-invert
                   4640: doc-lshift
                   4641: doc-rshift
                   4642: doc-2*
                   4643: doc-d2*
                   4644: doc-2/
                   4645: doc-d2/
                   4646: 
                   4647: 
                   4648: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21      crook    4649: @subsection Numeric comparison
                   4650: @cindex numeric comparison words
                   4651: 
1.67      anton    4652: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
                   4653: d0= d0<>}) work for for both signed and unsigned numbers.
1.44      crook    4654: 
1.28      crook    4655: doc-<
                   4656: doc-<=
                   4657: doc-<>
                   4658: doc-=
                   4659: doc->
                   4660: doc->=
                   4661: 
1.21      crook    4662: doc-0<
1.23      crook    4663: doc-0<=
1.21      crook    4664: doc-0<>
                   4665: doc-0=
1.23      crook    4666: doc-0>
                   4667: doc-0>=
1.28      crook    4668: 
                   4669: doc-u<
                   4670: doc-u<=
1.44      crook    4671: @c u<> and u= exist but are the same as <> and =
1.31      anton    4672: @c doc-u<>
                   4673: @c doc-u=
1.28      crook    4674: doc-u>
                   4675: doc-u>=
                   4676: 
                   4677: doc-within
                   4678: 
                   4679: doc-d<
                   4680: doc-d<=
                   4681: doc-d<>
                   4682: doc-d=
                   4683: doc-d>
                   4684: doc-d>=
1.23      crook    4685: 
1.21      crook    4686: doc-d0<
1.23      crook    4687: doc-d0<=
                   4688: doc-d0<>
1.21      crook    4689: doc-d0=
1.23      crook    4690: doc-d0>
                   4691: doc-d0>=
                   4692: 
1.21      crook    4693: doc-du<
1.28      crook    4694: doc-du<=
1.44      crook    4695: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4696: @c doc-du<>
                   4697: @c doc-du=
1.28      crook    4698: doc-du>
                   4699: doc-du>=
1.1       anton    4700: 
1.44      crook    4701: 
1.21      crook    4702: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4703: @subsection Mixed precision
                   4704: @cindex mixed precision arithmetic words
                   4705: 
1.44      crook    4706: 
1.1       anton    4707: doc-m+
                   4708: doc-*/
                   4709: doc-*/mod
                   4710: doc-m*
                   4711: doc-um*
                   4712: doc-m*/
                   4713: doc-um/mod
                   4714: doc-fm/mod
                   4715: doc-sm/rem
                   4716: 
1.44      crook    4717: 
1.21      crook    4718: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4719: @subsection Floating Point
                   4720: @cindex floating point arithmetic words
                   4721: 
1.49      anton    4722: For the rules used by the text interpreter for
                   4723: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4724: 
1.67      anton    4725: Gforth has a separate floating point stack, but the documentation uses
                   4726: the unified notation.@footnote{It's easy to generate the separate
                   4727: notation from that by just separating the floating-point numbers out:
                   4728: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
                   4729: r3 )}.}
1.1       anton    4730: 
                   4731: @cindex floating-point arithmetic, pitfalls
                   4732: Floating point numbers have a number of unpleasant surprises for the
                   4733: unwary (e.g., floating point addition is not associative) and even a few
                   4734: for the wary. You should not use them unless you know what you are doing
                   4735: or you don't care that the results you get are totally bogus. If you
                   4736: want to learn about the problems of floating point numbers (and how to
1.66      anton    4737: avoid them), you might start with @cite{David Goldberg,
                   4738: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
                   4739: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
                   4740: Surveys 23(1):5@minus{}48, March 1991}.
1.1       anton    4741: 
1.44      crook    4742: 
1.21      crook    4743: doc-d>f
                   4744: doc-f>d
1.1       anton    4745: doc-f+
                   4746: doc-f-
                   4747: doc-f*
                   4748: doc-f/
                   4749: doc-fnegate
                   4750: doc-fabs
                   4751: doc-fmax
                   4752: doc-fmin
                   4753: doc-floor
                   4754: doc-fround
                   4755: doc-f**
                   4756: doc-fsqrt
                   4757: doc-fexp
                   4758: doc-fexpm1
                   4759: doc-fln
                   4760: doc-flnp1
                   4761: doc-flog
                   4762: doc-falog
1.32      anton    4763: doc-f2*
                   4764: doc-f2/
                   4765: doc-1/f
                   4766: doc-precision
                   4767: doc-set-precision
                   4768: 
                   4769: @cindex angles in trigonometric operations
                   4770: @cindex trigonometric operations
                   4771: Angles in floating point operations are given in radians (a full circle
                   4772: has 2 pi radians).
                   4773: 
1.1       anton    4774: doc-fsin
                   4775: doc-fcos
                   4776: doc-fsincos
                   4777: doc-ftan
                   4778: doc-fasin
                   4779: doc-facos
                   4780: doc-fatan
                   4781: doc-fatan2
                   4782: doc-fsinh
                   4783: doc-fcosh
                   4784: doc-ftanh
                   4785: doc-fasinh
                   4786: doc-facosh
                   4787: doc-fatanh
1.21      crook    4788: doc-pi
1.28      crook    4789: 
1.32      anton    4790: @cindex equality of floats
                   4791: @cindex floating-point comparisons
1.31      anton    4792: One particular problem with floating-point arithmetic is that comparison
                   4793: for equality often fails when you would expect it to succeed.  For this
                   4794: reason approximate equality is often preferred (but you still have to
1.67      anton    4795: know what you are doing).  Also note that IEEE NaNs may compare
1.68      anton    4796: differently from what you might expect.  The comparison words are:
1.31      anton    4797: 
                   4798: doc-f~rel
                   4799: doc-f~abs
1.68      anton    4800: doc-f~
1.31      anton    4801: doc-f=
                   4802: doc-f<>
                   4803: 
                   4804: doc-f<
                   4805: doc-f<=
                   4806: doc-f>
                   4807: doc-f>=
                   4808: 
1.21      crook    4809: doc-f0<
1.28      crook    4810: doc-f0<=
                   4811: doc-f0<>
1.21      crook    4812: doc-f0=
1.28      crook    4813: doc-f0>
                   4814: doc-f0>=
                   4815: 
1.1       anton    4816: 
                   4817: @node Stack Manipulation, Memory, Arithmetic, Words
                   4818: @section Stack Manipulation
                   4819: @cindex stack manipulation words
                   4820: 
                   4821: @cindex floating-point stack in the standard
1.21      crook    4822: Gforth maintains a number of separate stacks:
                   4823: 
1.29      crook    4824: @cindex data stack
                   4825: @cindex parameter stack
1.21      crook    4826: @itemize @bullet
                   4827: @item
1.29      crook    4828: A data stack (also known as the @dfn{parameter stack}) -- for
                   4829: characters, cells, addresses, and double cells.
1.21      crook    4830: 
1.29      crook    4831: @cindex floating-point stack
1.21      crook    4832: @item
1.44      crook    4833: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4834: 
1.29      crook    4835: @cindex return stack
1.21      crook    4836: @item
1.44      crook    4837: A return stack -- for holding the return addresses of colon
1.32      anton    4838: definitions and other (non-FP) data.
1.21      crook    4839: 
1.29      crook    4840: @cindex locals stack
1.21      crook    4841: @item
1.44      crook    4842: A locals stack -- for holding local variables.
1.21      crook    4843: @end itemize
                   4844: 
1.1       anton    4845: @menu
                   4846: * Data stack::                  
                   4847: * Floating point stack::        
                   4848: * Return stack::                
                   4849: * Locals stack::                
                   4850: * Stack pointer manipulation::  
                   4851: @end menu
                   4852: 
                   4853: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4854: @subsection Data stack
                   4855: @cindex data stack manipulation words
                   4856: @cindex stack manipulations words, data stack
                   4857: 
1.44      crook    4858: 
1.1       anton    4859: doc-drop
                   4860: doc-nip
                   4861: doc-dup
                   4862: doc-over
                   4863: doc-tuck
                   4864: doc-swap
1.21      crook    4865: doc-pick
1.1       anton    4866: doc-rot
                   4867: doc--rot
                   4868: doc-?dup
                   4869: doc-roll
                   4870: doc-2drop
                   4871: doc-2nip
                   4872: doc-2dup
                   4873: doc-2over
                   4874: doc-2tuck
                   4875: doc-2swap
                   4876: doc-2rot
                   4877: 
1.44      crook    4878: 
1.1       anton    4879: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4880: @subsection Floating point stack
                   4881: @cindex floating-point stack manipulation words
                   4882: @cindex stack manipulation words, floating-point stack
                   4883: 
1.32      anton    4884: Whilst every sane Forth has a separate floating-point stack, it is not
                   4885: strictly required; an ANS Forth system could theoretically keep
                   4886: floating-point numbers on the data stack. As an additional difficulty,
                   4887: you don't know how many cells a floating-point number takes. It is
                   4888: reportedly possible to write words in a way that they work also for a
                   4889: unified stack model, but we do not recommend trying it. Instead, just
                   4890: say that your program has an environmental dependency on a separate
                   4891: floating-point stack.
                   4892: 
                   4893: doc-floating-stack
                   4894: 
1.1       anton    4895: doc-fdrop
                   4896: doc-fnip
                   4897: doc-fdup
                   4898: doc-fover
                   4899: doc-ftuck
                   4900: doc-fswap
1.21      crook    4901: doc-fpick
1.1       anton    4902: doc-frot
                   4903: 
1.44      crook    4904: 
1.1       anton    4905: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4906: @subsection Return stack
                   4907: @cindex return stack manipulation words
                   4908: @cindex stack manipulation words, return stack
                   4909: 
1.32      anton    4910: @cindex return stack and locals
                   4911: @cindex locals and return stack
                   4912: A Forth system is allowed to keep local variables on the
                   4913: return stack. This is reasonable, as local variables usually eliminate
                   4914: the need to use the return stack explicitly. So, if you want to produce
                   4915: a standard compliant program and you are using local variables in a
                   4916: word, forget about return stack manipulations in that word (refer to the
                   4917: standard document for the exact rules).
                   4918: 
1.1       anton    4919: doc->r
                   4920: doc-r>
                   4921: doc-r@
                   4922: doc-rdrop
                   4923: doc-2>r
                   4924: doc-2r>
                   4925: doc-2r@
                   4926: doc-2rdrop
                   4927: 
1.44      crook    4928: 
1.1       anton    4929: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4930: @subsection Locals stack
                   4931: 
1.78      anton    4932: Gforth uses an extra locals stack.  It is described, along with the
                   4933: reasons for its existence, in @ref{Locals implementation}.
1.21      crook    4934: 
1.1       anton    4935: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4936: @subsection Stack pointer manipulation
                   4937: @cindex stack pointer manipulation words
                   4938: 
1.44      crook    4939: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    4940: doc-sp0
1.1       anton    4941: doc-sp@
                   4942: doc-sp!
1.21      crook    4943: doc-fp0
1.1       anton    4944: doc-fp@
                   4945: doc-fp!
1.21      crook    4946: doc-rp0
1.1       anton    4947: doc-rp@
                   4948: doc-rp!
1.21      crook    4949: doc-lp0
1.1       anton    4950: doc-lp@
                   4951: doc-lp!
                   4952: 
1.44      crook    4953: 
1.1       anton    4954: @node Memory, Control Structures, Stack Manipulation, Words
                   4955: @section Memory
1.26      crook    4956: @cindex memory words
1.1       anton    4957: 
1.32      anton    4958: @menu
                   4959: * Memory model::                
                   4960: * Dictionary allocation::       
                   4961: * Heap Allocation::             
                   4962: * Memory Access::               
                   4963: * Address arithmetic::          
                   4964: * Memory Blocks::               
                   4965: @end menu
                   4966: 
1.67      anton    4967: In addition to the standard Forth memory allocation words, there is also
                   4968: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   4969: garbage collector}.
                   4970: 
1.32      anton    4971: @node Memory model, Dictionary allocation, Memory, Memory
                   4972: @subsection ANS Forth and Gforth memory models
                   4973: 
                   4974: @c The ANS Forth description is a mess (e.g., is the heap part of
                   4975: @c the dictionary?), so let's not stick to closely with it.
                   4976: 
1.67      anton    4977: ANS Forth considers a Forth system as consisting of several address
                   4978: spaces, of which only @dfn{data space} is managed and accessible with
                   4979: the memory words.  Memory not necessarily in data space includes the
                   4980: stacks, the code (called code space) and the headers (called name
                   4981: space). In Gforth everything is in data space, but the code for the
                   4982: primitives is usually read-only.
1.32      anton    4983: 
                   4984: Data space is divided into a number of areas: The (data space portion of
                   4985: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   4986: refer to the search data structure embodied in word lists and headers,
                   4987: because it is used for looking up names, just as you would in a
                   4988: conventional dictionary.}, the heap, and a number of system-allocated
                   4989: buffers.
                   4990: 
1.68      anton    4991: @cindex address arithmetic restrictions, ANS vs. Gforth
                   4992: @cindex contiguous regions, ANS vs. Gforth
1.32      anton    4993: In ANS Forth data space is also divided into contiguous regions.  You
                   4994: can only use address arithmetic within a contiguous region, not between
                   4995: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    4996: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    4997: allocation}).
                   4998: 
                   4999: Gforth provides one big address space, and address arithmetic can be
                   5000: performed between any addresses. However, in the dictionary headers or
                   5001: code are interleaved with data, so almost the only contiguous data space
                   5002: regions there are those described by ANS Forth as contiguous; but you
                   5003: can be sure that the dictionary is allocated towards increasing
                   5004: addresses even between contiguous regions.  The memory order of
                   5005: allocations in the heap is platform-dependent (and possibly different
                   5006: from one run to the next).
                   5007: 
1.27      crook    5008: 
1.32      anton    5009: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   5010: @subsection Dictionary allocation
1.27      crook    5011: @cindex reserving data space
                   5012: @cindex data space - reserving some
                   5013: 
1.32      anton    5014: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   5015: you want to deallocate X, you also deallocate everything
                   5016: allocated after X.
                   5017: 
1.68      anton    5018: @cindex contiguous regions in dictionary allocation
1.32      anton    5019: The allocations using the words below are contiguous and grow the region
                   5020: towards increasing addresses.  Other words that allocate dictionary
                   5021: memory of any kind (i.e., defining words including @code{:noname}) end
                   5022: the contiguous region and start a new one.
                   5023: 
                   5024: In ANS Forth only @code{create}d words are guaranteed to produce an
                   5025: address that is the start of the following contiguous region.  In
                   5026: particular, the cell allocated by @code{variable} is not guaranteed to
                   5027: be contiguous with following @code{allot}ed memory.
                   5028: 
                   5029: You can deallocate memory by using @code{allot} with a negative argument
                   5030: (with some restrictions, see @code{allot}). For larger deallocations use
                   5031: @code{marker}.
1.27      crook    5032: 
1.29      crook    5033: 
1.27      crook    5034: doc-here
                   5035: doc-unused
                   5036: doc-allot
                   5037: doc-c,
1.29      crook    5038: doc-f,
1.27      crook    5039: doc-,
                   5040: doc-2,
                   5041: 
1.32      anton    5042: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   5043: course you should allocate memory in an aligned way, too. I.e., before
                   5044: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   5045: The words below align @code{here} if it is not already.  Basically it is
                   5046: only already aligned for a type, if the last allocation was a multiple
                   5047: of the size of this type and if @code{here} was aligned for this type
                   5048: before.
                   5049: 
                   5050: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   5051: ANS Forth (@code{maxalign}ed in Gforth).
                   5052: 
                   5053: doc-align
                   5054: doc-falign
                   5055: doc-sfalign
                   5056: doc-dfalign
                   5057: doc-maxalign
                   5058: doc-cfalign
                   5059: 
                   5060: 
                   5061: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   5062: @subsection Heap allocation
                   5063: @cindex heap allocation
                   5064: @cindex dynamic allocation of memory
                   5065: @cindex memory-allocation word set
                   5066: 
1.68      anton    5067: @cindex contiguous regions and heap allocation
1.32      anton    5068: Heap allocation supports deallocation of allocated memory in any
                   5069: order. Dictionary allocation is not affected by it (i.e., it does not
                   5070: end a contiguous region). In Gforth, these words are implemented using
                   5071: the standard C library calls malloc(), free() and resize().
                   5072: 
1.68      anton    5073: The memory region produced by one invocation of @code{allocate} or
                   5074: @code{resize} is internally contiguous.  There is no contiguity between
                   5075: such a region and any other region (including others allocated from the
                   5076: heap).
                   5077: 
1.32      anton    5078: doc-allocate
                   5079: doc-free
                   5080: doc-resize
                   5081: 
1.27      crook    5082: 
1.32      anton    5083: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    5084: @subsection Memory Access
                   5085: @cindex memory access words
                   5086: 
                   5087: doc-@
                   5088: doc-!
                   5089: doc-+!
                   5090: doc-c@
                   5091: doc-c!
                   5092: doc-2@
                   5093: doc-2!
                   5094: doc-f@
                   5095: doc-f!
                   5096: doc-sf@
                   5097: doc-sf!
                   5098: doc-df@
                   5099: doc-df!
                   5100: 
1.68      anton    5101: 
1.32      anton    5102: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   5103: @subsection Address arithmetic
1.1       anton    5104: @cindex address arithmetic words
                   5105: 
1.67      anton    5106: Address arithmetic is the foundation on which you can build data
                   5107: structures like arrays, records (@pxref{Structures}) and objects
                   5108: (@pxref{Object-oriented Forth}).
1.32      anton    5109: 
1.68      anton    5110: @cindex address unit
                   5111: @cindex au (address unit)
1.1       anton    5112: ANS Forth does not specify the sizes of the data types. Instead, it
                   5113: offers a number of words for computing sizes and doing address
1.29      crook    5114: arithmetic. Address arithmetic is performed in terms of address units
                   5115: (aus); on most systems the address unit is one byte. Note that a
                   5116: character may have more than one au, so @code{chars} is no noop (on
1.68      anton    5117: platforms where it is a noop, it compiles to nothing).
1.1       anton    5118: 
1.67      anton    5119: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
                   5120: you have the address of a cell, perform @code{1 cells +}, and you will
                   5121: have the address of the next cell.
                   5122: 
1.68      anton    5123: @cindex contiguous regions and address arithmetic
1.67      anton    5124: In ANS Forth you can perform address arithmetic only within a contiguous
                   5125: region, i.e., if you have an address into one region, you can only add
                   5126: and subtract such that the result is still within the region; you can
                   5127: only subtract or compare addresses from within the same contiguous
                   5128: region.  Reasons: several contiguous regions can be arranged in memory
                   5129: in any way; on segmented systems addresses may have unusual
                   5130: representations, such that address arithmetic only works within a
                   5131: region.  Gforth provides a few more guarantees (linear address space,
                   5132: dictionary grows upwards), but in general I have found it easy to stay
                   5133: within contiguous regions (exception: computing and comparing to the
                   5134: address just beyond the end of an array).
                   5135: 
1.1       anton    5136: @cindex alignment of addresses for types
                   5137: ANS Forth also defines words for aligning addresses for specific
                   5138: types. Many computers require that accesses to specific data types
                   5139: must only occur at specific addresses; e.g., that cells may only be
                   5140: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5141: accesses, it can usually perform aligned accesses faster. 
                   5142: 
                   5143: For the performance-conscious: alignment operations are usually only
                   5144: necessary during the definition of a data structure, not during the
                   5145: (more frequent) accesses to it.
                   5146: 
                   5147: ANS Forth defines no words for character-aligning addresses. This is not
                   5148: an oversight, but reflects the fact that addresses that are not
                   5149: char-aligned have no use in the standard and therefore will not be
                   5150: created.
                   5151: 
                   5152: @cindex @code{CREATE} and alignment
1.29      crook    5153: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5154: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5155: are aligned for all purposes.
                   5156: 
1.26      crook    5157: Note that the ANS Forth word @code{char} has nothing to do with address
                   5158: arithmetic.
1.1       anton    5159: 
1.44      crook    5160: 
1.1       anton    5161: doc-chars
                   5162: doc-char+
                   5163: doc-cells
                   5164: doc-cell+
                   5165: doc-cell
                   5166: doc-aligned
                   5167: doc-floats
                   5168: doc-float+
                   5169: doc-float
                   5170: doc-faligned
                   5171: doc-sfloats
                   5172: doc-sfloat+
                   5173: doc-sfaligned
                   5174: doc-dfloats
                   5175: doc-dfloat+
                   5176: doc-dfaligned
                   5177: doc-maxaligned
                   5178: doc-cfaligned
                   5179: doc-address-unit-bits
                   5180: 
1.44      crook    5181: 
1.32      anton    5182: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5183: @subsection Memory Blocks
                   5184: @cindex memory block words
1.27      crook    5185: @cindex character strings - moving and copying
                   5186: 
1.49      anton    5187: Memory blocks often represent character strings; For ways of storing
                   5188: character strings in memory see @ref{String Formats}.  For other
                   5189: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5190: 
1.67      anton    5191: A few of these words work on address unit blocks.  In that case, you
                   5192: usually have to insert @code{CHARS} before the word when working on
                   5193: character strings.  Most words work on character blocks, and expect a
                   5194: char-aligned address.
                   5195: 
                   5196: When copying characters between overlapping memory regions, use
                   5197: @code{chars move} or choose carefully between @code{cmove} and
                   5198: @code{cmove>}.
1.44      crook    5199: 
1.1       anton    5200: doc-move
                   5201: doc-erase
                   5202: doc-cmove
                   5203: doc-cmove>
                   5204: doc-fill
                   5205: doc-blank
1.21      crook    5206: doc-compare
                   5207: doc-search
1.27      crook    5208: doc--trailing
                   5209: doc-/string
                   5210: 
1.44      crook    5211: 
1.27      crook    5212: @comment TODO examples
                   5213: 
1.1       anton    5214: 
1.26      crook    5215: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5216: @section Control Structures
                   5217: @cindex control structures
                   5218: 
1.33      anton    5219: Control structures in Forth cannot be used interpretively, only in a
                   5220: colon definition@footnote{To be precise, they have no interpretation
                   5221: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5222: not like this limitation, but have not seen a satisfying way around it
                   5223: yet, although many schemes have been proposed.
1.1       anton    5224: 
                   5225: @menu
1.33      anton    5226: * Selection::                   IF ... ELSE ... ENDIF
                   5227: * Simple Loops::                BEGIN ...
1.29      crook    5228: * Counted Loops::               DO
1.67      anton    5229: * Arbitrary control structures::  
                   5230: * Calls and returns::           
1.1       anton    5231: * Exception Handling::          
                   5232: @end menu
                   5233: 
                   5234: @node Selection, Simple Loops, Control Structures, Control Structures
                   5235: @subsection Selection
                   5236: @cindex selection control structures
                   5237: @cindex control structures for selection
                   5238: 
                   5239: @cindex @code{IF} control structure
                   5240: @example
1.29      crook    5241: @i{flag}
1.1       anton    5242: IF
1.29      crook    5243:   @i{code}
1.1       anton    5244: ENDIF
                   5245: @end example
1.21      crook    5246: @noindent
1.33      anton    5247: 
1.44      crook    5248: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5249: with any bit set represents truth) @i{code} is executed.
1.33      anton    5250: 
1.1       anton    5251: @example
1.29      crook    5252: @i{flag}
1.1       anton    5253: IF
1.29      crook    5254:   @i{code1}
1.1       anton    5255: ELSE
1.29      crook    5256:   @i{code2}
1.1       anton    5257: ENDIF
                   5258: @end example
                   5259: 
1.44      crook    5260: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5261: executed.
1.33      anton    5262: 
1.1       anton    5263: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5264: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5265: recommend using @code{ENDIF}, because it is less confusing for people
                   5266: who also know other languages (and is not prone to reinforcing negative
                   5267: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5268: system that only supplies @code{THEN} is simple:
                   5269: @example
1.21      crook    5270: : ENDIF   POSTPONE THEN ; immediate
1.1       anton    5271: @end example
                   5272: 
                   5273: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5274: (adv.)}  has the following meanings:
                   5275: @quotation
                   5276: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5277: (if you were there, then you saw them).
                   5278: @end quotation
                   5279: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5280: and many other programming languages has the meaning 3d.]
                   5281: 
1.21      crook    5282: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5283: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5284: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5285: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5286: @file{compat/control.fs}.
                   5287: 
                   5288: @cindex @code{CASE} control structure
                   5289: @example
1.29      crook    5290: @i{n}
1.1       anton    5291: CASE
1.29      crook    5292:   @i{n1} OF @i{code1} ENDOF
                   5293:   @i{n2} OF @i{code2} ENDOF
1.1       anton    5294:   @dots{}
1.68      anton    5295:   ( n ) @i{default-code} ( n )
1.1       anton    5296: ENDCASE
                   5297: @end example
                   5298: 
1.68      anton    5299: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If no
                   5300: @i{ni} matches, the optional @i{default-code} is executed. The optional
                   5301: default case can be added by simply writing the code after the last
                   5302: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
                   5303: not consume it.
1.1       anton    5304: 
1.69      anton    5305: @progstyle
                   5306: To keep the code understandable, you should ensure that on all paths
                   5307: through a selection construct the stack is changed in the same way
                   5308: (wrt. number and types of stack items consumed and pushed).
                   5309: 
1.1       anton    5310: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5311: @subsection Simple Loops
                   5312: @cindex simple loops
                   5313: @cindex loops without count 
                   5314: 
                   5315: @cindex @code{WHILE} loop
                   5316: @example
                   5317: BEGIN
1.29      crook    5318:   @i{code1}
                   5319:   @i{flag}
1.1       anton    5320: WHILE
1.29      crook    5321:   @i{code2}
1.1       anton    5322: REPEAT
                   5323: @end example
                   5324: 
1.29      crook    5325: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5326: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5327: false, execution continues after the @code{REPEAT}.
                   5328: 
                   5329: @cindex @code{UNTIL} loop
                   5330: @example
                   5331: BEGIN
1.29      crook    5332:   @i{code}
                   5333:   @i{flag}
1.1       anton    5334: UNTIL
                   5335: @end example
                   5336: 
1.29      crook    5337: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5338: 
1.69      anton    5339: @progstyle
                   5340: To keep the code understandable, a complete iteration of the loop should
                   5341: not change the number and types of the items on the stacks.
                   5342: 
1.1       anton    5343: @cindex endless loop
                   5344: @cindex loops, endless
                   5345: @example
                   5346: BEGIN
1.29      crook    5347:   @i{code}
1.1       anton    5348: AGAIN
                   5349: @end example
                   5350: 
                   5351: This is an endless loop.
                   5352: 
                   5353: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5354: @subsection Counted Loops
                   5355: @cindex counted loops
                   5356: @cindex loops, counted
                   5357: @cindex @code{DO} loops
                   5358: 
                   5359: The basic counted loop is:
                   5360: @example
1.29      crook    5361: @i{limit} @i{start}
1.1       anton    5362: ?DO
1.29      crook    5363:   @i{body}
1.1       anton    5364: LOOP
                   5365: @end example
                   5366: 
1.29      crook    5367: This performs one iteration for every integer, starting from @i{start}
                   5368: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5369: accessed with @code{i}. For example, the loop:
1.1       anton    5370: @example
                   5371: 10 0 ?DO
                   5372:   i .
                   5373: LOOP
                   5374: @end example
1.21      crook    5375: @noindent
                   5376: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5377: 
1.1       anton    5378: The index of the innermost loop can be accessed with @code{i}, the index
                   5379: of the next loop with @code{j}, and the index of the third loop with
                   5380: @code{k}.
                   5381: 
1.44      crook    5382: 
1.1       anton    5383: doc-i
                   5384: doc-j
                   5385: doc-k
                   5386: 
1.44      crook    5387: 
1.1       anton    5388: The loop control data are kept on the return stack, so there are some
1.21      crook    5389: restrictions on mixing return stack accesses and counted loop words. In
                   5390: particuler, if you put values on the return stack outside the loop, you
                   5391: cannot read them inside the loop@footnote{well, not in a way that is
                   5392: portable.}. If you put values on the return stack within a loop, you
                   5393: have to remove them before the end of the loop and before accessing the
                   5394: index of the loop.
1.1       anton    5395: 
                   5396: There are several variations on the counted loop:
                   5397: 
1.21      crook    5398: @itemize @bullet
                   5399: @item
                   5400: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5401: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5402: 
                   5403: @example
                   5404: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5405: @end example
                   5406: prints @code{0 1 2 3}
                   5407: 
1.1       anton    5408: 
1.21      crook    5409: @item
                   5410: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5411: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5412: return stack so @code{EXIT} can get to its return address. For example:
                   5413: 
                   5414: @example
                   5415: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5416: @end example
                   5417: prints @code{0 1 2 3}
                   5418: 
                   5419: 
                   5420: @item
1.29      crook    5421: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5422: (and @code{LOOP} iterates until they become equal by wrap-around
                   5423: arithmetic). This behaviour is usually not what you want. Therefore,
                   5424: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5425: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5426: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5427: unsigned loop parameters.
                   5428: 
1.21      crook    5429: @item
                   5430: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5431: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5432: if you know that the loop is entered in any case. Such knowledge tends
                   5433: to become invalid during maintenance of a program, and then the
                   5434: @code{DO} will make trouble.
                   5435: 
                   5436: @item
1.29      crook    5437: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5438: index by @i{n} instead of by 1. The loop is terminated when the border
                   5439: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5440: 
1.21      crook    5441: @example
                   5442: 4 0 +DO  i .  2 +LOOP
                   5443: @end example
                   5444: @noindent
                   5445: prints @code{0 2}
                   5446: 
                   5447: @example
                   5448: 4 1 +DO  i .  2 +LOOP
                   5449: @end example
                   5450: @noindent
                   5451: prints @code{1 3}
1.1       anton    5452: 
1.68      anton    5453: @item
1.1       anton    5454: @cindex negative increment for counted loops
                   5455: @cindex counted loops with negative increment
1.29      crook    5456: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5457: 
1.21      crook    5458: @example
                   5459: -1 0 ?DO  i .  -1 +LOOP
                   5460: @end example
                   5461: @noindent
                   5462: prints @code{0 -1}
1.1       anton    5463: 
1.21      crook    5464: @example
                   5465: 0 0 ?DO  i .  -1 +LOOP
                   5466: @end example
                   5467: prints nothing.
1.1       anton    5468: 
1.29      crook    5469: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5470: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5471: index by @i{u} each iteration. The loop is terminated when the border
                   5472: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5473: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5474: 
1.21      crook    5475: @example
                   5476: -2 0 -DO  i .  1 -LOOP
                   5477: @end example
                   5478: @noindent
                   5479: prints @code{0 -1}
1.1       anton    5480: 
1.21      crook    5481: @example
                   5482: -1 0 -DO  i .  1 -LOOP
                   5483: @end example
                   5484: @noindent
                   5485: prints @code{0}
                   5486: 
                   5487: @example
                   5488: 0 0 -DO  i .  1 -LOOP
                   5489: @end example
                   5490: @noindent
                   5491: prints nothing.
1.1       anton    5492: 
1.21      crook    5493: @end itemize
1.1       anton    5494: 
                   5495: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5496: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5497: for these words that uses only standard words is provided in
                   5498: @file{compat/loops.fs}.
1.1       anton    5499: 
                   5500: 
                   5501: @cindex @code{FOR} loops
1.26      crook    5502: Another counted loop is:
1.1       anton    5503: @example
1.29      crook    5504: @i{n}
1.1       anton    5505: FOR
1.29      crook    5506:   @i{body}
1.1       anton    5507: NEXT
                   5508: @end example
                   5509: This is the preferred loop of native code compiler writers who are too
1.26      crook    5510: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5511: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5512: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5513: Forth systems may behave differently, even if they support @code{FOR}
                   5514: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5515: 
                   5516: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5517: @subsection Arbitrary control structures
                   5518: @cindex control structures, user-defined
                   5519: 
                   5520: @cindex control-flow stack
                   5521: ANS Forth permits and supports using control structures in a non-nested
                   5522: way. Information about incomplete control structures is stored on the
                   5523: control-flow stack. This stack may be implemented on the Forth data
                   5524: stack, and this is what we have done in Gforth.
                   5525: 
                   5526: @cindex @code{orig}, control-flow stack item
                   5527: @cindex @code{dest}, control-flow stack item
                   5528: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5529: entry represents a backward branch target. A few words are the basis for
                   5530: building any control structure possible (except control structures that
                   5531: need storage, like calls, coroutines, and backtracking).
                   5532: 
1.44      crook    5533: 
1.1       anton    5534: doc-if
                   5535: doc-ahead
                   5536: doc-then
                   5537: doc-begin
                   5538: doc-until
                   5539: doc-again
                   5540: doc-cs-pick
                   5541: doc-cs-roll
                   5542: 
1.44      crook    5543: 
1.21      crook    5544: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5545: manipulate the control-flow stack in a portable way. Without them, you
                   5546: would need to know how many stack items are occupied by a control-flow
                   5547: entry (many systems use one cell. In Gforth they currently take three,
                   5548: but this may change in the future).
                   5549: 
1.1       anton    5550: Some standard control structure words are built from these words:
                   5551: 
1.44      crook    5552: 
1.1       anton    5553: doc-else
                   5554: doc-while
                   5555: doc-repeat
                   5556: 
1.44      crook    5557: 
                   5558: @noindent
1.1       anton    5559: Gforth adds some more control-structure words:
                   5560: 
1.44      crook    5561: 
1.1       anton    5562: doc-endif
                   5563: doc-?dup-if
                   5564: doc-?dup-0=-if
                   5565: 
1.44      crook    5566: 
                   5567: @noindent
1.1       anton    5568: Counted loop words constitute a separate group of words:
                   5569: 
1.44      crook    5570: 
1.1       anton    5571: doc-?do
                   5572: doc-+do
                   5573: doc-u+do
                   5574: doc--do
                   5575: doc-u-do
                   5576: doc-do
                   5577: doc-for
                   5578: doc-loop
                   5579: doc-+loop
                   5580: doc--loop
                   5581: doc-next
                   5582: doc-leave
                   5583: doc-?leave
                   5584: doc-unloop
                   5585: doc-done
                   5586: 
1.44      crook    5587: 
1.21      crook    5588: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5589: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5590: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5591: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5592: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5593: resolved (by using one of the loop-ending words or @code{DONE}).
                   5594: 
1.44      crook    5595: @noindent
1.26      crook    5596: Another group of control structure words are:
1.1       anton    5597: 
1.44      crook    5598: 
1.1       anton    5599: doc-case
                   5600: doc-endcase
                   5601: doc-of
                   5602: doc-endof
                   5603: 
1.44      crook    5604: 
1.21      crook    5605: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5606: @code{CS-ROLL}.
1.1       anton    5607: 
                   5608: @subsubsection Programming Style
1.47      crook    5609: @cindex control structures programming style
                   5610: @cindex programming style, arbitrary control structures
1.1       anton    5611: 
                   5612: In order to ensure readability we recommend that you do not create
                   5613: arbitrary control structures directly, but define new control structure
                   5614: words for the control structure you want and use these words in your
1.26      crook    5615: program. For example, instead of writing:
1.1       anton    5616: 
                   5617: @example
1.26      crook    5618: BEGIN
1.1       anton    5619:   ...
1.26      crook    5620: IF [ 1 CS-ROLL ]
1.1       anton    5621:   ...
1.26      crook    5622: AGAIN THEN
1.1       anton    5623: @end example
                   5624: 
1.21      crook    5625: @noindent
1.1       anton    5626: we recommend defining control structure words, e.g.,
                   5627: 
                   5628: @example
1.26      crook    5629: : WHILE ( DEST -- ORIG DEST )
                   5630:  POSTPONE IF
                   5631:  1 CS-ROLL ; immediate
                   5632: 
                   5633: : REPEAT ( orig dest -- )
                   5634:  POSTPONE AGAIN
                   5635:  POSTPONE THEN ; immediate
1.1       anton    5636: @end example
                   5637: 
1.21      crook    5638: @noindent
1.1       anton    5639: and then using these to create the control structure:
                   5640: 
                   5641: @example
1.26      crook    5642: BEGIN
1.1       anton    5643:   ...
1.26      crook    5644: WHILE
1.1       anton    5645:   ...
1.26      crook    5646: REPEAT
1.1       anton    5647: @end example
                   5648: 
                   5649: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5650: @code{WHILE} are predefined, so in this example it would not be
                   5651: necessary to define them.
                   5652: 
                   5653: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5654: @subsection Calls and returns
                   5655: @cindex calling a definition
                   5656: @cindex returning from a definition
                   5657: 
1.3       anton    5658: @cindex recursive definitions
                   5659: A definition can be called simply be writing the name of the definition
1.26      crook    5660: to be called. Normally a definition is invisible during its own
1.3       anton    5661: definition. If you want to write a directly recursive definition, you
1.26      crook    5662: can use @code{recursive} to make the current definition visible, or
                   5663: @code{recurse} to call the current definition directly.
1.3       anton    5664: 
1.44      crook    5665: 
1.3       anton    5666: doc-recursive
                   5667: doc-recurse
                   5668: 
1.44      crook    5669: 
1.21      crook    5670: @comment TODO add example of the two recursion methods
1.12      anton    5671: @quotation
                   5672: @progstyle
                   5673: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5674: definition by name is more descriptive (if the name is well-chosen) than
                   5675: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5676: implementation, it is much better to read (and think) ``now sort the
                   5677: partitions'' than to read ``now do a recursive call''.
                   5678: @end quotation
1.3       anton    5679: 
1.29      crook    5680: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5681: 
                   5682: @example
1.28      crook    5683: Defer foo
1.3       anton    5684: 
                   5685: : bar ( ... -- ... )
                   5686:  ... foo ... ;
                   5687: 
                   5688: :noname ( ... -- ... )
                   5689:  ... bar ... ;
                   5690: IS foo
                   5691: @end example
                   5692: 
1.44      crook    5693: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33      anton    5694: 
1.26      crook    5695: The current definition returns control to the calling definition when
1.33      anton    5696: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5697: 
                   5698: doc-exit
                   5699: doc-;s
                   5700: 
1.44      crook    5701: 
1.1       anton    5702: @node Exception Handling,  , Calls and returns, Control Structures
                   5703: @subsection Exception Handling
1.26      crook    5704: @cindex exceptions
1.1       anton    5705: 
1.68      anton    5706: @c quit is a very bad idea for error handling, 
                   5707: @c because it does not translate into a THROW
                   5708: @c it also does not belong into this chapter
                   5709: 
                   5710: If a word detects an error condition that it cannot handle, it can
                   5711: @code{throw} an exception.  In the simplest case, this will terminate
                   5712: your program, and report an appropriate error.
1.21      crook    5713: 
1.68      anton    5714: doc-throw
1.1       anton    5715: 
1.69      anton    5716: @code{Throw} consumes a cell-sized error number on the stack. There are
                   5717: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
                   5718: Gforth (and most other systems) you can use the iors produced by various
                   5719: words as error numbers (e.g., a typical use of @code{allocate} is
                   5720: @code{allocate throw}).  Gforth also provides the word @code{exception}
                   5721: to define your own error numbers (with decent error reporting); an ANS
                   5722: Forth version of this word (but without the error messages) is available
                   5723: in @code{compat/except.fs}.  And finally, you can use your own error
1.68      anton    5724: numbers (anything outside the range -4095..0), but won't get nice error
                   5725: messages, only numbers.  For example, try:
                   5726: 
                   5727: @example
1.69      anton    5728: -10 throw                    \ ANS defined
                   5729: -267 throw                   \ system defined
                   5730: s" my error" exception throw \ user defined
                   5731: 7 throw                      \ arbitrary number
1.68      anton    5732: @end example
                   5733: 
                   5734: doc---exception-exception
1.1       anton    5735: 
1.69      anton    5736: A common idiom to @code{THROW} a specific error if a flag is true is
                   5737: this:
                   5738: 
                   5739: @example
                   5740: @code{( flag ) 0<> @i{errno} and throw}
                   5741: @end example
                   5742: 
                   5743: Your program can provide exception handlers to catch exceptions.  An
                   5744: exception handler can be used to correct the problem, or to clean up
                   5745: some data structures and just throw the exception to the next exception
                   5746: handler.  Note that @code{throw} jumps to the dynamically innermost
                   5747: exception handler.  The system's exception handler is outermost, and just
                   5748: prints an error and restarts command-line interpretation (or, in batch
                   5749: mode (i.e., while processing the shell command line), leaves Gforth).
1.1       anton    5750: 
1.68      anton    5751: The ANS Forth way to catch exceptions is @code{catch}:
1.1       anton    5752: 
1.68      anton    5753: doc-catch
                   5754: 
                   5755: The most common use of exception handlers is to clean up the state when
                   5756: an error happens.  E.g.,
1.1       anton    5757: 
1.26      crook    5758: @example
1.68      anton    5759: base @ >r hex \ actually the hex should be inside foo, or we h
                   5760: ['] foo catch ( nerror|0 )
                   5761: r> base !
1.69      anton    5762: ( nerror|0 ) throw \ pass it on
1.26      crook    5763: @end example
1.1       anton    5764: 
1.69      anton    5765: A use of @code{catch} for handling the error @code{myerror} might look
                   5766: like this:
1.44      crook    5767: 
1.68      anton    5768: @example
1.69      anton    5769: ['] foo catch
                   5770: CASE
                   5771:   myerror OF ... ( do something about it ) ENDOF
                   5772:   dup throw \ default: pass other errors on, do nothing on non-errors
                   5773: ENDCASE
1.68      anton    5774: @end example
1.44      crook    5775: 
1.68      anton    5776: Having to wrap the code into a separate word is often cumbersome,
                   5777: therefore Gforth provides an alternative syntax:
1.1       anton    5778: 
                   5779: @example
1.69      anton    5780: TRY
1.68      anton    5781:   @i{code1}
1.69      anton    5782: RECOVER     \ optional
1.68      anton    5783:   @i{code2} \ optional
1.69      anton    5784: ENDTRY
1.1       anton    5785: @end example
                   5786: 
1.68      anton    5787: This performs @i{Code1}.  If @i{code1} completes normally, execution
                   5788: continues after the @code{endtry}.  If @i{Code1} throws, the stacks are
                   5789: reset to the state during @code{try}, the throw value is pushed on the
                   5790: data stack, and execution constinues at @i{code2}, and finally falls
                   5791: through the @code{endtry} into the following code. If there is no
                   5792: @code{recover} clause, this works like an empty recover clause.
1.26      crook    5793: 
1.68      anton    5794: doc-try
                   5795: doc-recover
                   5796: doc-endtry
1.26      crook    5797: 
1.69      anton    5798: The cleanup example from above in this syntax:
1.26      crook    5799: 
1.68      anton    5800: @example
1.69      anton    5801: base @ >r TRY
1.68      anton    5802:   hex foo \ now the hex is placed correctly
1.69      anton    5803:   0       \ value for throw
                   5804: ENDTRY
1.68      anton    5805: r> base ! throw
1.1       anton    5806: @end example
                   5807: 
1.69      anton    5808: And here's the error handling example:
1.1       anton    5809: 
1.68      anton    5810: @example
1.69      anton    5811: TRY
1.68      anton    5812:   foo
1.69      anton    5813: RECOVER
                   5814:   CASE
                   5815:     myerror OF ... ( do something about it ) ENDOF
                   5816:     throw \ pass other errors on
                   5817:   ENDCASE
                   5818: ENDTRY
1.68      anton    5819: @end example
1.1       anton    5820: 
1.69      anton    5821: @progstyle
                   5822: As usual, you should ensure that the stack depth is statically known at
                   5823: the end: either after the @code{throw} for passing on errors, or after
                   5824: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
                   5825: selection construct for handling the error).
                   5826: 
1.68      anton    5827: There are two alternatives to @code{throw}: @code{Abort"} is conditional
                   5828: and you can provide an error message.  @code{Abort} just produces an
                   5829: ``Aborted'' error.
1.1       anton    5830: 
1.68      anton    5831: The problem with these words is that exception handlers cannot
                   5832: differentiate between different @code{abort"}s; they just look like
                   5833: @code{-2 throw} to them (the error message cannot be accessed by
                   5834: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
                   5835: exception handlers.
1.44      crook    5836: 
1.68      anton    5837: doc-abort"
1.26      crook    5838: doc-abort
1.29      crook    5839: 
                   5840: 
1.44      crook    5841: 
1.29      crook    5842: @c -------------------------------------------------------------
1.47      crook    5843: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    5844: @section Defining Words
                   5845: @cindex defining words
                   5846: 
1.47      crook    5847: Defining words are used to extend Forth by creating new entries in the dictionary.
                   5848: 
1.29      crook    5849: @menu
1.67      anton    5850: * CREATE::                      
1.44      crook    5851: * Variables::                   Variables and user variables
1.67      anton    5852: * Constants::                   
1.44      crook    5853: * Values::                      Initialised variables
1.67      anton    5854: * Colon Definitions::           
1.44      crook    5855: * Anonymous Definitions::       Definitions without names
1.69      anton    5856: * Supplying names::             Passing definition names as strings
1.67      anton    5857: * User-defined Defining Words::  
1.44      crook    5858: * Deferred words::              Allow forward references
1.67      anton    5859: * Aliases::                     
1.29      crook    5860: @end menu
                   5861: 
1.44      crook    5862: @node CREATE, Variables, Defining Words, Defining Words
                   5863: @subsection @code{CREATE}
1.29      crook    5864: @cindex simple defining words
                   5865: @cindex defining words, simple
                   5866: 
                   5867: Defining words are used to create new entries in the dictionary. The
                   5868: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   5869: this:
                   5870: 
                   5871: @example
                   5872: CREATE new-word1
                   5873: @end example
                   5874: 
1.69      anton    5875: @code{CREATE} is a parsing word, i.e., it takes an argument from the
                   5876: input stream (@code{new-word1} in our example).  It generates a
                   5877: dictionary entry for @code{new-word1}. When @code{new-word1} is
                   5878: executed, all that it does is leave an address on the stack. The address
                   5879: represents the value of the data space pointer (@code{HERE}) at the time
                   5880: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
                   5881: associating a name with the address of a region of memory.
1.29      crook    5882: 
1.34      anton    5883: doc-create
                   5884: 
1.69      anton    5885: Note that in ANS Forth guarantees only for @code{create} that its body
                   5886: is in dictionary data space (i.e., where @code{here}, @code{allot}
                   5887: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
                   5888: @code{create}d words can be modified with @code{does>}
                   5889: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
                   5890: can only be applied to @code{create}d words.
                   5891: 
1.29      crook    5892: By extending this example to reserve some memory in data space, we end
1.69      anton    5893: up with something like a @i{variable}. Here are two different ways to do
                   5894: it:
1.29      crook    5895: 
                   5896: @example
                   5897: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   5898: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   5899: @end example
                   5900: 
                   5901: The variable can be examined and modified using @code{@@} (``fetch'') and
                   5902: @code{!} (``store'') like this:
                   5903: 
                   5904: @example
                   5905: new-word2 @@ .      \ get address, fetch from it and display
                   5906: 1234 new-word2 !   \ new value, get address, store to it
                   5907: @end example
                   5908: 
1.44      crook    5909: @cindex arrays
                   5910: A similar mechanism can be used to create arrays. For example, an
                   5911: 80-character text input buffer:
1.29      crook    5912: 
                   5913: @example
1.44      crook    5914: CREATE text-buf 80 chars allot
                   5915: 
                   5916: text-buf 0 chars c@@ \ the 1st character (offset 0)
                   5917: text-buf 3 chars c@@ \ the 4th character (offset 3)
                   5918: @end example
1.29      crook    5919: 
1.44      crook    5920: You can build arbitrarily complex data structures by allocating
1.49      anton    5921: appropriate areas of memory. For further discussions of this, and to
1.66      anton    5922: learn about some Gforth tools that make it easier,
1.49      anton    5923: @xref{Structures}.
1.44      crook    5924: 
                   5925: 
                   5926: @node Variables, Constants, CREATE, Defining Words
                   5927: @subsection Variables
                   5928: @cindex variables
                   5929: 
                   5930: The previous section showed how a sequence of commands could be used to
                   5931: generate a variable.  As a final refinement, the whole code sequence can
                   5932: be wrapped up in a defining word (pre-empting the subject of the next
                   5933: section), making it easier to create new variables:
                   5934: 
                   5935: @example
                   5936: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   5937: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   5938: 
                   5939: myvariableX foo \ variable foo starts off with an unknown value
                   5940: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    5941: 
                   5942: 45 3 * foo !   \ set foo to 135
                   5943: 1234 joe !     \ set joe to 1234
                   5944: 3 joe +!       \ increment joe by 3.. to 1237
                   5945: @end example
                   5946: 
                   5947: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    5948: Forth already has a definition @code{Variable}. ANS Forth does not
1.69      anton    5949: guarantee that a @code{Variable} is initialised when it is created
                   5950: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
                   5951: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
                   5952: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    5953: @code{fvariable} for double and floating-point variables, respectively
1.69      anton    5954: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47      crook    5955: store a boolean, you can use @code{on} and @code{off} to toggle its
                   5956: state.
1.29      crook    5957: 
1.34      anton    5958: doc-variable
                   5959: doc-2variable
                   5960: doc-fvariable
                   5961: 
1.29      crook    5962: @cindex user variables
                   5963: @cindex user space
                   5964: The defining word @code{User} behaves in the same way as @code{Variable}.
                   5965: The difference is that it reserves space in @i{user (data) space} rather
                   5966: than normal data space. In a Forth system that has a multi-tasker, each
                   5967: task has its own set of user variables.
                   5968: 
1.34      anton    5969: doc-user
1.67      anton    5970: @c doc-udp
                   5971: @c doc-uallot
1.34      anton    5972: 
1.29      crook    5973: @comment TODO is that stuff about user variables strictly correct? Is it
                   5974: @comment just terminal tasks that have user variables?
                   5975: @comment should document tasker.fs (with some examples) elsewhere
                   5976: @comment in this manual, then expand on user space and user variables.
                   5977: 
1.44      crook    5978: @node Constants, Values, Variables, Defining Words
                   5979: @subsection Constants
                   5980: @cindex constants
                   5981: 
                   5982: @code{Constant} allows you to declare a fixed value and refer to it by
                   5983: name. For example:
1.29      crook    5984: 
                   5985: @example
                   5986: 12 Constant INCHES-PER-FOOT
                   5987: 3E+08 fconstant SPEED-O-LIGHT
                   5988: @end example
                   5989: 
                   5990: A @code{Variable} can be both read and written, so its run-time
                   5991: behaviour is to supply an address through which its current value can be
                   5992: manipulated. In contrast, the value of a @code{Constant} cannot be
                   5993: changed once it has been declared@footnote{Well, often it can be -- but
                   5994: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   5995: on).} so it's not necessary to supply the address -- it is more
                   5996: efficient to return the value of the constant directly. That's exactly
                   5997: what happens; the run-time effect of a constant is to put its value on
1.49      anton    5998: the top of the stack (You can find one
                   5999: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    6000: 
1.69      anton    6001: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29      crook    6002: double and floating-point constants, respectively.
                   6003: 
1.34      anton    6004: doc-constant
                   6005: doc-2constant
                   6006: doc-fconstant
                   6007: 
                   6008: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    6009: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   6010: @c constant, use it and then delete the definition of the constant..
1.69      anton    6011: 
                   6012: @c anton->An ANS Forth system can compile a constant to a literal; On
                   6013: @c decompilation you would see only the number, just as if it had been used
                   6014: @c in the first place.  The word will stay, of course, but it will only be
                   6015: @c used by the text interpreter (no run-time duties, except when it is 
                   6016: @c POSTPONEd or somesuch).
                   6017: 
                   6018: @c nac:
1.44      crook    6019: @c I agree that it's rather deep, but IMO it is an important difference
                   6020: @c relative to other programming languages.. often it's annoying: it
                   6021: @c certainly changes my programming style relative to C.
                   6022: 
1.69      anton    6023: @c anton: In what way?
                   6024: 
1.29      crook    6025: Constants in Forth behave differently from their equivalents in other
                   6026: programming languages. In other languages, a constant (such as an EQU in
                   6027: assembler or a #define in C) only exists at compile-time; in the
                   6028: executable program the constant has been translated into an absolute
                   6029: number and, unless you are using a symbolic debugger, it's impossible to
                   6030: know what abstract thing that number represents. In Forth a constant has
1.44      crook    6031: an entry in the header space and remains there after the code that uses
                   6032: it has been defined. In fact, it must remain in the dictionary since it
                   6033: has run-time duties to perform. For example:
1.29      crook    6034: 
                   6035: @example
                   6036: 12 Constant INCHES-PER-FOOT
                   6037: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   6038: @end example
                   6039: 
                   6040: @cindex in-lining of constants
                   6041: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   6042: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   6043: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   6044: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   6045: attempt to optimise constants by in-lining them where they are used. You
                   6046: can force Gforth to in-line a constant like this:
                   6047: 
                   6048: @example
                   6049: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   6050: @end example
                   6051: 
                   6052: If you use @code{see} to decompile @i{this} version of
                   6053: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    6054: longer present. To understand how this works, read
                   6055: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    6056: 
                   6057: In-lining constants in this way might improve execution time
                   6058: fractionally, and can ensure that a constant is now only referenced at
                   6059: compile-time. However, the definition of the constant still remains in
                   6060: the dictionary. Some Forth compilers provide a mechanism for controlling
                   6061: a second dictionary for holding transient words such that this second
                   6062: dictionary can be deleted later in order to recover memory
                   6063: space. However, there is no standard way of doing this.
                   6064: 
                   6065: 
1.44      crook    6066: @node Values, Colon Definitions, Constants, Defining Words
                   6067: @subsection Values
                   6068: @cindex values
1.34      anton    6069: 
1.69      anton    6070: A @code{Value} behaves like a @code{Constant}, but it can be changed.
                   6071: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
                   6072: (not in ANS Forth) you can access (and change) a @code{value} also with
                   6073: @code{>body}.
                   6074: 
                   6075: Here are some
                   6076: examples:
1.29      crook    6077: 
                   6078: @example
1.69      anton    6079: 12 Value APPLES     \ Define APPLES with an initial value of 12
                   6080: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
                   6081: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
                   6082: APPLES              \ puts 35 on the top of the stack.
1.29      crook    6083: @end example
                   6084: 
1.44      crook    6085: doc-value
                   6086: doc-to
1.29      crook    6087: 
1.35      anton    6088: 
1.69      anton    6089: 
1.44      crook    6090: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   6091: @subsection Colon Definitions
                   6092: @cindex colon definitions
1.35      anton    6093: 
                   6094: @example
1.44      crook    6095: : name ( ... -- ... )
                   6096:     word1 word2 word3 ;
1.29      crook    6097: @end example
                   6098: 
1.44      crook    6099: @noindent
                   6100: Creates a word called @code{name} that, upon execution, executes
                   6101: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    6102: 
1.49      anton    6103: The explanation above is somewhat superficial. For simple examples of
                   6104: colon definitions see @ref{Your first definition}.  For an in-depth
1.66      anton    6105: discussion of some of the issues involved, @xref{Interpretation and
1.49      anton    6106: Compilation Semantics}.
1.29      crook    6107: 
1.44      crook    6108: doc-:
                   6109: doc-;
1.1       anton    6110: 
1.34      anton    6111: 
1.69      anton    6112: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44      crook    6113: @subsection Anonymous Definitions
                   6114: @cindex colon definitions
                   6115: @cindex defining words without name
1.34      anton    6116: 
1.44      crook    6117: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   6118: name. You can do this with:
1.1       anton    6119: 
1.44      crook    6120: doc-:noname
1.1       anton    6121: 
1.44      crook    6122: This leaves the execution token for the word on the stack after the
                   6123: closing @code{;}. Here's an example in which a deferred word is
                   6124: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6125: 
1.29      crook    6126: @example
1.44      crook    6127: Defer deferred
                   6128: :noname ( ... -- ... )
                   6129:   ... ;
                   6130: IS deferred
1.29      crook    6131: @end example
1.26      crook    6132: 
1.44      crook    6133: @noindent
                   6134: Gforth provides an alternative way of doing this, using two separate
                   6135: words:
1.27      crook    6136: 
1.44      crook    6137: doc-noname
                   6138: @cindex execution token of last defined word
                   6139: doc-lastxt
1.1       anton    6140: 
1.44      crook    6141: @noindent
                   6142: The previous example can be rewritten using @code{noname} and
                   6143: @code{lastxt}:
1.1       anton    6144: 
1.26      crook    6145: @example
1.44      crook    6146: Defer deferred
                   6147: noname : ( ... -- ... )
                   6148:   ... ;
                   6149: lastxt IS deferred
1.26      crook    6150: @end example
1.1       anton    6151: 
1.29      crook    6152: @noindent
1.44      crook    6153: @code{noname} works with any defining word, not just @code{:}.
                   6154: 
                   6155: @code{lastxt} also works when the last word was not defined as
1.71      anton    6156: @code{noname}.  It does not work for combined words, though.  It also has
                   6157: the useful property that is is valid as soon as the header for a
                   6158: definition has been built. Thus:
1.44      crook    6159: 
                   6160: @example
                   6161: lastxt . : foo [ lastxt . ] ; ' foo .
                   6162: @end example
1.1       anton    6163: 
1.44      crook    6164: @noindent
                   6165: prints 3 numbers; the last two are the same.
1.26      crook    6166: 
1.69      anton    6167: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
                   6168: @subsection Supplying the name of a defined word
                   6169: @cindex names for defined words
                   6170: @cindex defining words, name given in a string
                   6171: 
                   6172: By default, a defining word takes the name for the defined word from the
                   6173: input stream. Sometimes you want to supply the name from a string. You
                   6174: can do this with:
                   6175: 
                   6176: doc-nextname
                   6177: 
                   6178: For example:
                   6179: 
                   6180: @example
                   6181: s" foo" nextname create
                   6182: @end example
                   6183: 
                   6184: @noindent
                   6185: is equivalent to:
                   6186: 
                   6187: @example
                   6188: create foo
                   6189: @end example
                   6190: 
                   6191: @noindent
                   6192: @code{nextname} works with any defining word.
                   6193: 
1.1       anton    6194: 
1.69      anton    6195: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26      crook    6196: @subsection User-defined Defining Words
                   6197: @cindex user-defined defining words
                   6198: @cindex defining words, user-defined
1.1       anton    6199: 
1.29      crook    6200: You can create a new defining word by wrapping defining-time code around
                   6201: an existing defining word and putting the sequence in a colon
1.69      anton    6202: definition. 
                   6203: 
                   6204: @c anton: This example is very complex and leads in a quite different
                   6205: @c direction from the CREATE-DOES> stuff that follows.  It should probably
                   6206: @c be done elsewhere, or as a subsubsection of this subsection (or as a
                   6207: @c subsection of Defining Words)
                   6208: 
                   6209: For example, suppose that you have a word @code{stats} that
1.29      crook    6210: gathers statistics about colon definitions given the @i{xt} of the
                   6211: definition, and you want every colon definition in your application to
                   6212: make a call to @code{stats}. You can define and use a new version of
                   6213: @code{:} like this:
                   6214: 
                   6215: @example
                   6216: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6217:   ... ;  \ other code
                   6218: 
                   6219: : my: : lastxt postpone literal ['] stats compile, ;
                   6220: 
                   6221: my: foo + - ;
                   6222: @end example
                   6223: 
                   6224: When @code{foo} is defined using @code{my:} these steps occur:
                   6225: 
                   6226: @itemize @bullet
                   6227: @item
                   6228: @code{my:} is executed.
                   6229: @item
                   6230: The @code{:} within the definition (the one between @code{my:} and
                   6231: @code{lastxt}) is executed, and does just what it always does; it parses
                   6232: the input stream for a name, builds a dictionary header for the name
                   6233: @code{foo} and switches @code{state} from interpret to compile.
                   6234: @item
                   6235: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
                   6236: being defined -- @code{foo} -- onto the stack.
                   6237: @item
                   6238: The code that was produced by @code{postpone literal} is executed; this
                   6239: causes the value on the stack to be compiled as a literal in the code
                   6240: area of @code{foo}.
                   6241: @item
                   6242: The code @code{['] stats} compiles a literal into the definition of
                   6243: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6244: execution token for @code{stats} -- is layed down in the code area of
                   6245: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6246: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6247: in the code area is implementation-dependent. A threaded implementation
                   6248: might spit out the execution token directly whilst another
                   6249: implementation might spit out a native code sequence.}.
                   6250: @item
                   6251: At this point, the execution of @code{my:} is complete, and control
                   6252: returns to the text interpreter. The text interpreter is in compile
                   6253: state, so subsequent text @code{+ -} is compiled into the definition of
                   6254: @code{foo} and the @code{;} terminates the definition as always.
                   6255: @end itemize
                   6256: 
                   6257: You can use @code{see} to decompile a word that was defined using
                   6258: @code{my:} and see how it is different from a normal @code{:}
                   6259: definition. For example:
                   6260: 
                   6261: @example
                   6262: : bar + - ;  \ like foo but using : rather than my:
                   6263: see bar
                   6264: : bar
                   6265:   + - ;
                   6266: see foo
                   6267: : foo
                   6268:   107645672 stats + - ;
                   6269: 
                   6270: \ use ' stats . to show that 107645672 is the xt for stats
                   6271: @end example
                   6272: 
                   6273: You can use techniques like this to make new defining words in terms of
                   6274: @i{any} existing defining word.
1.1       anton    6275: 
                   6276: 
1.29      crook    6277: @cindex defining defining words
1.26      crook    6278: @cindex @code{CREATE} ... @code{DOES>}
                   6279: If you want the words defined with your defining words to behave
                   6280: differently from words defined with standard defining words, you can
                   6281: write your defining word like this:
1.1       anton    6282: 
                   6283: @example
1.26      crook    6284: : def-word ( "name" -- )
1.29      crook    6285:     CREATE @i{code1}
1.26      crook    6286: DOES> ( ... -- ... )
1.29      crook    6287:     @i{code2} ;
1.26      crook    6288: 
                   6289: def-word name
1.1       anton    6290: @end example
                   6291: 
1.29      crook    6292: @cindex child words
                   6293: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6294: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6295: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6296: is not executed at this time. The word @code{name} is sometimes called a
                   6297: @dfn{child} of @code{def-word}.
                   6298: 
                   6299: When you execute @code{name}, the address of the body of @code{name} is
                   6300: put on the data stack and @i{code2} is executed (the address of the body
                   6301: of @code{name} is the address @code{HERE} returns immediately after the
1.69      anton    6302: @code{CREATE}, i.e., the address a @code{create}d word returns by
                   6303: default).
                   6304: 
                   6305: @c anton:
                   6306: @c www.dictionary.com says:
                   6307: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
                   6308: @c several generations of absence, usually caused by the chance
                   6309: @c recombination of genes.  2.An individual or a part that exhibits
                   6310: @c atavism. Also called throwback.  3.The return of a trait or recurrence
                   6311: @c of previous behavior after a period of absence.
                   6312: @c
                   6313: @c Doesn't seem to fit.
1.29      crook    6314: 
1.69      anton    6315: @c @cindex atavism in child words
1.33      anton    6316: You can use @code{def-word} to define a set of child words that behave
1.69      anton    6317: similarly; they all have a common run-time behaviour determined by
                   6318: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
                   6319: body of the child word. The structure of the data is common to all
                   6320: children of @code{def-word}, but the data values are specific -- and
                   6321: private -- to each child word. When a child word is executed, the
                   6322: address of its private data area is passed as a parameter on TOS to be
                   6323: used and manipulated@footnote{It is legitimate both to read and write to
                   6324: this data area.} by @i{code2}.
1.29      crook    6325: 
                   6326: The two fragments of code that make up the defining words act (are
                   6327: executed) at two completely separate times:
1.1       anton    6328: 
1.29      crook    6329: @itemize @bullet
                   6330: @item
                   6331: At @i{define time}, the defining word executes @i{code1} to generate a
                   6332: child word
                   6333: @item
                   6334: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6335: is executed, using parameters (data) that are private and specific to
                   6336: the child word.
                   6337: @end itemize
                   6338: 
1.44      crook    6339: Another way of understanding the behaviour of @code{def-word} and
                   6340: @code{name} is to say that, if you make the following definitions:
1.33      anton    6341: @example
                   6342: : def-word1 ( "name" -- )
                   6343:     CREATE @i{code1} ;
                   6344: 
                   6345: : action1 ( ... -- ... )
                   6346:     @i{code2} ;
                   6347: 
                   6348: def-word1 name1
                   6349: @end example
                   6350: 
1.44      crook    6351: @noindent
                   6352: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6353: 
1.29      crook    6354: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6355: 
1.1       anton    6356: @example
1.29      crook    6357: : CONSTANT ( w "name" -- )
                   6358:     CREATE ,
1.26      crook    6359: DOES> ( -- w )
                   6360:     @@ ;
1.1       anton    6361: @end example
                   6362: 
1.29      crook    6363: @comment There is a beautiful description of how this works and what
                   6364: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6365: @comment commentary on the Counting Fruits problem.
                   6366: 
                   6367: When you create a constant with @code{5 CONSTANT five}, a set of
                   6368: define-time actions take place; first a new word @code{five} is created,
                   6369: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6370: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6371: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6372: no code of its own; it simply contains a data field and a pointer to the
                   6373: code that follows @code{DOES>} in its defining word. That makes words
                   6374: created in this way very compact.
                   6375: 
                   6376: The final example in this section is intended to remind you that space
                   6377: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6378: both read and written by a Standard program@footnote{Exercise: use this
                   6379: example as a starting point for your own implementation of @code{Value}
                   6380: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6381: @code{[']}.}:
                   6382: 
                   6383: @example
                   6384: : foo ( "name" -- )
                   6385:     CREATE -1 ,
                   6386: DOES> ( -- )
1.33      anton    6387:     @@ . ;
1.29      crook    6388: 
                   6389: foo first-word
                   6390: foo second-word
                   6391: 
                   6392: 123 ' first-word >BODY !
                   6393: @end example
                   6394: 
                   6395: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6396: have executed it to get the address of its data field. However, since it
                   6397: was defined to have @code{DOES>} actions, its execution semantics are to
                   6398: perform those @code{DOES>} actions. To get the address of its data field
                   6399: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6400: translate the xt into the address of the data field.  When you execute
                   6401: @code{first-word}, it will display @code{123}. When you execute
                   6402: @code{second-word} it will display @code{-1}.
1.26      crook    6403: 
                   6404: @cindex stack effect of @code{DOES>}-parts
                   6405: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6406: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6407: the stack effect of the defined words, not the stack effect of the
                   6408: following code (the following code expects the address of the body on
                   6409: the top of stack, which is not reflected in the stack comment). This is
                   6410: the convention that I use and recommend (it clashes a bit with using
                   6411: locals declarations for stack effect specification, though).
1.1       anton    6412: 
1.53      anton    6413: @menu
                   6414: * CREATE..DOES> applications::  
                   6415: * CREATE..DOES> details::       
1.63      anton    6416: * Advanced does> usage example::  
1.53      anton    6417: @end menu
                   6418: 
                   6419: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26      crook    6420: @subsubsection Applications of @code{CREATE..DOES>}
                   6421: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6422: 
1.26      crook    6423: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6424: 
1.26      crook    6425: @cindex factoring similar colon definitions
                   6426: When you see a sequence of code occurring several times, and you can
                   6427: identify a meaning, you will factor it out as a colon definition. When
                   6428: you see similar colon definitions, you can factor them using
                   6429: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6430: that look very similar:
1.1       anton    6431: @example
1.26      crook    6432: : ori, ( reg-target reg-source n -- )
                   6433:     0 asm-reg-reg-imm ;
                   6434: : andi, ( reg-target reg-source n -- )
                   6435:     1 asm-reg-reg-imm ;
1.1       anton    6436: @end example
                   6437: 
1.26      crook    6438: @noindent
                   6439: This could be factored with:
                   6440: @example
                   6441: : reg-reg-imm ( op-code -- )
                   6442:     CREATE ,
                   6443: DOES> ( reg-target reg-source n -- )
                   6444:     @@ asm-reg-reg-imm ;
                   6445: 
                   6446: 0 reg-reg-imm ori,
                   6447: 1 reg-reg-imm andi,
                   6448: @end example
1.1       anton    6449: 
1.26      crook    6450: @cindex currying
                   6451: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6452: supply a part of the parameters for a word (known as @dfn{currying} in
                   6453: the functional language community). E.g., @code{+} needs two
                   6454: parameters. Creating versions of @code{+} with one parameter fixed can
                   6455: be done like this:
1.1       anton    6456: @example
1.26      crook    6457: : curry+ ( n1 -- )
                   6458:     CREATE ,
                   6459: DOES> ( n2 -- n1+n2 )
                   6460:     @@ + ;
                   6461: 
                   6462:  3 curry+ 3+
                   6463: -2 curry+ 2-
1.1       anton    6464: @end example
                   6465: 
1.63      anton    6466: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6467: @subsubsection The gory details of @code{CREATE..DOES>}
                   6468: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6469: 
1.26      crook    6470: doc-does>
1.1       anton    6471: 
1.26      crook    6472: @cindex @code{DOES>} in a separate definition
                   6473: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6474: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6475: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6476: @example
                   6477: : does1 
                   6478: DOES> ( ... -- ... )
1.44      crook    6479:     ... ;
                   6480: 
                   6481: : does2
                   6482: DOES> ( ... -- ... )
                   6483:     ... ;
                   6484: 
                   6485: : def-word ( ... -- ... )
                   6486:     create ...
                   6487:     IF
                   6488:        does1
                   6489:     ELSE
                   6490:        does2
                   6491:     ENDIF ;
                   6492: @end example
                   6493: 
                   6494: In this example, the selection of whether to use @code{does1} or
1.69      anton    6495: @code{does2} is made at definition-time; at the time that the child word is
1.44      crook    6496: @code{CREATE}d.
                   6497: 
                   6498: @cindex @code{DOES>} in interpretation state
                   6499: In a standard program you can apply a @code{DOES>}-part only if the last
                   6500: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6501: will override the behaviour of the last word defined in any case. In a
                   6502: standard program, you can use @code{DOES>} only in a colon
                   6503: definition. In Gforth, you can also use it in interpretation state, in a
                   6504: kind of one-shot mode; for example:
                   6505: @example
                   6506: CREATE name ( ... -- ... )
                   6507:   @i{initialization}
                   6508: DOES>
                   6509:   @i{code} ;
                   6510: @end example
                   6511: 
                   6512: @noindent
                   6513: is equivalent to the standard:
                   6514: @example
                   6515: :noname
                   6516: DOES>
                   6517:     @i{code} ;
                   6518: CREATE name EXECUTE ( ... -- ... )
                   6519:     @i{initialization}
                   6520: @end example
                   6521: 
1.53      anton    6522: doc->body
                   6523: 
1.63      anton    6524: @node Advanced does> usage example,  , CREATE..DOES> details, User-defined Defining Words
                   6525: @subsubsection Advanced does> usage example
                   6526: 
                   6527: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
                   6528: for disassembling instructions, that follow a very repetetive scheme:
                   6529: 
                   6530: @example
                   6531: :noname @var{disasm-operands} s" @var{inst-name}" type ;
                   6532: @var{entry-num} cells @var{table} + !
                   6533: @end example
                   6534: 
                   6535: Of course, this inspires the idea to factor out the commonalities to
                   6536: allow a definition like
                   6537: 
                   6538: @example
                   6539: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
                   6540: @end example
                   6541: 
                   6542: The parameters @var{disasm-operands} and @var{table} are usually
1.69      anton    6543: correlated.  Moreover, before I wrote the disassembler, there already
                   6544: existed code that defines instructions like this:
1.63      anton    6545: 
                   6546: @example
                   6547: @var{entry-num} @var{inst-format} @var{inst-name}
                   6548: @end example
                   6549: 
                   6550: This code comes from the assembler and resides in
                   6551: @file{arch/mips/insts.fs}.
                   6552: 
                   6553: So I had to define the @var{inst-format} words that performed the scheme
                   6554: above when executed.  At first I chose to use run-time code-generation:
                   6555: 
                   6556: @example
                   6557: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
                   6558:   :noname Postpone @var{disasm-operands}
                   6559:   name Postpone sliteral Postpone type Postpone ;
                   6560:   swap cells @var{table} + ! ;
                   6561: @end example
                   6562: 
                   6563: Note that this supplies the other two parameters of the scheme above.
1.44      crook    6564: 
1.63      anton    6565: An alternative would have been to write this using
                   6566: @code{create}/@code{does>}:
                   6567: 
                   6568: @example
                   6569: : @var{inst-format} ( entry-num "name" -- )
                   6570:   here name string, ( entry-num c-addr ) \ parse and save "name"
                   6571:   noname create , ( entry-num )
                   6572:   lastxt swap cells @var{table} + !
                   6573: does> ( addr w -- )
                   6574:   \ disassemble instruction w at addr
                   6575:   @@ >r 
                   6576:   @var{disasm-operands}
                   6577:   r> count type ;
                   6578: @end example
                   6579: 
                   6580: Somehow the first solution is simpler, mainly because it's simpler to
                   6581: shift a string from definition-time to use-time with @code{sliteral}
                   6582: than with @code{string,} and friends.
                   6583: 
                   6584: I wrote a lot of words following this scheme and soon thought about
                   6585: factoring out the commonalities among them.  Note that this uses a
                   6586: two-level defining word, i.e., a word that defines ordinary defining
                   6587: words.
                   6588: 
                   6589: This time a solution involving @code{postpone} and friends seemed more
                   6590: difficult (try it as an exercise), so I decided to use a
                   6591: @code{create}/@code{does>} word; since I was already at it, I also used
                   6592: @code{create}/@code{does>} for the lower level (try using
                   6593: @code{postpone} etc. as an exercise), resulting in the following
                   6594: definition:
                   6595: 
                   6596: @example
                   6597: : define-format ( disasm-xt table-xt -- )
                   6598:     \ define an instruction format that uses disasm-xt for
                   6599:     \ disassembling and enters the defined instructions into table
                   6600:     \ table-xt
                   6601:     create 2,
                   6602: does> ( u "inst" -- )
                   6603:     \ defines an anonymous word for disassembling instruction inst,
                   6604:     \ and enters it as u-th entry into table-xt
                   6605:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
                   6606:     noname create 2,      \ define anonymous word
                   6607:     execute lastxt swap ! \ enter xt of defined word into table-xt
                   6608: does> ( addr w -- )
                   6609:     \ disassemble instruction w at addr
                   6610:     2@@ >r ( addr w disasm-xt R: c-addr )
                   6611:     execute ( R: c-addr ) \ disassemble operands
                   6612:     r> count type ; \ print name 
                   6613: @end example
                   6614: 
                   6615: Note that the tables here (in contrast to above) do the @code{cells +}
                   6616: by themselves (that's why you have to pass an xt).  This word is used in
                   6617: the following way:
                   6618: 
                   6619: @example
                   6620: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
                   6621: @end example
                   6622: 
1.71      anton    6623: As shown above, the defined instruction format is then used like this:
                   6624: 
                   6625: @example
                   6626: @var{entry-num} @var{inst-format} @var{inst-name}
                   6627: @end example
                   6628: 
1.63      anton    6629: In terms of currying, this kind of two-level defining word provides the
                   6630: parameters in three stages: first @var{disasm-operands} and @var{table},
                   6631: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
                   6632: the instruction to be disassembled.  
                   6633: 
                   6634: Of course this did not quite fit all the instruction format names used
                   6635: in @file{insts.fs}, so I had to define a few wrappers that conditioned
                   6636: the parameters into the right form.
                   6637: 
                   6638: If you have trouble following this section, don't worry.  First, this is
                   6639: involved and takes time (and probably some playing around) to
                   6640: understand; second, this is the first two-level
                   6641: @code{create}/@code{does>} word I have written in seventeen years of
                   6642: Forth; and if I did not have @file{insts.fs} to start with, I may well
                   6643: have elected to use just a one-level defining word (with some repeating
                   6644: of parameters when using the defining word). So it is not necessary to
                   6645: understand this, but it may improve your understanding of Forth.
1.44      crook    6646: 
                   6647: 
                   6648: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
                   6649: @subsection Deferred words
                   6650: @cindex deferred words
                   6651: 
                   6652: The defining word @code{Defer} allows you to define a word by name
                   6653: without defining its behaviour; the definition of its behaviour is
                   6654: deferred. Here are two situation where this can be useful:
                   6655: 
                   6656: @itemize @bullet
                   6657: @item
                   6658: Where you want to allow the behaviour of a word to be altered later, and
                   6659: for all precompiled references to the word to change when its behaviour
                   6660: is changed.
                   6661: @item
                   6662: For mutual recursion; @xref{Calls and returns}.
                   6663: @end itemize
                   6664: 
                   6665: In the following example, @code{foo} always invokes the version of
                   6666: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6667: always invokes the version that prints ``@code{Hello}''. There is no way
                   6668: of getting @code{foo} to use the later version without re-ordering the
                   6669: source code and recompiling it.
                   6670: 
                   6671: @example
                   6672: : greet ." Good morning" ;
                   6673: : foo ... greet ... ;
                   6674: : greet ." Hello" ;
                   6675: : bar ... greet ... ;
                   6676: @end example
                   6677: 
                   6678: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6679: word. The behaviour of a @code{Defer}red word can be defined and
                   6680: redefined at any time by using @code{IS} to associate the xt of a
                   6681: previously-defined word with it. The previous example becomes:
                   6682: 
                   6683: @example
1.69      anton    6684: Defer greet ( -- )
1.44      crook    6685: : foo ... greet ... ;
                   6686: : bar ... greet ... ;
1.69      anton    6687: : greet1 ( -- ) ." Good morning" ;
                   6688: : greet2 ( -- ) ." Hello" ;
1.44      crook    6689: ' greet2 <IS> greet  \ make greet behave like greet2
                   6690: @end example
                   6691: 
1.69      anton    6692: @progstyle
                   6693: You should write a stack comment for every deferred word, and put only
                   6694: XTs into deferred words that conform to this stack effect.  Otherwise
                   6695: it's too difficult to use the deferred word.
                   6696: 
1.44      crook    6697: A deferred word can be used to improve the statistics-gathering example
                   6698: from @ref{User-defined Defining Words}; rather than edit the
                   6699: application's source code to change every @code{:} to a @code{my:}, do
                   6700: this:
                   6701: 
                   6702: @example
                   6703: : real: : ;     \ retain access to the original
                   6704: defer :         \ redefine as a deferred word
1.69      anton    6705: ' my: <IS> :      \ use special version of :
1.44      crook    6706: \
                   6707: \ load application here
                   6708: \
1.69      anton    6709: ' real: <IS> :    \ go back to the original
1.44      crook    6710: @end example
                   6711: 
                   6712: 
                   6713: One thing to note is that @code{<IS>} consumes its name when it is
                   6714: executed.  If you want to specify the name at compile time, use
                   6715: @code{[IS]}:
                   6716: 
                   6717: @example
                   6718: : set-greet ( xt -- )
                   6719:   [IS] greet ;
                   6720: 
                   6721: ' greet1 set-greet
                   6722: @end example
                   6723: 
1.69      anton    6724: A deferred word can only inherit execution semantics from the xt
                   6725: (because that is all that an xt can represent -- for more discussion of
                   6726: this @pxref{Tokens for Words}); by default it will have default
                   6727: interpretation and compilation semantics deriving from this execution
                   6728: semantics.  However, you can change the interpretation and compilation
                   6729: semantics of the deferred word in the usual ways:
1.44      crook    6730: 
                   6731: @example
                   6732: : bar .... ; compile-only
                   6733: Defer fred immediate
                   6734: Defer jim
                   6735: 
                   6736: ' bar <IS> jim  \ jim has default semantics
                   6737: ' bar <IS> fred \ fred is immediate
                   6738: @end example
                   6739: 
                   6740: doc-defer
                   6741: doc-<is>
                   6742: doc-[is]
                   6743: doc-is
                   6744: @comment TODO document these: what's defers [is]
                   6745: doc-what's
                   6746: doc-defers
                   6747: 
                   6748: @c Use @code{words-deferred} to see a list of deferred words.
                   6749: 
                   6750: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
                   6751: are provided in @file{compat/defer.fs}.
                   6752: 
                   6753: 
1.69      anton    6754: @node Aliases,  , Deferred words, Defining Words
1.44      crook    6755: @subsection Aliases
                   6756: @cindex aliases
1.1       anton    6757: 
1.44      crook    6758: The defining word @code{Alias} allows you to define a word by name that
                   6759: has the same behaviour as some other word. Here are two situation where
                   6760: this can be useful:
1.1       anton    6761: 
1.44      crook    6762: @itemize @bullet
                   6763: @item
                   6764: When you want access to a word's definition from a different word list
                   6765: (for an example of this, see the definition of the @code{Root} word list
                   6766: in the Gforth source).
                   6767: @item
                   6768: When you want to create a synonym; a definition that can be known by
                   6769: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   6770: aliases).
                   6771: @end itemize
1.1       anton    6772: 
1.69      anton    6773: Like deferred words, an alias has default compilation and interpretation
                   6774: semantics at the beginning (not the modifications of the other word),
                   6775: but you can change them in the usual ways (@code{immediate},
                   6776: @code{compile-only}). For example:
1.1       anton    6777: 
                   6778: @example
1.44      crook    6779: : foo ... ; immediate
                   6780: 
                   6781: ' foo Alias bar \ bar is not an immediate word
                   6782: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    6783: @end example
                   6784: 
1.44      crook    6785: Words that are aliases have the same xt, different headers in the
                   6786: dictionary, and consequently different name tokens (@pxref{Tokens for
                   6787: Words}) and possibly different immediate flags.  An alias can only have
                   6788: default or immediate compilation semantics; you can define aliases for
                   6789: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    6790: 
1.44      crook    6791: doc-alias
1.1       anton    6792: 
                   6793: 
1.47      crook    6794: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   6795: @section Interpretation and Compilation Semantics
1.26      crook    6796: @cindex semantics, interpretation and compilation
1.1       anton    6797: 
1.71      anton    6798: @c !! state and ' are used without explanation
                   6799: @c example for immediate/compile-only? or is the tutorial enough
                   6800: 
1.26      crook    6801: @cindex interpretation semantics
1.71      anton    6802: The @dfn{interpretation semantics} of a (named) word are what the text
1.26      crook    6803: interpreter does when it encounters the word in interpret state. It also
                   6804: appears in some other contexts, e.g., the execution token returned by
1.71      anton    6805: @code{' @i{word}} identifies the interpretation semantics of @i{word}
                   6806: (in other words, @code{' @i{word} execute} is equivalent to
1.29      crook    6807: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    6808: 
1.26      crook    6809: @cindex compilation semantics
1.71      anton    6810: The @dfn{compilation semantics} of a (named) word are what the text
                   6811: interpreter does when it encounters the word in compile state. It also
                   6812: appears in other contexts, e.g, @code{POSTPONE @i{word}}
                   6813: compiles@footnote{In standard terminology, ``appends to the current
                   6814: definition''.} the compilation semantics of @i{word}.
1.1       anton    6815: 
1.26      crook    6816: @cindex execution semantics
                   6817: The standard also talks about @dfn{execution semantics}. They are used
                   6818: only for defining the interpretation and compilation semantics of many
                   6819: words. By default, the interpretation semantics of a word are to
                   6820: @code{execute} its execution semantics, and the compilation semantics of
                   6821: a word are to @code{compile,} its execution semantics.@footnote{In
                   6822: standard terminology: The default interpretation semantics are its
                   6823: execution semantics; the default compilation semantics are to append its
                   6824: execution semantics to the execution semantics of the current
                   6825: definition.}
                   6826: 
1.71      anton    6827: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
                   6828: the text interpreter, ticked, or @code{postpone}d, so they have no
                   6829: interpretation or compilation semantics.  Their behaviour is represented
                   6830: by their XT (@pxref{Tokens for Words}), and we call it execution
                   6831: semantics, too.
                   6832: 
1.26      crook    6833: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   6834: 
                   6835: @cindex immediate words
                   6836: @cindex compile-only words
                   6837: You can change the semantics of the most-recently defined word:
                   6838: 
1.44      crook    6839: 
1.26      crook    6840: doc-immediate
                   6841: doc-compile-only
                   6842: doc-restrict
                   6843: 
1.44      crook    6844: 
1.26      crook    6845: Note that ticking (@code{'}) a compile-only word gives an error
                   6846: (``Interpreting a compile-only word'').
1.1       anton    6847: 
1.47      crook    6848: @menu
1.67      anton    6849: * Combined words::              
1.47      crook    6850: @end menu
1.44      crook    6851: 
1.71      anton    6852: 
1.48      anton    6853: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    6854: @subsection Combined Words
                   6855: @cindex combined words
                   6856: 
                   6857: Gforth allows you to define @dfn{combined words} -- words that have an
                   6858: arbitrary combination of interpretation and compilation semantics.
                   6859: 
1.26      crook    6860: doc-interpret/compile:
1.1       anton    6861: 
1.26      crook    6862: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   6863: recommend that you do not define such words, as cute as they may be:
                   6864: they make it hard to get at both parts of the word in some contexts.
                   6865: E.g., assume you want to get an execution token for the compilation
                   6866: part. Instead, define two words, one that embodies the interpretation
                   6867: part, and one that embodies the compilation part.  Once you have done
                   6868: that, you can define a combined word with @code{interpret/compile:} for
                   6869: the convenience of your users.
1.1       anton    6870: 
1.26      crook    6871: You might try to use this feature to provide an optimizing
                   6872: implementation of the default compilation semantics of a word. For
                   6873: example, by defining:
1.1       anton    6874: @example
1.26      crook    6875: :noname
                   6876:    foo bar ;
                   6877: :noname
                   6878:    POSTPONE foo POSTPONE bar ;
1.29      crook    6879: interpret/compile: opti-foobar
1.1       anton    6880: @end example
1.26      crook    6881: 
1.23      crook    6882: @noindent
1.26      crook    6883: as an optimizing version of:
                   6884: 
1.1       anton    6885: @example
1.26      crook    6886: : foobar
                   6887:     foo bar ;
1.1       anton    6888: @end example
                   6889: 
1.26      crook    6890: Unfortunately, this does not work correctly with @code{[compile]},
                   6891: because @code{[compile]} assumes that the compilation semantics of all
                   6892: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    6893: opti-foobar} would compile compilation semantics, whereas
                   6894: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    6895: 
1.26      crook    6896: @cindex state-smart words (are a bad idea)
1.29      crook    6897: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    6898: by @code{interpret/compile:} (words are state-smart if they check
                   6899: @code{STATE} during execution). E.g., they would try to code
                   6900: @code{foobar} like this:
1.1       anton    6901: 
1.26      crook    6902: @example
                   6903: : foobar
                   6904:   STATE @@
                   6905:   IF ( compilation state )
                   6906:     POSTPONE foo POSTPONE bar
                   6907:   ELSE
                   6908:     foo bar
                   6909:   ENDIF ; immediate
                   6910: @end example
1.1       anton    6911: 
1.26      crook    6912: Although this works if @code{foobar} is only processed by the text
                   6913: interpreter, it does not work in other contexts (like @code{'} or
                   6914: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   6915: for a state-smart word, not for the interpretation semantics of the
                   6916: original @code{foobar}; when you execute this execution token (directly
                   6917: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   6918: state, the result will not be what you expected (i.e., it will not
                   6919: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   6920: write them@footnote{For a more detailed discussion of this topic, see
1.66      anton    6921: M. Anton Ertl,
                   6922: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
                   6923: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1       anton    6924: 
1.26      crook    6925: @cindex defining words with arbitrary semantics combinations
                   6926: It is also possible to write defining words that define words with
                   6927: arbitrary combinations of interpretation and compilation semantics. In
                   6928: general, they look like this:
1.1       anton    6929: 
1.26      crook    6930: @example
                   6931: : def-word
                   6932:     create-interpret/compile
1.29      crook    6933:     @i{code1}
1.26      crook    6934: interpretation>
1.29      crook    6935:     @i{code2}
1.26      crook    6936: <interpretation
                   6937: compilation>
1.29      crook    6938:     @i{code3}
1.26      crook    6939: <compilation ;
                   6940: @end example
1.1       anton    6941: 
1.29      crook    6942: For a @i{word} defined with @code{def-word}, the interpretation
                   6943: semantics are to push the address of the body of @i{word} and perform
                   6944: @i{code2}, and the compilation semantics are to push the address of
                   6945: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    6946: can also be defined like this (except that the defined constants don't
                   6947: behave correctly when @code{[compile]}d):
1.1       anton    6948: 
1.26      crook    6949: @example
                   6950: : constant ( n "name" -- )
                   6951:     create-interpret/compile
                   6952:     ,
                   6953: interpretation> ( -- n )
                   6954:     @@
                   6955: <interpretation
                   6956: compilation> ( compilation. -- ; run-time. -- n )
                   6957:     @@ postpone literal
                   6958: <compilation ;
                   6959: @end example
1.1       anton    6960: 
1.44      crook    6961: 
1.26      crook    6962: doc-create-interpret/compile
                   6963: doc-interpretation>
                   6964: doc-<interpretation
                   6965: doc-compilation>
                   6966: doc-<compilation
1.1       anton    6967: 
1.44      crook    6968: 
1.29      crook    6969: Words defined with @code{interpret/compile:} and
1.26      crook    6970: @code{create-interpret/compile} have an extended header structure that
                   6971: differs from other words; however, unless you try to access them with
                   6972: plain address arithmetic, you should not notice this. Words for
                   6973: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    6974: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   6975: with @code{create-interpret/compile}.
1.1       anton    6976: 
1.44      crook    6977: 
1.47      crook    6978: @c -------------------------------------------------------------
1.81    ! anton    6979: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47      crook    6980: @section Tokens for Words
                   6981: @cindex tokens for words
                   6982: 
                   6983: This section describes the creation and use of tokens that represent
                   6984: words.
                   6985: 
1.71      anton    6986: @menu
                   6987: * Execution token::             represents execution/interpretation semantics
                   6988: * Compilation token::           represents compilation semantics
                   6989: * Name token::                  represents named words
                   6990: @end menu
1.47      crook    6991: 
1.71      anton    6992: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
                   6993: @subsection Execution token
1.47      crook    6994: 
                   6995: @cindex xt
                   6996: @cindex execution token
1.71      anton    6997: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
                   6998: You can use @code{execute} to invoke this behaviour.
1.47      crook    6999: 
1.71      anton    7000: @cindex tick (')
                   7001: You can use @code{'} to get an execution token that represents the
                   7002: interpretation semantics of a named word:
1.47      crook    7003: 
                   7004: @example
1.71      anton    7005: 5 ' .
                   7006: execute
                   7007: @end example
1.47      crook    7008: 
1.71      anton    7009: doc-'
                   7010: 
                   7011: @code{'} parses at run-time; there is also a word @code{[']} that parses
                   7012: when it is compiled, and compiles the resulting XT:
                   7013: 
                   7014: @example
                   7015: : foo ['] . execute ;
                   7016: 5 foo
                   7017: : bar ' execute ; \ by contrast,
                   7018: 5 bar .           \ ' parses "." when bar executes
                   7019: @end example
                   7020: 
                   7021: doc-[']
                   7022: 
                   7023: If you want the execution token of @i{word}, write @code{['] @i{word}}
                   7024: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
                   7025: @code{'} and @code{[']} behave somewhat unusually by complaining about
                   7026: compile-only words (because these words have no interpretation
                   7027: semantics).  You might get what you want by using @code{COMP' @i{word}
                   7028: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
                   7029: token}).
                   7030: 
                   7031: Another way to get an XT is @code{:noname} or @code{lastxt}
                   7032: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
                   7033: for the only behaviour the word has (the execution semantics).  For
                   7034: named words, @code{lastxt} produces an XT for the same behaviour it
                   7035: would produce if the word was defined anonymously.
                   7036: 
                   7037: @example
                   7038: :noname ." hello" ;
                   7039: execute
1.47      crook    7040: @end example
                   7041: 
1.71      anton    7042: An XT occupies one cell and can be manipulated like any other cell.
                   7043: 
1.47      crook    7044: @cindex code field address
                   7045: @cindex CFA
1.71      anton    7046: In ANS Forth the XT is just an abstract data type (i.e., defined by the
                   7047: operations that produce or consume it).  For old hands: In Gforth, the
                   7048: XT is implemented as a code field address (CFA).
                   7049: 
                   7050: @c !! discuss "compile," some more (or in Macros).
                   7051: 
                   7052: doc-execute
                   7053: doc-perform
                   7054: doc-compile,
                   7055: 
                   7056: @node Compilation token, Name token, Execution token, Tokens for Words
                   7057: @subsection Compilation token
1.47      crook    7058: 
                   7059: @cindex compilation token
1.71      anton    7060: @cindex CT (compilation token)
                   7061: Gforth represents the compilation semantics of a named word by a
1.47      crook    7062: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   7063: @i{xt} is an execution token. The compilation semantics represented by
                   7064: the compilation token can be performed with @code{execute}, which
                   7065: consumes the whole compilation token, with an additional stack effect
                   7066: determined by the represented compilation semantics.
                   7067: 
                   7068: At present, the @i{w} part of a compilation token is an execution token,
                   7069: and the @i{xt} part represents either @code{execute} or
                   7070: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   7071: word. If the word has default compilation semantics, the @i{xt} will
                   7072: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   7073: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   7074: knowledge, unless necessary; future versions of Gforth may introduce
                   7075: unusual compilation tokens (e.g., a compilation token that represents
                   7076: the compilation semantics of a literal).
                   7077: 
1.71      anton    7078: You can perform the compilation semantics represented by the compilation
                   7079: token with @code{execute}.  You can compile the compilation semantics
                   7080: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
                   7081: equivalent to @code{postpone @i{word}}.
                   7082: 
                   7083: doc-[comp']
                   7084: doc-comp'
                   7085: doc-postpone,
                   7086: 
                   7087: @node Name token,  , Compilation token, Tokens for Words
                   7088: @subsection Name token
1.47      crook    7089: 
                   7090: @cindex name token
                   7091: @cindex name field address
                   7092: @cindex NFA
1.71      anton    7093: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
1.47      crook    7094: Gforth, the abstract data type @emph{name token} is implemented as a
                   7095: name field address (NFA).
                   7096: 
                   7097: doc-find-name
                   7098: doc-name>int
                   7099: doc-name?int
                   7100: doc-name>comp
                   7101: doc-name>string
                   7102: 
1.81    ! anton    7103: @c ----------------------------------------------------------
        !          7104: @node Compiling words, The Text Interpreter, Tokens for Words, Words
        !          7105: @section Compiling words
        !          7106: @cindex compiling words
        !          7107: @cindex macros
        !          7108: 
        !          7109: In contrast to most other languages, Forth has no strict boundary
        !          7110: between compilation and run-time.  
        !          7111: 
        !          7112: doc-postpone
        !          7113: 
        !          7114: @comment TODO -- expand glossary text for POSTPONE
        !          7115: 
        !          7116: doc-literal
        !          7117: doc-]L
        !          7118: doc-2literal
        !          7119: doc-fliteral
        !          7120: doc-[
        !          7121: doc-]
        !          7122: 
        !          7123: 
        !          7124: 
1.47      crook    7125: 
1.26      crook    7126: @c ----------------------------------------------------------
1.81    ! anton    7127: @node The Text Interpreter, Word Lists, Compiling words, Words
1.26      crook    7128: @section  The Text Interpreter
                   7129: @cindex interpreter - outer
                   7130: @cindex text interpreter
                   7131: @cindex outer interpreter
1.1       anton    7132: 
1.34      anton    7133: @c Should we really describe all these ugly details?  IMO the text
                   7134: @c interpreter should be much cleaner, but that may not be possible within
                   7135: @c ANS Forth. - anton
1.44      crook    7136: @c nac-> I wanted to explain how it works to show how you can exploit
                   7137: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   7138: @c some of these gory details was very helpful to me. None of the textbooks
                   7139: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   7140: @c seems to positively avoid going into too much detail for some of
                   7141: @c the internals.
1.34      anton    7142: 
1.71      anton    7143: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
                   7144: @c it is; for the ugly details, I would prefer another place.  I wonder
                   7145: @c whether we should have a chapter before "Words" that describes some
                   7146: @c basic concepts referred to in words, and a chapter after "Words" that
                   7147: @c describes implementation details.
                   7148: 
1.29      crook    7149: The text interpreter@footnote{This is an expanded version of the
                   7150: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    7151: that processes input from the current input device. It is also called
                   7152: the outer interpreter, in contrast to the inner interpreter
                   7153: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   7154: implementations.
1.27      crook    7155: 
1.29      crook    7156: @cindex interpret state
                   7157: @cindex compile state
                   7158: The text interpreter operates in one of two states: @dfn{interpret
                   7159: state} and @dfn{compile state}. The current state is defined by the
1.71      anton    7160: aptly-named variable @code{state}.
1.29      crook    7161: 
                   7162: This section starts by describing how the text interpreter behaves when
                   7163: it is in interpret state, processing input from the user input device --
                   7164: the keyboard. This is the mode that a Forth system is in after it starts
                   7165: up.
                   7166: 
                   7167: @cindex input buffer
                   7168: @cindex terminal input buffer
                   7169: The text interpreter works from an area of memory called the @dfn{input
                   7170: buffer}@footnote{When the text interpreter is processing input from the
                   7171: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   7172: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   7173: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    7174: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    7175: leading spaces (called @dfn{delimiters}) then parses a string (a
                   7176: sequence of non-space characters) until it reaches either a space
                   7177: character or the end of the buffer. Having parsed a string, it makes two
                   7178: attempts to process it:
1.27      crook    7179: 
1.29      crook    7180: @cindex dictionary
1.27      crook    7181: @itemize @bullet
                   7182: @item
1.29      crook    7183: It looks for the string in a @dfn{dictionary} of definitions. If the
                   7184: string is found, the string names a @dfn{definition} (also known as a
                   7185: @dfn{word}) and the dictionary search returns information that allows
                   7186: the text interpreter to perform the word's @dfn{interpretation
                   7187: semantics}. In most cases, this simply means that the word will be
                   7188: executed.
1.27      crook    7189: @item
                   7190: If the string is not found in the dictionary, the text interpreter
1.29      crook    7191: attempts to treat it as a number, using the rules described in
                   7192: @ref{Number Conversion}. If the string represents a legal number in the
                   7193: current radix, the number is pushed onto a parameter stack (the data
                   7194: stack for integers, the floating-point stack for floating-point
                   7195: numbers).
                   7196: @end itemize
                   7197: 
                   7198: If both attempts fail, or if the word is found in the dictionary but has
                   7199: no interpretation semantics@footnote{This happens if the word was
                   7200: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   7201: remainder of the input buffer, issues an error message and waits for
                   7202: more input. If one of the attempts succeeds, the text interpreter
                   7203: repeats the parsing process until the whole of the input buffer has been
                   7204: processed, at which point it prints the status message ``@code{ ok}''
                   7205: and waits for more input.
                   7206: 
1.71      anton    7207: @c anton: this should be in the input stream subsection (or below it)
                   7208: 
1.29      crook    7209: @cindex parse area
                   7210: The text interpreter keeps track of its position in the input buffer by
                   7211: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   7212: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   7213: of the input buffer. The region from offset @code{>IN @@} to the end of
                   7214: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   7215: the text interpreter processes the contents of the input buffer by
                   7216: parsing strings from the parse area until the parse area is empty.}.
                   7217: This example shows how @code{>IN} changes as the text interpreter parses
                   7218: the input buffer:
                   7219: 
                   7220: @example
                   7221: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   7222:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   7223: 
                   7224: 1 2 3 remaining + remaining . 
                   7225: 
                   7226: : foo 1 2 3 remaining SWAP remaining ;
                   7227: @end example
                   7228: 
                   7229: @noindent
                   7230: The result is:
                   7231: 
                   7232: @example
                   7233: ->+ remaining .<-
                   7234: ->.<-5  ok
                   7235: 
                   7236: ->SWAP remaining ;-<
                   7237: ->;<-  ok
                   7238: @end example
                   7239: 
                   7240: @cindex parsing words
                   7241: The value of @code{>IN} can also be modified by a word in the input
                   7242: buffer that is executed by the text interpreter.  This means that a word
                   7243: can ``trick'' the text interpreter into either skipping a section of the
                   7244: input buffer@footnote{This is how parsing words work.} or into parsing a
                   7245: section twice. For example:
1.27      crook    7246: 
1.29      crook    7247: @example
1.71      anton    7248: : lat ." <<foo>>" ;
                   7249: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29      crook    7250: @end example
                   7251: 
                   7252: @noindent
                   7253: When @code{flat} is executed, this output is produced@footnote{Exercise
                   7254: for the reader: what would happen if the @code{3} were replaced with
                   7255: @code{4}?}:
                   7256: 
                   7257: @example
1.71      anton    7258: <<bar>><<foo>>
1.29      crook    7259: @end example
                   7260: 
1.71      anton    7261: This technique can be used to work around some of the interoperability
                   7262: problems of parsing words.  Of course, it's better to avoid parsing
                   7263: words where possible.
                   7264: 
1.29      crook    7265: @noindent
                   7266: Two important notes about the behaviour of the text interpreter:
1.27      crook    7267: 
                   7268: @itemize @bullet
                   7269: @item
                   7270: It processes each input string to completion before parsing additional
1.29      crook    7271: characters from the input buffer.
                   7272: @item
                   7273: It treats the input buffer as a read-only region (and so must your code).
                   7274: @end itemize
                   7275: 
                   7276: @noindent
                   7277: When the text interpreter is in compile state, its behaviour changes in
                   7278: these ways:
                   7279: 
                   7280: @itemize @bullet
                   7281: @item
                   7282: If a parsed string is found in the dictionary, the text interpreter will
                   7283: perform the word's @dfn{compilation semantics}. In most cases, this
                   7284: simply means that the execution semantics of the word will be appended
                   7285: to the current definition.
1.27      crook    7286: @item
1.29      crook    7287: When a number is encountered, it is compiled into the current definition
                   7288: (as a literal) rather than being pushed onto a parameter stack.
                   7289: @item
                   7290: If an error occurs, @code{state} is modified to put the text interpreter
                   7291: back into interpret state.
                   7292: @item
                   7293: Each time a line is entered from the keyboard, Gforth prints
                   7294: ``@code{ compiled}'' rather than `` @code{ok}''.
                   7295: @end itemize
                   7296: 
                   7297: @cindex text interpreter - input sources
                   7298: When the text interpreter is using an input device other than the
                   7299: keyboard, its behaviour changes in these ways:
                   7300: 
                   7301: @itemize @bullet
                   7302: @item
                   7303: When the parse area is empty, the text interpreter attempts to refill
                   7304: the input buffer from the input source. When the input source is
1.71      anton    7305: exhausted, the input source is set back to the previous input source.
1.29      crook    7306: @item
                   7307: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7308: time the parse area is emptied.
                   7309: @item
                   7310: If an error occurs, the input source is set back to the user input
                   7311: device.
1.27      crook    7312: @end itemize
1.21      crook    7313: 
1.49      anton    7314: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7315: 
1.26      crook    7316: doc->in
1.27      crook    7317: doc-source
                   7318: 
1.26      crook    7319: doc-tib
                   7320: doc-#tib
1.1       anton    7321: 
1.44      crook    7322: 
1.26      crook    7323: @menu
1.67      anton    7324: * Input Sources::               
                   7325: * Number Conversion::           
                   7326: * Interpret/Compile states::    
                   7327: * Literals::                    
                   7328: * Interpreter Directives::      
1.26      crook    7329: @end menu
1.1       anton    7330: 
1.29      crook    7331: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7332: @subsection Input Sources
                   7333: @cindex input sources
                   7334: @cindex text interpreter - input sources
                   7335: 
1.44      crook    7336: By default, the text interpreter processes input from the user input
1.29      crook    7337: device (the keyboard) when Forth starts up. The text interpreter can
                   7338: process input from any of these sources:
                   7339: 
                   7340: @itemize @bullet
                   7341: @item
                   7342: The user input device -- the keyboard.
                   7343: @item
                   7344: A file, using the words described in @ref{Forth source files}.
                   7345: @item
                   7346: A block, using the words described in @ref{Blocks}.
                   7347: @item
                   7348: A text string, using @code{evaluate}.
                   7349: @end itemize
                   7350: 
                   7351: A program can identify the current input device from the values of
                   7352: @code{source-id} and @code{blk}.
                   7353: 
1.44      crook    7354: 
1.29      crook    7355: doc-source-id
                   7356: doc-blk
                   7357: 
                   7358: doc-save-input
                   7359: doc-restore-input
                   7360: 
                   7361: doc-evaluate
1.1       anton    7362: 
1.29      crook    7363: 
1.44      crook    7364: 
1.29      crook    7365: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7366: @subsection Number Conversion
                   7367: @cindex number conversion
                   7368: @cindex double-cell numbers, input format
                   7369: @cindex input format for double-cell numbers
                   7370: @cindex single-cell numbers, input format
                   7371: @cindex input format for single-cell numbers
                   7372: @cindex floating-point numbers, input format
                   7373: @cindex input format for floating-point numbers
1.1       anton    7374: 
1.29      crook    7375: This section describes the rules that the text interpreter uses when it
                   7376: tries to convert a string into a number.
1.1       anton    7377: 
1.26      crook    7378: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7379: number base@footnote{For example, 0-9 when the number base is decimal or
                   7380: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7381: 
1.26      crook    7382: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7383: 
1.29      crook    7384: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7385: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7386: 
1.26      crook    7387: Let * represent any number of instances of the previous character
                   7388: (including none).
1.1       anton    7389: 
1.26      crook    7390: Let any other character represent itself.
1.1       anton    7391: 
1.29      crook    7392: @noindent
1.26      crook    7393: Now, the conversion rules are:
1.21      crook    7394: 
1.26      crook    7395: @itemize @bullet
                   7396: @item
                   7397: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7398: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7399: @item
                   7400: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7401: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7402: arithmetic. Examples are -45 -5681 -0
                   7403: @item
                   7404: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7405: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7406: (all three of these represent the same number).
1.26      crook    7407: @item
                   7408: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7409: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7410: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7411: -34.65 (all three of these represent the same number).
1.26      crook    7412: @item
1.29      crook    7413: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7414: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7415: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7416: number) +12.E-4
1.26      crook    7417: @end itemize
1.1       anton    7418: 
1.26      crook    7419: By default, the number base used for integer number conversion is given
1.35      anton    7420: by the contents of the variable @code{base}.  Note that a lot of
                   7421: confusion can result from unexpected values of @code{base}.  If you
                   7422: change @code{base} anywhere, make sure to save the old value and restore
                   7423: it afterwards.  In general I recommend keeping @code{base} decimal, and
                   7424: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7425: 
1.29      crook    7426: doc-dpl
1.26      crook    7427: doc-base
                   7428: doc-hex
                   7429: doc-decimal
1.1       anton    7430: 
1.44      crook    7431: 
1.26      crook    7432: @cindex '-prefix for character strings
                   7433: @cindex &-prefix for decimal numbers
                   7434: @cindex %-prefix for binary numbers
                   7435: @cindex $-prefix for hexadecimal numbers
1.35      anton    7436: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7437: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7438: implementing @code{$} etc. as parsing words that process the subsequent
                   7439: number in the input stream and push it onto the stack. For example, see
                   7440: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7441: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7442: is required between the prefix and the number.} before the first digit
                   7443: of an (integer) number. Four prefixes are supported:
1.1       anton    7444: 
1.26      crook    7445: @itemize @bullet
                   7446: @item
1.35      anton    7447: @code{&} -- decimal
1.26      crook    7448: @item
1.35      anton    7449: @code{%} -- binary
1.26      crook    7450: @item
1.35      anton    7451: @code{$} -- hexadecimal
1.26      crook    7452: @item
1.35      anton    7453: @code{'} -- base @code{max-char+1}
1.26      crook    7454: @end itemize
1.1       anton    7455: 
1.26      crook    7456: Here are some examples, with the equivalent decimal number shown after
                   7457: in braces:
1.1       anton    7458: 
1.26      crook    7459: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
                   7460: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
                   7461: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
                   7462: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    7463: 
1.26      crook    7464: @cindex number conversion - traps for the unwary
1.29      crook    7465: @noindent
1.26      crook    7466: Number conversion has a number of traps for the unwary:
1.1       anton    7467: 
1.26      crook    7468: @itemize @bullet
                   7469: @item
                   7470: You cannot determine the current number base using the code sequence
1.35      anton    7471: @code{base @@ .} -- the number base is always 10 in the current number
                   7472: base. Instead, use something like @code{base @@ dec.}
1.26      crook    7473: @item
                   7474: If the number base is set to a value greater than 14 (for example,
                   7475: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   7476: it to be intepreted as either a single-precision integer or a
                   7477: floating-point number (Gforth treats it as an integer). The ambiguity
                   7478: can be resolved by explicitly stating the sign of the mantissa and/or
                   7479: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   7480: ambiguity arises; either representation will be treated as a
                   7481: floating-point number.
                   7482: @item
1.29      crook    7483: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    7484: It is used to specify file types.
                   7485: @item
1.72      anton    7486: ANS Forth requires the @code{.} of a double-precision number to be the
                   7487: final character in the string.  Gforth allows the @code{.} to be
                   7488: anywhere after the first digit.
1.26      crook    7489: @item
                   7490: The number conversion process does not check for overflow.
                   7491: @item
1.72      anton    7492: In an ANS Forth program @code{base} is required to be decimal when
                   7493: converting floating-point numbers.  In Gforth, number conversion to
                   7494: floating-point numbers always uses base &10, irrespective of the value
                   7495: of @code{base}.
1.26      crook    7496: @end itemize
1.1       anton    7497: 
1.49      anton    7498: You can read numbers into your programs with the words described in
                   7499: @ref{Input}.
1.1       anton    7500: 
1.26      crook    7501: @node Interpret/Compile states, Literals, Number Conversion, The Text Interpreter
                   7502: @subsection Interpret/Compile states
                   7503: @cindex Interpret/Compile states
1.1       anton    7504: 
1.29      crook    7505: A standard program is not permitted to change @code{state}
                   7506: explicitly. However, it can change @code{state} implicitly, using the
                   7507: words @code{[} and @code{]}. When @code{[} is executed it switches
                   7508: @code{state} to interpret state, and therefore the text interpreter
                   7509: starts interpreting. When @code{]} is executed it switches @code{state}
                   7510: to compile state and therefore the text interpreter starts
1.44      crook    7511: compiling. The most common usage for these words is for switching into
                   7512: interpret state and back from within a colon definition; this technique
1.49      anton    7513: can be used to compile a literal (for an example, @pxref{Literals}) or
                   7514: for conditional compilation (for an example, @pxref{Interpreter
                   7515: Directives}).
1.44      crook    7516: 
1.35      anton    7517: 
                   7518: @c This is a bad example: It's non-standard, and it's not necessary.
                   7519: @c However, I can't think of a good example for switching into compile
                   7520: @c state when there is no current word (@code{state}-smart words are not a
                   7521: @c good reason).  So maybe we should use an example for switching into
                   7522: @c interpret @code{state} in a colon def. - anton
1.44      crook    7523: @c nac-> I agree. I started out by putting in the example, then realised
                   7524: @c that it was non-ANS, so wrote more words around it. I hope this
                   7525: @c re-written version is acceptable to you. I do want to keep the example
                   7526: @c as it is helpful for showing what is and what is not portable, particularly
                   7527: @c where it outlaws a style in common use.
                   7528: 
1.72      anton    7529: @c anton: it's more important to show what's portable.  After we have done
                   7530: @c that, we can also show what's not.  In any case, I intend to write a
                   7531: @c section Macros (or so) which will also deal with [ ].
1.35      anton    7532: 
1.44      crook    7533: @code{[} and @code{]} also give you the ability to switch into compile
                   7534: state and back, but we cannot think of any useful Standard application
                   7535: for this ability. Pre-ANS Forth textbooks have examples like this:
1.29      crook    7536: 
                   7537: @example
                   7538: : AA ." this is A" ;
                   7539: : BB ." this is B" ;
                   7540: : CC ." this is C" ;
                   7541: 
1.44      crook    7542: create table ] aa bb cc [
                   7543: 
1.29      crook    7544: : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   7545:   cells table + @ execute ;
                   7546: @end example
                   7547: 
1.44      crook    7548: This example builds a jump table; @code{0 go} will display ``@code{this
                   7549: is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   7550: defining @code{table} like this:
1.29      crook    7551: 
                   7552: @example
1.44      crook    7553: create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
1.29      crook    7554: @end example
                   7555: 
1.44      crook    7556: The problem with this code is that the definition of @code{table} is not
                   7557: portable -- it @i{compile}s execution tokens into code space. Whilst it
                   7558: @i{may} work on systems where code space and data space co-incide, the
1.29      crook    7559: Standard only allows data space to be assigned for a @code{CREATE}d
                   7560: word. In addition, the Standard only allows @code{@@} to access data
                   7561: space, whilst this example is using it to access code space. The only
                   7562: portable, Standard way to build this table is to build it in data space,
                   7563: like this:
                   7564: 
                   7565: @example
                   7566: create table ' aa , ' bb , ' cc ,
                   7567: @end example
                   7568: 
1.26      crook    7569: doc-state
1.44      crook    7570: 
1.26      crook    7571: @node Literals, Interpreter Directives, Interpret/Compile states, The Text Interpreter
                   7572: @subsection Literals
                   7573: @cindex Literals
1.21      crook    7574: 
1.29      crook    7575: Often, you want to use a number within a colon definition. When you do
                   7576: this, the text interpreter automatically compiles the number as a
                   7577: @i{literal}. A literal is a number whose run-time effect is to be pushed
                   7578: onto the stack.  If you had to do some maths to generate the number, you
                   7579: might write it like this:
                   7580: 
                   7581: @example
                   7582: : HOUR-TO-SEC ( n1 -- n2 )
                   7583:   60 *      \ to minutes
                   7584:   60 * ;    \ to seconds
                   7585: @end example
                   7586: 
                   7587: It is very clear what this definition is doing, but it's inefficient
                   7588: since it is performing 2 multiples at run-time. An alternative would be
                   7589: to write:
                   7590: 
                   7591: @example
                   7592: : HOUR-TO-SEC ( n1 -- n2 )
                   7593:   3600 * ;  \ to seconds
                   7594: @end example
                   7595: 
                   7596: Which does the same thing, and has the advantage of using a single
                   7597: multiply. Ideally, we'd like the efficiency of the second with the
                   7598: readability of the first.
                   7599: 
                   7600: @code{Literal} allows us to achieve that. It takes a number from the
                   7601: stack and lays it down in the current definition just as though the
                   7602: number had been typed directly into the definition. Our first attempt
                   7603: might look like this:
                   7604: 
                   7605: @example
                   7606: 60          \ mins per hour
                   7607: 60 *        \ seconds per minute
                   7608: : HOUR-TO-SEC ( n1 -- n2 )
                   7609:   Literal * ;  \ to seconds
                   7610: @end example
                   7611: 
                   7612: But this produces the error message @code{unstructured}. What happened?
                   7613: The stack notation for @code{:} is (@i{ -- colon-sys}) and the size of
                   7614: @i{colon-sys} is implementation-defined. In other words, once we start a
                   7615: colon definition we can't portably access anything that was on the stack
                   7616: before the definition began@footnote{@cite{Two Problems in ANS Forth},
                   7617: by Thomas Worthington; Forth Dimensions 20(2) pages 32--34 describes
                   7618: some situations where you might want to access stack items above
                   7619: colon-sys, and provides a solution to the problem.}. The correct way of
                   7620: solving this problem in this instance is to use @code{[ ]} like this:
                   7621: 
                   7622: @example
                   7623: : HOUR-TO-SEC ( n1 -- n2 )
                   7624:   [ 60          \ minutes per hour
                   7625:     60 * ]      \ seconds per minute
                   7626:   LITERAL * ;   \ to seconds
                   7627: @end example
1.23      crook    7628: 
1.44      crook    7629: 
                   7630: 
1.48      anton    7631: @node Interpreter Directives,  , Literals, The Text Interpreter
1.26      crook    7632: @subsection Interpreter Directives
                   7633: @cindex interpreter directives
1.72      anton    7634: @cindex conditional compilation
1.1       anton    7635: 
1.29      crook    7636: These words are usually used in interpret state; typically to control
                   7637: which parts of a source file are processed by the text
1.26      crook    7638: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   7639: supplements these with a rich set of immediate control structure words
                   7640: to compensate for the fact that the non-immediate versions can only be
1.29      crook    7641: used in compile state (@pxref{Control Structures}). Typical usages:
                   7642: 
                   7643: @example
1.72      anton    7644: FALSE Constant HAVE-ASSEMBLER
1.29      crook    7645: .
                   7646: .
1.72      anton    7647: HAVE-ASSEMBLER [IF]
1.29      crook    7648: : ASSEMBLER-FEATURE
                   7649:   ...
                   7650: ;
                   7651: [ENDIF]
                   7652: .
                   7653: .
                   7654: : SEE
                   7655:   ... \ general-purpose SEE code
1.72      anton    7656:   [ HAVE-ASSEMBLER [IF] ]
1.29      crook    7657:   ... \ assembler-specific SEE code
                   7658:   [ [ENDIF] ]
                   7659: ;
                   7660: @end example
1.1       anton    7661: 
1.44      crook    7662: 
1.26      crook    7663: doc-[IF]
                   7664: doc-[ELSE]
                   7665: doc-[THEN]
                   7666: doc-[ENDIF]
1.1       anton    7667: 
1.26      crook    7668: doc-[IFDEF]
                   7669: doc-[IFUNDEF]
1.1       anton    7670: 
1.26      crook    7671: doc-[?DO]
                   7672: doc-[DO]
                   7673: doc-[FOR]
                   7674: doc-[LOOP]
                   7675: doc-[+LOOP]
                   7676: doc-[NEXT]
1.1       anton    7677: 
1.26      crook    7678: doc-[BEGIN]
                   7679: doc-[UNTIL]
                   7680: doc-[AGAIN]
                   7681: doc-[WHILE]
                   7682: doc-[REPEAT]
1.1       anton    7683: 
1.27      crook    7684: 
1.26      crook    7685: @c -------------------------------------------------------------
1.47      crook    7686: @node Word Lists, Environmental Queries, The Text Interpreter, Words
1.26      crook    7687: @section Word Lists
                   7688: @cindex word lists
1.32      anton    7689: @cindex header space
1.1       anton    7690: 
1.36      anton    7691: A wordlist is a list of named words; you can add new words and look up
                   7692: words by name (and you can remove words in a restricted way with
                   7693: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   7694: 
                   7695: @cindex search order stack
                   7696: The text interpreter searches the wordlists present in the search order
                   7697: (a stack of wordlists), from the top to the bottom.  Within each
                   7698: wordlist, the search starts conceptually at the newest word; i.e., if
                   7699: two words in a wordlist have the same name, the newer word is found.
1.1       anton    7700: 
1.26      crook    7701: @cindex compilation word list
1.36      anton    7702: New words are added to the @dfn{compilation wordlist} (aka current
                   7703: wordlist).
1.1       anton    7704: 
1.36      anton    7705: @cindex wid
                   7706: A word list is identified by a cell-sized word list identifier (@i{wid})
                   7707: in much the same way as a file is identified by a file handle. The
                   7708: numerical value of the wid has no (portable) meaning, and might change
                   7709: from session to session.
1.1       anton    7710: 
1.29      crook    7711: The ANS Forth ``Search order'' word set is intended to provide a set of
                   7712: low-level tools that allow various different schemes to be
1.74      anton    7713: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26      crook    7714: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    7715: Forth.
1.1       anton    7716: 
1.27      crook    7717: @comment TODO: locals section refers to here, saying that every word list (aka
                   7718: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78      anton    7719: @c anton: but better in a separate subsection on wordlist internals
1.1       anton    7720: 
1.45      crook    7721: @comment TODO: document markers, reveal, tables, mappedwordlist
                   7722: 
                   7723: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    7724: @comment word from the source files, rather than some alias.
1.44      crook    7725: 
1.26      crook    7726: doc-forth-wordlist
                   7727: doc-definitions
                   7728: doc-get-current
                   7729: doc-set-current
                   7730: doc-get-order
1.45      crook    7731: doc---gforthman-set-order
1.26      crook    7732: doc-wordlist
1.30      anton    7733: doc-table
1.79      anton    7734: doc->order
1.36      anton    7735: doc-previous
1.26      crook    7736: doc-also
1.45      crook    7737: doc---gforthman-forth
1.26      crook    7738: doc-only
1.45      crook    7739: doc---gforthman-order
1.15      anton    7740: 
1.26      crook    7741: doc-find
                   7742: doc-search-wordlist
1.15      anton    7743: 
1.26      crook    7744: doc-words
                   7745: doc-vlist
1.44      crook    7746: @c doc-words-deferred
1.1       anton    7747: 
1.74      anton    7748: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26      crook    7749: doc-root
                   7750: doc-vocabulary
                   7751: doc-seal
                   7752: doc-vocs
                   7753: doc-current
                   7754: doc-context
1.1       anton    7755: 
1.44      crook    7756: 
1.26      crook    7757: @menu
1.75      anton    7758: * Vocabularies::                
1.67      anton    7759: * Why use word lists?::         
1.75      anton    7760: * Word list example::           
1.26      crook    7761: @end menu
                   7762: 
1.75      anton    7763: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
                   7764: @subsection Vocabularies
                   7765: @cindex Vocabularies, detailed explanation
                   7766: 
                   7767: Here is an example of creating and using a new wordlist using ANS
                   7768: Forth words:
                   7769: 
                   7770: @example
                   7771: wordlist constant my-new-words-wordlist
                   7772: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
                   7773: 
                   7774: \ add it to the search order
                   7775: also my-new-words
                   7776: 
                   7777: \ alternatively, add it to the search order and make it
                   7778: \ the compilation word list
                   7779: also my-new-words definitions
                   7780: \ type "order" to see the problem
                   7781: @end example
                   7782: 
                   7783: The problem with this example is that @code{order} has no way to
                   7784: associate the name @code{my-new-words} with the wid of the word list (in
                   7785: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   7786: that has no associated name). There is no Standard way of associating a
                   7787: name with a wid.
                   7788: 
                   7789: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   7790: associates a name with a wid:
                   7791: 
                   7792: @example
                   7793: vocabulary my-new-words
                   7794: 
                   7795: \ add it to the search order
                   7796: also my-new-words
                   7797: 
                   7798: \ alternatively, add it to the search order and make it
                   7799: \ the compilation word list
                   7800: my-new-words definitions
                   7801: \ type "order" to see that the problem is solved
                   7802: @end example
                   7803: 
                   7804: 
                   7805: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26      crook    7806: @subsection Why use word lists?
                   7807: @cindex word lists - why use them?
                   7808: 
1.74      anton    7809: Here are some reasons why people use wordlists:
1.26      crook    7810: 
                   7811: @itemize @bullet
1.74      anton    7812: 
                   7813: @c anton: Gforth's hashing implementation makes the search speed
                   7814: @c independent from the number of words.  But it is linear with the number
                   7815: @c of wordlists that have to be searched, so in effect using more wordlists
                   7816: @c actually slows down compilation.
                   7817: 
                   7818: @c @item
                   7819: @c To improve compilation speed by reducing the number of header space
                   7820: @c entries that must be searched. This is achieved by creating a new
                   7821: @c word list that contains all of the definitions that are used in the
                   7822: @c definition of a Forth system but which would not usually be used by
                   7823: @c programs running on that system. That word list would be on the search
                   7824: @c list when the Forth system was compiled but would be removed from the
                   7825: @c search list for normal operation. This can be a useful technique for
                   7826: @c low-performance systems (for example, 8-bit processors in embedded
                   7827: @c systems) but is unlikely to be necessary in high-performance desktop
                   7828: @c systems.
                   7829: 
1.26      crook    7830: @item
                   7831: To prevent a set of words from being used outside the context in which
                   7832: they are valid. Two classic examples of this are an integrated editor
                   7833: (all of the edit commands are defined in a separate word list; the
                   7834: search order is set to the editor word list when the editor is invoked;
                   7835: the old search order is restored when the editor is terminated) and an
                   7836: integrated assembler (the op-codes for the machine are defined in a
                   7837: separate word list which is used when a @code{CODE} word is defined).
1.74      anton    7838: 
                   7839: @item
                   7840: To organize the words of an application or library into a user-visible
                   7841: set (in @code{forth-wordlist} or some other common wordlist) and a set
                   7842: of helper words used just for the implementation (hidden in a separate
1.75      anton    7843: wordlist).  This keeps @code{words}' output smaller, separates
                   7844: implementation and interface, and reduces the chance of name conflicts
                   7845: within the common wordlist.
1.74      anton    7846: 
1.26      crook    7847: @item
                   7848: To prevent a name-space clash between multiple definitions with the same
                   7849: name. For example, when building a cross-compiler you might have a word
                   7850: @code{IF} that generates conditional code for your target system. By
                   7851: placing this definition in a different word list you can control whether
                   7852: the host system's @code{IF} or the target system's @code{IF} get used in
                   7853: any particular context by controlling the order of the word lists on the
                   7854: search order stack.
1.74      anton    7855: 
1.26      crook    7856: @end itemize
1.1       anton    7857: 
1.74      anton    7858: The downsides of using wordlists are:
                   7859: 
                   7860: @itemize
                   7861: 
                   7862: @item
                   7863: Debugging becomes more cumbersome.
                   7864: 
                   7865: @item
                   7866: Name conflicts worked around with wordlists are still there, and you
                   7867: have to arrange the search order carefully to get the desired results;
                   7868: if you forget to do that, you get hard-to-find errors (as in any case
                   7869: where you read the code differently from the compiler; @code{see} can
1.75      anton    7870: help seeing which of several possible words the name resolves to in such
                   7871: cases).  @code{See} displays just the name of the words, not what
                   7872: wordlist they belong to, so it might be misleading.  Using unique names
                   7873: is a better approach to avoid name conflicts.
1.74      anton    7874: 
                   7875: @item
                   7876: You have to explicitly undo any changes to the search order.  In many
                   7877: cases it would be more convenient if this happened implicitly.  Gforth
                   7878: currently does not provide such a feature, but it may do so in the
                   7879: future.
                   7880: @end itemize
                   7881: 
                   7882: 
1.75      anton    7883: @node Word list example,  , Why use word lists?, Word Lists
                   7884: @subsection Word list example
                   7885: @cindex word lists - example
1.1       anton    7886: 
1.74      anton    7887: The following example is from the
                   7888: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   7889: garbage collector} and uses wordlists to separate public words from
                   7890: helper words:
                   7891: 
                   7892: @example
                   7893: get-current ( wid )
                   7894: vocabulary garbage-collector also garbage-collector definitions
                   7895: ... \ define helper words
                   7896: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
                   7897: ... \ define the public (i.e., API) words
                   7898:     \ they can refer to the helper words
                   7899: previous \ restore original search order (helper words become invisible)
                   7900: @end example
                   7901: 
1.26      crook    7902: @c -------------------------------------------------------------
                   7903: @node Environmental Queries, Files, Word Lists, Words
                   7904: @section Environmental Queries
                   7905: @cindex environmental queries
1.21      crook    7906: 
1.26      crook    7907: ANS Forth introduced the idea of ``environmental queries'' as a way
                   7908: for a program running on a system to determine certain characteristics of the system.
                   7909: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    7910: 
1.32      anton    7911: The Standard requires that the header space used for environmental queries
                   7912: be distinct from the header space used for definitions.
1.21      crook    7913: 
1.26      crook    7914: Typically, environmental queries are supported by creating a set of
1.29      crook    7915: definitions in a word list that is @i{only} used during environmental
1.26      crook    7916: queries; that is what Gforth does. There is no Standard way of adding
                   7917: definitions to the set of recognised environmental queries, but any
                   7918: implementation that supports the loading of optional word sets must have
                   7919: some mechanism for doing this (after loading the word set, the
                   7920: associated environmental query string must return @code{true}). In
                   7921: Gforth, the word list used to honour environmental queries can be
                   7922: manipulated just like any other word list.
1.21      crook    7923: 
1.44      crook    7924: 
1.26      crook    7925: doc-environment?
                   7926: doc-environment-wordlist
1.21      crook    7927: 
1.26      crook    7928: doc-gforth
                   7929: doc-os-class
1.21      crook    7930: 
1.44      crook    7931: 
1.26      crook    7932: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   7933: returning two items on the stack, querying it using @code{environment?}
                   7934: will return an additional item; the @code{true} flag that shows that the
                   7935: string was recognised.
1.21      crook    7936: 
1.26      crook    7937: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    7938: 
1.26      crook    7939: Here are some examples of using environmental queries:
1.21      crook    7940: 
1.26      crook    7941: @example
                   7942: s" address-unit-bits" environment? 0=
                   7943: [IF]
                   7944:      cr .( environmental attribute address-units-bits unknown... ) cr
1.75      anton    7945: [ELSE]
                   7946:      drop \ ensure balanced stack effect
1.26      crook    7947: [THEN]
1.21      crook    7948: 
1.75      anton    7949: \ this might occur in the prelude of a standard program that uses THROW
                   7950: s" exception" environment? [IF]
                   7951:    0= [IF]
                   7952:       : throw abort" exception thrown" ;
                   7953:    [THEN]
                   7954: [ELSE] \ we don't know, so make sure
                   7955:    : throw abort" exception thrown" ;
                   7956: [THEN]
1.21      crook    7957: 
1.26      crook    7958: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   7959:                         [ELSE] .( Not Gforth..) [THEN]
1.75      anton    7960: 
                   7961: \ a program using v*
                   7962: s" gforth" environment? [IF]
                   7963:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
                   7964:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   7965:      >r swap 2swap swap 0e r> 0 ?DO
                   7966:        dup f@ over + 2swap dup f@ f* f+ over + 2swap
                   7967:      LOOP
                   7968:      2drop 2drop ; 
                   7969:   [THEN]
                   7970: [ELSE] \ 
                   7971:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   7972:   ...
                   7973: [THEN]
1.26      crook    7974: @end example
1.21      crook    7975: 
1.26      crook    7976: Here is an example of adding a definition to the environment word list:
1.21      crook    7977: 
1.26      crook    7978: @example
                   7979: get-current environment-wordlist set-current
                   7980: true constant block
                   7981: true constant block-ext
                   7982: set-current
                   7983: @end example
1.21      crook    7984: 
1.26      crook    7985: You can see what definitions are in the environment word list like this:
1.21      crook    7986: 
1.26      crook    7987: @example
1.79      anton    7988: environment-wordlist >order words previous
1.26      crook    7989: @end example
1.21      crook    7990: 
                   7991: 
1.26      crook    7992: @c -------------------------------------------------------------
                   7993: @node Files, Blocks, Environmental Queries, Words
                   7994: @section Files
1.28      crook    7995: @cindex files
                   7996: @cindex I/O - file-handling
1.21      crook    7997: 
1.26      crook    7998: Gforth provides facilities for accessing files that are stored in the
                   7999: host operating system's file-system. Files that are processed by Gforth
                   8000: can be divided into two categories:
1.21      crook    8001: 
1.23      crook    8002: @itemize @bullet
                   8003: @item
1.29      crook    8004: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    8005: @item
1.29      crook    8006: Files that are processed by some other program (@dfn{general files}).
1.26      crook    8007: @end itemize
                   8008: 
                   8009: @menu
1.48      anton    8010: * Forth source files::          
                   8011: * General files::               
                   8012: * Search Paths::                
1.26      crook    8013: @end menu
                   8014: 
                   8015: @c -------------------------------------------------------------
                   8016: @node Forth source files, General files, Files, Files
                   8017: @subsection Forth source files
                   8018: @cindex including files
                   8019: @cindex Forth source files
1.21      crook    8020: 
1.26      crook    8021: The simplest way to interpret the contents of a file is to use one of
                   8022: these two formats:
1.21      crook    8023: 
1.26      crook    8024: @example
                   8025: include mysource.fs
                   8026: s" mysource.fs" included
                   8027: @end example
1.21      crook    8028: 
1.75      anton    8029: You usually want to include a file only if it is not included already
1.26      crook    8030: (by, say, another source file). In that case, you can use one of these
1.45      crook    8031: three formats:
1.21      crook    8032: 
1.26      crook    8033: @example
                   8034: require mysource.fs
                   8035: needs mysource.fs
                   8036: s" mysource.fs" required
                   8037: @end example
1.21      crook    8038: 
1.26      crook    8039: @cindex stack effect of included files
                   8040: @cindex including files, stack effect
1.45      crook    8041: It is good practice to write your source files such that interpreting them
                   8042: does not change the stack. Source files designed in this way can be used with
1.26      crook    8043: @code{required} and friends without complications. For example:
1.21      crook    8044: 
1.26      crook    8045: @example
1.75      anton    8046: 1024 require foo.fs drop
1.26      crook    8047: @end example
1.21      crook    8048: 
1.75      anton    8049: Here you want to pass the argument 1024 (e.g., a buffer size) to
                   8050: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
                   8051: ), which allows its use with @code{require}.  Of course with such
                   8052: parameters to required files, you have to ensure that the first
                   8053: @code{require} fits for all uses (i.e., @code{require} it early in the
                   8054: master load file).
1.44      crook    8055: 
1.26      crook    8056: doc-include-file
                   8057: doc-included
1.28      crook    8058: doc-included?
1.26      crook    8059: doc-include
                   8060: doc-required
                   8061: doc-require
                   8062: doc-needs
1.75      anton    8063: @c doc-init-included-files @c internal
                   8064: @c doc-loadfilename @c internal word
                   8065: doc-sourcefilename
                   8066: doc-sourceline#
1.44      crook    8067: 
1.26      crook    8068: A definition in ANS Forth for @code{required} is provided in
                   8069: @file{compat/required.fs}.
1.21      crook    8070: 
1.26      crook    8071: @c -------------------------------------------------------------
                   8072: @node General files, Search Paths, Forth source files, Files
                   8073: @subsection General files
                   8074: @cindex general files
                   8075: @cindex file-handling
1.21      crook    8076: 
1.75      anton    8077: Files are opened/created by name and type. The following file access
                   8078: methods (FAMs) are recognised:
1.44      crook    8079: 
1.75      anton    8080: @cindex fam (file access method)
1.26      crook    8081: doc-r/o
                   8082: doc-r/w
                   8083: doc-w/o
                   8084: doc-bin
1.1       anton    8085: 
1.44      crook    8086: 
1.26      crook    8087: When a file is opened/created, it returns a file identifier,
1.29      crook    8088: @i{wfileid} that is used for all other file commands. All file
                   8089: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    8090: successful operation and an implementation-defined non-zero value in the
                   8091: case of an error.
1.21      crook    8092: 
1.44      crook    8093: 
1.26      crook    8094: doc-open-file
                   8095: doc-create-file
1.21      crook    8096: 
1.26      crook    8097: doc-close-file
                   8098: doc-delete-file
                   8099: doc-rename-file
                   8100: doc-read-file
                   8101: doc-read-line
                   8102: doc-write-file
                   8103: doc-write-line
                   8104: doc-emit-file
                   8105: doc-flush-file
1.21      crook    8106: 
1.26      crook    8107: doc-file-status
                   8108: doc-file-position
                   8109: doc-reposition-file
                   8110: doc-file-size
                   8111: doc-resize-file
1.21      crook    8112: 
1.44      crook    8113: 
1.26      crook    8114: @c ---------------------------------------------------------
1.48      anton    8115: @node Search Paths,  , General files, Files
1.26      crook    8116: @subsection Search Paths
                   8117: @cindex path for @code{included}
                   8118: @cindex file search path
                   8119: @cindex @code{include} search path
                   8120: @cindex search path for files
1.21      crook    8121: 
1.26      crook    8122: If you specify an absolute filename (i.e., a filename starting with
                   8123: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   8124: @samp{C:...})) for @code{included} and friends, that file is included
                   8125: just as you would expect.
1.21      crook    8126: 
1.75      anton    8127: If the filename starts with @file{./}, this refers to the directory that
                   8128: the present file was @code{included} from.  This allows files to include
                   8129: other files relative to their own position (irrespective of the current
                   8130: working directory or the absolute position).  This feature is essential
                   8131: for libraries consisting of several files, where a file may include
                   8132: other files from the library.  It corresponds to @code{#include "..."}
                   8133: in C. If the current input source is not a file, @file{.} refers to the
                   8134: directory of the innermost file being included, or, if there is no file
                   8135: being included, to the current working directory.
                   8136: 
                   8137: For relative filenames (not starting with @file{./}), Gforth uses a
                   8138: search path similar to Forth's search order (@pxref{Word Lists}). It
                   8139: tries to find the given filename in the directories present in the path,
                   8140: and includes the first one it finds. There are separate search paths for
                   8141: Forth source files and general files.  If the search path contains the
                   8142: directory @file{.}, this refers to the directory of the current file, or
                   8143: the working directory, as if the file had been specified with @file{./}.
1.21      crook    8144: 
1.26      crook    8145: Use @file{~+} to refer to the current working directory (as in the
                   8146: @code{bash}).
1.1       anton    8147: 
1.75      anton    8148: @c anton: fold the following subsubsections into this subsection?
1.1       anton    8149: 
1.48      anton    8150: @menu
1.75      anton    8151: * Source Search Paths::         
1.48      anton    8152: * General Search Paths::        
                   8153: @end menu
                   8154: 
1.26      crook    8155: @c ---------------------------------------------------------
1.75      anton    8156: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
                   8157: @subsubsection Source Search Paths
                   8158: @cindex search path control, source files
1.5       anton    8159: 
1.26      crook    8160: The search path is initialized when you start Gforth (@pxref{Invoking
1.75      anton    8161: Gforth}). You can display it and change it using @code{fpath} in
                   8162: combination with the general path handling words.
1.5       anton    8163: 
1.75      anton    8164: doc-fpath
                   8165: @c the functionality of the following words is easily available through
                   8166: @c   fpath and the general path words.  The may go away.
                   8167: @c doc-.fpath
                   8168: @c doc-fpath+
                   8169: @c doc-fpath=
                   8170: @c doc-open-fpath-file
1.44      crook    8171: 
                   8172: @noindent
1.26      crook    8173: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    8174: 
1.26      crook    8175: @example
1.75      anton    8176: fpath path= /usr/lib/forth/|./
1.26      crook    8177: require timer.fs
                   8178: @end example
1.5       anton    8179: 
1.75      anton    8180: 
1.26      crook    8181: @c ---------------------------------------------------------
1.75      anton    8182: @node General Search Paths,  , Source Search Paths, Search Paths
1.26      crook    8183: @subsubsection General Search Paths
1.75      anton    8184: @cindex search path control, source files
1.5       anton    8185: 
1.26      crook    8186: Your application may need to search files in several directories, like
                   8187: @code{included} does. To facilitate this, Gforth allows you to define
                   8188: and use your own search paths, by providing generic equivalents of the
                   8189: Forth search path words:
1.5       anton    8190: 
1.75      anton    8191: doc-open-path-file
                   8192: doc-path-allot
                   8193: doc-clear-path
                   8194: doc-also-path
1.26      crook    8195: doc-.path
                   8196: doc-path+
                   8197: doc-path=
1.5       anton    8198: 
1.75      anton    8199: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44      crook    8200: 
1.75      anton    8201: Here's an example of creating an empty search path:
                   8202: @c
1.26      crook    8203: @example
1.75      anton    8204: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26      crook    8205: @end example
1.5       anton    8206: 
1.26      crook    8207: @c -------------------------------------------------------------
                   8208: @node Blocks, Other I/O, Files, Words
                   8209: @section Blocks
1.28      crook    8210: @cindex I/O - blocks
                   8211: @cindex blocks
                   8212: 
                   8213: When you run Gforth on a modern desk-top computer, it runs under the
                   8214: control of an operating system which provides certain services.  One of
                   8215: these services is @var{file services}, which allows Forth source code
                   8216: and data to be stored in files and read into Gforth (@pxref{Files}).
                   8217: 
                   8218: Traditionally, Forth has been an important programming language on
                   8219: systems where it has interfaced directly to the underlying hardware with
                   8220: no intervening operating system. Forth provides a mechanism, called
1.29      crook    8221: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    8222: 
                   8223: A block is a 1024-byte data area, which can be used to hold data or
                   8224: Forth source code. No structure is imposed on the contents of the
                   8225: block. A block is identified by its number; blocks are numbered
                   8226: contiguously from 1 to an implementation-defined maximum.
                   8227: 
                   8228: A typical system that used blocks but no operating system might use a
                   8229: single floppy-disk drive for mass storage, with the disks formatted to
                   8230: provide 256-byte sectors. Blocks would be implemented by assigning the
                   8231: first four sectors of the disk to block 1, the second four sectors to
                   8232: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   8233: would not contain any file system information, just the set of blocks.
                   8234: 
1.29      crook    8235: @cindex blocks file
1.28      crook    8236: On systems that do provide file services, blocks are typically
1.29      crook    8237: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    8238: file}.  The size of the blocks file will be an exact multiple of 1024
                   8239: bytes, corresponding to the number of blocks it contains. This is the
                   8240: mechanism that Gforth uses.
                   8241: 
1.29      crook    8242: @cindex @file{blocks.fb}
1.75      anton    8243: Only one blocks file can be open at a time. If you use block words without
1.28      crook    8244: having specified a blocks file, Gforth defaults to the blocks file
                   8245: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75      anton    8246: locate a blocks file (@pxref{Source Search Paths}).
1.28      crook    8247: 
1.29      crook    8248: @cindex block buffers
1.28      crook    8249: When you read and write blocks under program control, Gforth uses a
1.29      crook    8250: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    8251: not used when you use @code{load} to interpret the contents of a block.
                   8252: 
1.75      anton    8253: The behaviour of the block buffers is analagous to that of a cache.
                   8254: Each block buffer has three states:
1.28      crook    8255: 
                   8256: @itemize @bullet
                   8257: @item
                   8258: Unassigned
                   8259: @item
                   8260: Assigned-clean
                   8261: @item
                   8262: Assigned-dirty
                   8263: @end itemize
                   8264: 
1.29      crook    8265: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    8266: block, the block (specified by its block number) must be assigned to a
                   8267: block buffer.
                   8268: 
                   8269: The assignment of a block to a block buffer is performed by @code{block}
                   8270: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   8271: contents of a block. Use @code{buffer} when you don't care about the
                   8272: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    8273: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    8274: with the particular block is already stored in a block buffer due to an
                   8275: earlier @code{block} command, @code{buffer} will return that block
                   8276: buffer and the existing contents of the block will be
                   8277: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    8278: block buffer for the block.}.
1.28      crook    8279: 
1.47      crook    8280: Once a block has been assigned to a block buffer using @code{block} or
1.75      anton    8281: @code{buffer}, that block buffer becomes the @i{current block
                   8282: buffer}. Data may only be manipulated (read or written) within the
                   8283: current block buffer.
1.47      crook    8284: 
                   8285: When the contents of the current block buffer has been modified it is
1.48      anton    8286: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75      anton    8287: either abandon the changes (by doing nothing) or mark the block as
                   8288: changed (assigned-dirty), using @code{update}. Using @code{update} does
                   8289: not change the blocks file; it simply changes a block buffer's state to
                   8290: @i{assigned-dirty}.  The block will be written implicitly when it's
                   8291: buffer is needed for another block, or explicitly by @code{flush} or
                   8292: @code{save-buffers}.
                   8293: 
                   8294: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
                   8295: blocks file on disk. Leaving Gforth with @code{bye} also performs a
                   8296: @code{flush}.
1.28      crook    8297: 
1.29      crook    8298: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    8299: algorithm to assign a block buffer to a block. That means that any
                   8300: particular block can only be assigned to one specific block buffer,
1.29      crook    8301: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    8302: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   8303: the new block immediately. If it is @i{assigned-dirty} its current
                   8304: contents are written back to the blocks file on disk before it is
1.28      crook    8305: allocated to the new block.
                   8306: 
                   8307: Although no structure is imposed on the contents of a block, it is
                   8308: traditional to display the contents as 16 lines each of 64 characters.  A
                   8309: block provides a single, continuous stream of input (for example, it
                   8310: acts as a single parse area) -- there are no end-of-line characters
                   8311: within a block, and no end-of-file character at the end of a
                   8312: block. There are two consequences of this:
1.26      crook    8313: 
1.28      crook    8314: @itemize @bullet
                   8315: @item
                   8316: The last character of one line wraps straight into the first character
                   8317: of the following line
                   8318: @item
                   8319: The word @code{\} -- comment to end of line -- requires special
                   8320: treatment; in the context of a block it causes all characters until the
                   8321: end of the current 64-character ``line'' to be ignored.
                   8322: @end itemize
                   8323: 
                   8324: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    8325: the current blocks file will be extended to the appropriate size and the
1.28      crook    8326: block buffer will be initialised with spaces.
                   8327: 
1.47      crook    8328: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   8329: for details) but doesn't encourage the use of blocks; the mechanism is
                   8330: only provided for backward compatibility -- ANS Forth requires blocks to
                   8331: be available when files are.
1.28      crook    8332: 
                   8333: Common techniques that are used when working with blocks include:
                   8334: 
                   8335: @itemize @bullet
                   8336: @item
                   8337: A screen editor that allows you to edit blocks without leaving the Forth
                   8338: environment.
                   8339: @item
                   8340: Shadow screens; where every code block has an associated block
                   8341: containing comments (for example: code in odd block numbers, comments in
                   8342: even block numbers). Typically, the block editor provides a convenient
                   8343: mechanism to toggle between code and comments.
                   8344: @item
                   8345: Load blocks; a single block (typically block 1) contains a number of
                   8346: @code{thru} commands which @code{load} the whole of the application.
                   8347: @end itemize
1.26      crook    8348: 
1.29      crook    8349: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   8350: integrated into a Forth programming environment.
1.26      crook    8351: 
                   8352: @comment TODO what about errors on open-blocks?
1.44      crook    8353: 
1.26      crook    8354: doc-open-blocks
                   8355: doc-use
1.75      anton    8356: doc-block-offset
1.26      crook    8357: doc-get-block-fid
                   8358: doc-block-position
1.28      crook    8359: 
1.75      anton    8360: doc-list
1.28      crook    8361: doc-scr
                   8362: 
1.45      crook    8363: doc---gforthman-block
1.28      crook    8364: doc-buffer
                   8365: 
1.75      anton    8366: doc-empty-buffers
                   8367: doc-empty-buffer
1.26      crook    8368: doc-update
1.28      crook    8369: doc-updated?
1.26      crook    8370: doc-save-buffers
1.75      anton    8371: doc-save-buffer
1.26      crook    8372: doc-flush
1.28      crook    8373: 
1.26      crook    8374: doc-load
                   8375: doc-thru
                   8376: doc-+load
                   8377: doc-+thru
1.45      crook    8378: doc---gforthman--->
1.26      crook    8379: doc-block-included
                   8380: 
1.44      crook    8381: 
1.26      crook    8382: @c -------------------------------------------------------------
1.78      anton    8383: @node Other I/O, Locals, Blocks, Words
1.26      crook    8384: @section Other I/O
1.28      crook    8385: @cindex I/O - keyboard and display
1.26      crook    8386: 
                   8387: @menu
                   8388: * Simple numeric output::       Predefined formats
                   8389: * Formatted numeric output::    Formatted (pictured) output
                   8390: * String Formats::              How Forth stores strings in memory
1.67      anton    8391: * Displaying characters and strings::  Other stuff
1.26      crook    8392: * Input::                       Input
                   8393: @end menu
                   8394: 
                   8395: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8396: @subsection Simple numeric output
1.28      crook    8397: @cindex numeric output - simple/free-format
1.5       anton    8398: 
1.26      crook    8399: The simplest output functions are those that display numbers from the
                   8400: data or floating-point stacks. Floating-point output is always displayed
                   8401: using base 10. Numbers displayed from the data stack use the value stored
                   8402: in @code{base}.
1.5       anton    8403: 
1.44      crook    8404: 
1.26      crook    8405: doc-.
                   8406: doc-dec.
                   8407: doc-hex.
                   8408: doc-u.
                   8409: doc-.r
                   8410: doc-u.r
                   8411: doc-d.
                   8412: doc-ud.
                   8413: doc-d.r
                   8414: doc-ud.r
                   8415: doc-f.
                   8416: doc-fe.
                   8417: doc-fs.
1.5       anton    8418: 
1.44      crook    8419: 
1.26      crook    8420: Examples of printing the number 1234.5678E23 in the different floating-point output
                   8421: formats are shown below:
1.5       anton    8422: 
                   8423: @example
1.26      crook    8424: f. 123456779999999000000000000.
                   8425: fe. 123.456779999999E24
                   8426: fs. 1.23456779999999E26
1.5       anton    8427: @end example
                   8428: 
                   8429: 
1.26      crook    8430: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   8431: @subsection Formatted numeric output
1.28      crook    8432: @cindex formatted numeric output
1.26      crook    8433: @cindex pictured numeric output
1.28      crook    8434: @cindex numeric output - formatted
1.26      crook    8435: 
1.29      crook    8436: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    8437: output} for formatted printing of integers.  In this technique, digits
                   8438: are extracted from the number (using the current output radix defined by
                   8439: @code{base}), converted to ASCII codes and appended to a string that is
                   8440: built in a scratch-pad area of memory (@pxref{core-idef,
                   8441: Implementation-defined options, Implementation-defined
                   8442: options}). Arbitrary characters can be appended to the string during the
                   8443: extraction process. The completed string is specified by an address
                   8444: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   8445: under program control.
1.5       anton    8446: 
1.75      anton    8447: All of the integer output words described in the previous section
                   8448: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
                   8449: numeric output.
1.5       anton    8450: 
1.47      crook    8451: Three important things to remember about pictured numeric output:
1.5       anton    8452: 
1.26      crook    8453: @itemize @bullet
                   8454: @item
1.28      crook    8455: It always operates on double-precision numbers; to display a
1.49      anton    8456: single-precision number, convert it first (for ways of doing this
                   8457: @pxref{Double precision}).
1.26      crook    8458: @item
1.28      crook    8459: It always treats the double-precision number as though it were
                   8460: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    8461: @item
                   8462: The string is built up from right to left; least significant digit first.
                   8463: @end itemize
1.5       anton    8464: 
1.44      crook    8465: 
1.26      crook    8466: doc-<#
1.47      crook    8467: doc-<<#
1.26      crook    8468: doc-#
                   8469: doc-#s
                   8470: doc-hold
                   8471: doc-sign
                   8472: doc-#>
1.47      crook    8473: doc-#>>
1.5       anton    8474: 
1.26      crook    8475: doc-represent
1.5       anton    8476: 
1.44      crook    8477: 
                   8478: @noindent
1.26      crook    8479: Here are some examples of using pictured numeric output:
1.5       anton    8480: 
                   8481: @example
1.26      crook    8482: : my-u. ( u -- )
                   8483:   \ Simplest use of pns.. behaves like Standard u. 
                   8484:   0              \ convert to unsigned double
1.75      anton    8485:   <<#            \ start conversion
1.26      crook    8486:   #s             \ convert all digits
                   8487:   #>             \ complete conversion
1.75      anton    8488:   TYPE SPACE     \ display, with trailing space
                   8489:   #>> ;          \ release hold area
1.5       anton    8490: 
1.26      crook    8491: : cents-only ( u -- )
                   8492:   0              \ convert to unsigned double
1.75      anton    8493:   <<#            \ start conversion
1.26      crook    8494:   # #            \ convert two least-significant digits
                   8495:   #>             \ complete conversion, discard other digits
1.75      anton    8496:   TYPE SPACE     \ display, with trailing space
                   8497:   #>> ;          \ release hold area
1.5       anton    8498: 
1.26      crook    8499: : dollars-and-cents ( u -- )
                   8500:   0              \ convert to unsigned double
1.75      anton    8501:   <<#            \ start conversion
1.26      crook    8502:   # #            \ convert two least-significant digits
                   8503:   [char] . hold  \ insert decimal point
                   8504:   #s             \ convert remaining digits
                   8505:   [char] $ hold  \ append currency symbol
                   8506:   #>             \ complete conversion
1.75      anton    8507:   TYPE SPACE     \ display, with trailing space
                   8508:   #>> ;          \ release hold area
1.5       anton    8509: 
1.26      crook    8510: : my-. ( n -- )
                   8511:   \ handling negatives.. behaves like Standard .
                   8512:   s>d            \ convert to signed double
                   8513:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8514:   <<#            \ start conversion
1.26      crook    8515:   #s             \ convert all digits
                   8516:   rot sign       \ get at sign byte, append "-" if needed
                   8517:   #>             \ complete conversion
1.75      anton    8518:   TYPE SPACE     \ display, with trailing space
                   8519:   #>> ;          \ release hold area
1.5       anton    8520: 
1.26      crook    8521: : account. ( n -- )
1.75      anton    8522:   \ accountants don't like minus signs, they use parentheses
1.26      crook    8523:   \ for negative numbers
                   8524:   s>d            \ convert to signed double
                   8525:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8526:   <<#            \ start conversion
1.26      crook    8527:   2 pick         \ get copy of sign byte
                   8528:   0< IF [char] ) hold THEN \ right-most character of output
                   8529:   #s             \ convert all digits
                   8530:   rot            \ get at sign byte
                   8531:   0< IF [char] ( hold THEN
                   8532:   #>             \ complete conversion
1.75      anton    8533:   TYPE SPACE     \ display, with trailing space
                   8534:   #>> ;          \ release hold area
                   8535: 
1.5       anton    8536: @end example
                   8537: 
1.26      crook    8538: Here are some examples of using these words:
1.5       anton    8539: 
                   8540: @example
1.26      crook    8541: 1 my-u. 1
                   8542: hex -1 my-u. decimal FFFFFFFF
                   8543: 1 cents-only 01
                   8544: 1234 cents-only 34
                   8545: 2 dollars-and-cents $0.02
                   8546: 1234 dollars-and-cents $12.34
                   8547: 123 my-. 123
                   8548: -123 my. -123
                   8549: 123 account. 123
                   8550: -456 account. (456)
1.5       anton    8551: @end example
                   8552: 
                   8553: 
1.26      crook    8554: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   8555: @subsection String Formats
1.27      crook    8556: @cindex strings - see character strings
                   8557: @cindex character strings - formats
1.28      crook    8558: @cindex I/O - see character strings
1.75      anton    8559: @cindex counted strings
                   8560: 
                   8561: @c anton: this does not really belong here; maybe the memory section,
                   8562: @c  or the principles chapter
1.26      crook    8563: 
1.27      crook    8564: Forth commonly uses two different methods for representing character
                   8565: strings:
1.26      crook    8566: 
                   8567: @itemize @bullet
                   8568: @item
                   8569: @cindex address of counted string
1.45      crook    8570: @cindex counted string
1.29      crook    8571: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   8572: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   8573: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    8574: memory.
                   8575: @item
1.29      crook    8576: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   8577: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    8578: first byte of the string.
                   8579: @end itemize
                   8580: 
                   8581: ANS Forth encourages the use of the second format when representing
1.75      anton    8582: strings.
1.26      crook    8583: 
1.44      crook    8584: 
1.26      crook    8585: doc-count
                   8586: 
1.44      crook    8587: 
1.49      anton    8588: For words that move, copy and search for strings see @ref{Memory
                   8589: Blocks}. For words that display characters and strings see
                   8590: @ref{Displaying characters and strings}.
1.26      crook    8591: 
                   8592: @node Displaying characters and strings, Input, String Formats, Other I/O
                   8593: @subsection Displaying characters and strings
1.27      crook    8594: @cindex characters - compiling and displaying
                   8595: @cindex character strings - compiling and displaying
1.26      crook    8596: 
                   8597: This section starts with a glossary of Forth words and ends with a set
                   8598: of examples.
                   8599: 
1.44      crook    8600: 
1.26      crook    8601: doc-bl
                   8602: doc-space
                   8603: doc-spaces
                   8604: doc-emit
                   8605: doc-toupper
                   8606: doc-."
                   8607: doc-.(
                   8608: doc-type
1.44      crook    8609: doc-typewhite
1.26      crook    8610: doc-cr
1.27      crook    8611: @cindex cursor control
1.26      crook    8612: doc-at-xy
                   8613: doc-page
                   8614: doc-s"
                   8615: doc-c"
                   8616: doc-char
                   8617: doc-[char]
                   8618: doc-sliteral
                   8619: 
1.44      crook    8620: 
                   8621: @noindent
1.26      crook    8622: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    8623: 
                   8624: @example
1.26      crook    8625: .( text-1)
                   8626: : my-word
                   8627:   ." text-2" cr
                   8628:   .( text-3)
                   8629: ;
                   8630: 
                   8631: ." text-4"
                   8632: 
                   8633: : my-char
                   8634:   [char] ALPHABET emit
                   8635:   char emit
                   8636: ;
1.5       anton    8637: @end example
                   8638: 
1.26      crook    8639: When you load this code into Gforth, the following output is generated:
1.5       anton    8640: 
1.26      crook    8641: @example
1.30      anton    8642: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    8643: @end example
1.5       anton    8644: 
1.26      crook    8645: @itemize @bullet
                   8646: @item
                   8647: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   8648: is an immediate word; it behaves in the same way whether it is used inside
                   8649: or outside a colon definition.
                   8650: @item
                   8651: Message @code{text-4} is displayed because of Gforth's added interpretation
                   8652: semantics for @code{."}.
                   8653: @item
1.29      crook    8654: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    8655: performs the compilation semantics for @code{."} within the definition of
                   8656: @code{my-word}.
                   8657: @end itemize
1.5       anton    8658: 
1.26      crook    8659: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    8660: 
1.26      crook    8661: @example
1.30      anton    8662: @kbd{my-word @key{RET}} text-2
1.26      crook    8663:  ok
1.30      anton    8664: @kbd{my-char fred @key{RET}} Af ok
                   8665: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    8666: @end example
1.5       anton    8667: 
                   8668: @itemize @bullet
                   8669: @item
1.26      crook    8670: Message @code{text-2} is displayed because of the run-time behaviour of
                   8671: @code{."}.
                   8672: @item
                   8673: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   8674: on the stack at run-time. @code{emit} always displays the character
                   8675: when @code{my-char} is executed.
                   8676: @item
                   8677: @code{char} parses a string at run-time and the second @code{emit} displays
                   8678: the first character of the string.
1.5       anton    8679: @item
1.26      crook    8680: If you type @code{see my-char} you can see that @code{[char]} discarded
                   8681: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   8682: definition of @code{my-char}.
1.5       anton    8683: @end itemize
                   8684: 
                   8685: 
                   8686: 
1.48      anton    8687: @node Input,  , Displaying characters and strings, Other I/O
1.26      crook    8688: @subsection Input
                   8689: @cindex input
1.28      crook    8690: @cindex I/O - see input
                   8691: @cindex parsing a string
1.5       anton    8692: 
1.49      anton    8693: For ways of storing character strings in memory see @ref{String Formats}.
1.5       anton    8694: 
1.27      crook    8695: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29      crook    8696: @comment then index them
1.27      crook    8697: 
1.44      crook    8698: 
1.27      crook    8699: doc-key
                   8700: doc-key?
1.45      crook    8701: doc-ekey
                   8702: doc-ekey?
                   8703: doc-ekey>char
1.26      crook    8704: doc->number
                   8705: doc->float
                   8706: doc-accept
1.27      crook    8707: doc-pad
1.75      anton    8708: @c anton: these belong in the input stream section
1.27      crook    8709: doc-parse
                   8710: doc-word
                   8711: doc-sword
1.75      anton    8712: doc-name
1.27      crook    8713: doc-refill
                   8714: @comment obsolescent words..
                   8715: doc-convert
1.26      crook    8716: doc-query
                   8717: doc-expect
1.27      crook    8718: doc-span
1.5       anton    8719: 
                   8720: 
1.78      anton    8721: @c -------------------------------------------------------------
                   8722: @node Locals, Structures, Other I/O, Words
                   8723: @section Locals
                   8724: @cindex locals
                   8725: 
                   8726: Local variables can make Forth programming more enjoyable and Forth
                   8727: programs easier to read. Unfortunately, the locals of ANS Forth are
                   8728: laden with restrictions. Therefore, we provide not only the ANS Forth
                   8729: locals wordset, but also our own, more powerful locals wordset (we
                   8730: implemented the ANS Forth locals wordset through our locals wordset).
1.44      crook    8731: 
1.78      anton    8732: The ideas in this section have also been published in M. Anton Ertl,
                   8733: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
                   8734: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12      anton    8735: 
                   8736: @menu
1.78      anton    8737: * Gforth locals::               
                   8738: * ANS Forth locals::            
1.5       anton    8739: @end menu
                   8740: 
1.78      anton    8741: @node Gforth locals, ANS Forth locals, Locals, Locals
                   8742: @subsection Gforth locals
                   8743: @cindex Gforth locals
                   8744: @cindex locals, Gforth style
1.5       anton    8745: 
1.78      anton    8746: Locals can be defined with
1.44      crook    8747: 
1.78      anton    8748: @example
                   8749: @{ local1 local2 ... -- comment @}
                   8750: @end example
                   8751: or
                   8752: @example
                   8753: @{ local1 local2 ... @}
                   8754: @end example
1.5       anton    8755: 
1.78      anton    8756: E.g.,
                   8757: @example
                   8758: : max @{ n1 n2 -- n3 @}
                   8759:  n1 n2 > if
                   8760:    n1
                   8761:  else
                   8762:    n2
                   8763:  endif ;
                   8764: @end example
1.44      crook    8765: 
1.78      anton    8766: The similarity of locals definitions with stack comments is intended. A
                   8767: locals definition often replaces the stack comment of a word. The order
                   8768: of the locals corresponds to the order in a stack comment and everything
                   8769: after the @code{--} is really a comment.
1.77      anton    8770: 
1.78      anton    8771: This similarity has one disadvantage: It is too easy to confuse locals
                   8772: declarations with stack comments, causing bugs and making them hard to
                   8773: find. However, this problem can be avoided by appropriate coding
                   8774: conventions: Do not use both notations in the same program. If you do,
                   8775: they should be distinguished using additional means, e.g. by position.
1.77      anton    8776: 
1.78      anton    8777: @cindex types of locals
                   8778: @cindex locals types
                   8779: The name of the local may be preceded by a type specifier, e.g.,
                   8780: @code{F:} for a floating point value:
1.5       anton    8781: 
1.78      anton    8782: @example
                   8783: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   8784: \ complex multiplication
                   8785:  Ar Br f* Ai Bi f* f-
                   8786:  Ar Bi f* Ai Br f* f+ ;
                   8787: @end example
1.44      crook    8788: 
1.78      anton    8789: @cindex flavours of locals
                   8790: @cindex locals flavours
                   8791: @cindex value-flavoured locals
                   8792: @cindex variable-flavoured locals
                   8793: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   8794: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   8795: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   8796: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   8797: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   8798: produces its address (which becomes invalid when the variable's scope is
                   8799: left). E.g., the standard word @code{emit} can be defined in terms of
                   8800: @code{type} like this:
1.5       anton    8801: 
1.78      anton    8802: @example
                   8803: : emit @{ C^ char* -- @}
                   8804:     char* 1 type ;
                   8805: @end example
1.5       anton    8806: 
1.78      anton    8807: @cindex default type of locals
                   8808: @cindex locals, default type
                   8809: A local without type specifier is a @code{W:} local. Both flavours of
                   8810: locals are initialized with values from the data or FP stack.
1.44      crook    8811: 
1.78      anton    8812: Currently there is no way to define locals with user-defined data
                   8813: structures, but we are working on it.
1.5       anton    8814: 
1.78      anton    8815: Gforth allows defining locals everywhere in a colon definition. This
                   8816: poses the following questions:
1.5       anton    8817: 
1.78      anton    8818: @menu
                   8819: * Where are locals visible by name?::  
                   8820: * How long do locals live?::    
                   8821: * Locals programming style::    
                   8822: * Locals implementation::       
                   8823: @end menu
1.44      crook    8824: 
1.78      anton    8825: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   8826: @subsubsection Where are locals visible by name?
                   8827: @cindex locals visibility
                   8828: @cindex visibility of locals
                   8829: @cindex scope of locals
1.5       anton    8830: 
1.78      anton    8831: Basically, the answer is that locals are visible where you would expect
                   8832: it in block-structured languages, and sometimes a little longer. If you
                   8833: want to restrict the scope of a local, enclose its definition in
                   8834: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    8835: 
                   8836: 
1.78      anton    8837: doc-scope
                   8838: doc-endscope
1.5       anton    8839: 
                   8840: 
1.78      anton    8841: These words behave like control structure words, so you can use them
                   8842: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   8843: arbitrary ways.
1.77      anton    8844: 
1.78      anton    8845: If you want a more exact answer to the visibility question, here's the
                   8846: basic principle: A local is visible in all places that can only be
                   8847: reached through the definition of the local@footnote{In compiler
                   8848: construction terminology, all places dominated by the definition of the
                   8849: local.}. In other words, it is not visible in places that can be reached
                   8850: without going through the definition of the local. E.g., locals defined
                   8851: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   8852: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   8853: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77      anton    8854: 
1.78      anton    8855: The reasoning behind this solution is: We want to have the locals
                   8856: visible as long as it is meaningful. The user can always make the
                   8857: visibility shorter by using explicit scoping. In a place that can
                   8858: only be reached through the definition of a local, the meaning of a
                   8859: local name is clear. In other places it is not: How is the local
                   8860: initialized at the control flow path that does not contain the
                   8861: definition? Which local is meant, if the same name is defined twice in
                   8862: two independent control flow paths?
1.77      anton    8863: 
1.78      anton    8864: This should be enough detail for nearly all users, so you can skip the
                   8865: rest of this section. If you really must know all the gory details and
                   8866: options, read on.
1.77      anton    8867: 
1.78      anton    8868: In order to implement this rule, the compiler has to know which places
                   8869: are unreachable. It knows this automatically after @code{AHEAD},
                   8870: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   8871: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   8872: compiler that the control flow never reaches that place. If
                   8873: @code{UNREACHABLE} is not used where it could, the only consequence is
                   8874: that the visibility of some locals is more limited than the rule above
                   8875: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   8876: lie to the compiler), buggy code will be produced.
1.77      anton    8877: 
1.5       anton    8878: 
1.78      anton    8879: doc-unreachable
1.5       anton    8880: 
1.23      crook    8881: 
1.78      anton    8882: Another problem with this rule is that at @code{BEGIN}, the compiler
                   8883: does not know which locals will be visible on the incoming
                   8884: back-edge. All problems discussed in the following are due to this
                   8885: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   8886: loops as examples; the discussion also applies to @code{?DO} and other
                   8887: loops). Perhaps the most insidious example is:
1.26      crook    8888: @example
1.78      anton    8889: AHEAD
                   8890: BEGIN
                   8891:   x
                   8892: [ 1 CS-ROLL ] THEN
                   8893:   @{ x @}
                   8894:   ...
                   8895: UNTIL
1.26      crook    8896: @end example
1.23      crook    8897: 
1.78      anton    8898: This should be legal according to the visibility rule. The use of
                   8899: @code{x} can only be reached through the definition; but that appears
                   8900: textually below the use.
                   8901: 
                   8902: From this example it is clear that the visibility rules cannot be fully
                   8903: implemented without major headaches. Our implementation treats common
                   8904: cases as advertised and the exceptions are treated in a safe way: The
                   8905: compiler makes a reasonable guess about the locals visible after a
                   8906: @code{BEGIN}; if it is too pessimistic, the
                   8907: user will get a spurious error about the local not being defined; if the
                   8908: compiler is too optimistic, it will notice this later and issue a
                   8909: warning. In the case above the compiler would complain about @code{x}
                   8910: being undefined at its use. You can see from the obscure examples in
                   8911: this section that it takes quite unusual control structures to get the
                   8912: compiler into trouble, and even then it will often do fine.
1.23      crook    8913: 
1.78      anton    8914: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   8915: is that all locals visible before the @code{BEGIN} will also be
                   8916: visible after the @code{BEGIN}. This guess is valid for all loops that
                   8917: are entered only through the @code{BEGIN}, in particular, for normal
                   8918: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   8919: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   8920: compiler. When the branch to the @code{BEGIN} is finally generated by
                   8921: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   8922: warns the user if it was too optimistic:
1.26      crook    8923: @example
1.78      anton    8924: IF
                   8925:   @{ x @}
                   8926: BEGIN
                   8927:   \ x ? 
                   8928: [ 1 cs-roll ] THEN
                   8929:   ...
                   8930: UNTIL
1.26      crook    8931: @end example
1.23      crook    8932: 
1.78      anton    8933: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   8934: optimistically assumes that it lives until the @code{THEN}. It notices
                   8935: this difference when it compiles the @code{UNTIL} and issues a
                   8936: warning. The user can avoid the warning, and make sure that @code{x}
                   8937: is not used in the wrong area by using explicit scoping:
                   8938: @example
                   8939: IF
                   8940:   SCOPE
                   8941:   @{ x @}
                   8942:   ENDSCOPE
                   8943: BEGIN
                   8944: [ 1 cs-roll ] THEN
                   8945:   ...
                   8946: UNTIL
                   8947: @end example
1.23      crook    8948: 
1.78      anton    8949: Since the guess is optimistic, there will be no spurious error messages
                   8950: about undefined locals.
1.44      crook    8951: 
1.78      anton    8952: If the @code{BEGIN} is not reachable from above (e.g., after
                   8953: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   8954: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   8955: defined later. Therefore, the compiler assumes that no locals are
                   8956: visible after the @code{BEGIN}. However, the user can use
                   8957: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   8958: visible at the BEGIN as at the point where the top control-flow stack
                   8959: item was created.
1.23      crook    8960: 
1.44      crook    8961: 
1.78      anton    8962: doc-assume-live
1.26      crook    8963: 
1.23      crook    8964: 
1.78      anton    8965: @noindent
                   8966: E.g.,
                   8967: @example
                   8968: @{ x @}
                   8969: AHEAD
                   8970: ASSUME-LIVE
                   8971: BEGIN
                   8972:   x
                   8973: [ 1 CS-ROLL ] THEN
                   8974:   ...
                   8975: UNTIL
                   8976: @end example
1.44      crook    8977: 
1.78      anton    8978: Other cases where the locals are defined before the @code{BEGIN} can be
                   8979: handled by inserting an appropriate @code{CS-ROLL} before the
                   8980: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   8981: behind the @code{ASSUME-LIVE}).
1.23      crook    8982: 
1.78      anton    8983: Cases where locals are defined after the @code{BEGIN} (but should be
                   8984: visible immediately after the @code{BEGIN}) can only be handled by
                   8985: rearranging the loop. E.g., the ``most insidious'' example above can be
                   8986: arranged into:
                   8987: @example
                   8988: BEGIN
                   8989:   @{ x @}
                   8990:   ... 0=
                   8991: WHILE
                   8992:   x
                   8993: REPEAT
                   8994: @end example
1.44      crook    8995: 
1.78      anton    8996: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
                   8997: @subsubsection How long do locals live?
                   8998: @cindex locals lifetime
                   8999: @cindex lifetime of locals
1.23      crook    9000: 
1.78      anton    9001: The right answer for the lifetime question would be: A local lives at
                   9002: least as long as it can be accessed. For a value-flavoured local this
                   9003: means: until the end of its visibility. However, a variable-flavoured
                   9004: local could be accessed through its address far beyond its visibility
                   9005: scope. Ultimately, this would mean that such locals would have to be
                   9006: garbage collected. Since this entails un-Forth-like implementation
                   9007: complexities, I adopted the same cowardly solution as some other
                   9008: languages (e.g., C): The local lives only as long as it is visible;
                   9009: afterwards its address is invalid (and programs that access it
                   9010: afterwards are erroneous).
1.23      crook    9011: 
1.78      anton    9012: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
                   9013: @subsubsection Locals programming style
                   9014: @cindex locals programming style
                   9015: @cindex programming style, locals
1.23      crook    9016: 
1.78      anton    9017: The freedom to define locals anywhere has the potential to change
                   9018: programming styles dramatically. In particular, the need to use the
                   9019: return stack for intermediate storage vanishes. Moreover, all stack
                   9020: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9021: determined arguments) can be eliminated: If the stack items are in the
                   9022: wrong order, just write a locals definition for all of them; then
                   9023: write the items in the order you want.
1.23      crook    9024: 
1.78      anton    9025: This seems a little far-fetched and eliminating stack manipulations is
                   9026: unlikely to become a conscious programming objective. Still, the number
                   9027: of stack manipulations will be reduced dramatically if local variables
                   9028: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
                   9029: a traditional implementation of @code{max}).
1.23      crook    9030: 
1.78      anton    9031: This shows one potential benefit of locals: making Forth programs more
                   9032: readable. Of course, this benefit will only be realized if the
                   9033: programmers continue to honour the principle of factoring instead of
                   9034: using the added latitude to make the words longer.
1.23      crook    9035: 
1.78      anton    9036: @cindex single-assignment style for locals
                   9037: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9038: every value-flavoured local has only a single assignment and many
                   9039: advantages of functional languages apply to Forth. I.e., programs are
                   9040: easier to analyse, to optimize and to read: It is clear from the
                   9041: definition what the local stands for, it does not turn into something
                   9042: different later.
1.23      crook    9043: 
1.78      anton    9044: E.g., a definition using @code{TO} might look like this:
                   9045: @example
                   9046: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9047:  u1 u2 min 0
                   9048:  ?do
                   9049:    addr1 c@@ addr2 c@@ -
                   9050:    ?dup-if
                   9051:      unloop exit
                   9052:    then
                   9053:    addr1 char+ TO addr1
                   9054:    addr2 char+ TO addr2
                   9055:  loop
                   9056:  u1 u2 - ;
1.26      crook    9057: @end example
1.78      anton    9058: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9059: every loop iteration. @code{strcmp} is a typical example of the
                   9060: readability problems of using @code{TO}. When you start reading
                   9061: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9062: string. Only near the end of the loop you realize that it is something
                   9063: else.
1.23      crook    9064: 
1.78      anton    9065: This can be avoided by defining two locals at the start of the loop that
                   9066: are initialized with the right value for the current iteration.
                   9067: @example
                   9068: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9069:  addr1 addr2
                   9070:  u1 u2 min 0 
                   9071:  ?do @{ s1 s2 @}
                   9072:    s1 c@@ s2 c@@ -
                   9073:    ?dup-if
                   9074:      unloop exit
                   9075:    then
                   9076:    s1 char+ s2 char+
                   9077:  loop
                   9078:  2drop
                   9079:  u1 u2 - ;
                   9080: @end example
                   9081: Here it is clear from the start that @code{s1} has a different value
                   9082: in every loop iteration.
1.23      crook    9083: 
1.78      anton    9084: @node Locals implementation,  , Locals programming style, Gforth locals
                   9085: @subsubsection Locals implementation
                   9086: @cindex locals implementation
                   9087: @cindex implementation of locals
1.23      crook    9088: 
1.78      anton    9089: @cindex locals stack
                   9090: Gforth uses an extra locals stack. The most compelling reason for
                   9091: this is that the return stack is not float-aligned; using an extra stack
                   9092: also eliminates the problems and restrictions of using the return stack
                   9093: as locals stack. Like the other stacks, the locals stack grows toward
                   9094: lower addresses. A few primitives allow an efficient implementation:
                   9095: 
                   9096: 
                   9097: doc-@local#
                   9098: doc-f@local#
                   9099: doc-laddr#
                   9100: doc-lp+!#
                   9101: doc-lp!
                   9102: doc->l
                   9103: doc-f>l
                   9104: 
                   9105: 
                   9106: In addition to these primitives, some specializations of these
                   9107: primitives for commonly occurring inline arguments are provided for
                   9108: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9109: @code{@@local#} for the inline argument 0. The following compiling words
                   9110: compile the right specialized version, or the general version, as
                   9111: appropriate:
1.23      crook    9112: 
1.5       anton    9113: 
1.78      anton    9114: doc-compile-@local
                   9115: doc-compile-f@local
                   9116: doc-compile-lp+!
1.5       anton    9117: 
                   9118: 
1.78      anton    9119: Combinations of conditional branches and @code{lp+!#} like
                   9120: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9121: is taken) are provided for efficiency and correctness in loops.
1.5       anton    9122: 
1.78      anton    9123: A special area in the dictionary space is reserved for keeping the
                   9124: local variable names. @code{@{} switches the dictionary pointer to this
                   9125: area and @code{@}} switches it back and generates the locals
                   9126: initializing code. @code{W:} etc.@ are normal defining words. This
                   9127: special area is cleared at the start of every colon definition.
1.5       anton    9128: 
1.78      anton    9129: @cindex word list for defining locals
                   9130: A special feature of Gforth's dictionary is used to implement the
                   9131: definition of locals without type specifiers: every word list (aka
                   9132: vocabulary) has its own methods for searching
                   9133: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   9134: with a special search method: When it is searched for a word, it
                   9135: actually creates that word using @code{W:}. @code{@{} changes the search
                   9136: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   9137: and then the word list for defining locals without type specifiers.
1.5       anton    9138: 
1.78      anton    9139: The lifetime rules support a stack discipline within a colon
                   9140: definition: The lifetime of a local is either nested with other locals
                   9141: lifetimes or it does not overlap them.
1.23      crook    9142: 
1.78      anton    9143: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   9144: pointer manipulation is generated. Between control structure words
                   9145: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   9146: is the simplest of the other three control flow words. It has to
                   9147: restore the locals stack depth of the corresponding @code{BEGIN}
                   9148: before branching. The code looks like this:
                   9149: @format
                   9150: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   9151: @code{branch} <begin>
                   9152: @end format
1.26      crook    9153: 
1.78      anton    9154: @code{UNTIL} is a little more complicated: If it branches back, it
                   9155: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   9156: the locals stack must not be changed. The compiler generates the
                   9157: following code:
                   9158: @format
                   9159: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   9160: @end format
                   9161: The locals stack pointer is only adjusted if the branch is taken.
1.44      crook    9162: 
1.78      anton    9163: @code{THEN} can produce somewhat inefficient code:
                   9164: @format
                   9165: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   9166: <orig target>:
                   9167: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   9168: @end format
                   9169: The second @code{lp+!#} adjusts the locals stack pointer from the
                   9170: level at the @i{orig} point to the level after the @code{THEN}. The
                   9171: first @code{lp+!#} adjusts the locals stack pointer from the current
                   9172: level to the level at the orig point, so the complete effect is an
                   9173: adjustment from the current level to the right level after the
                   9174: @code{THEN}.
1.26      crook    9175: 
1.78      anton    9176: @cindex locals information on the control-flow stack
                   9177: @cindex control-flow stack items, locals information
                   9178: In a conventional Forth implementation a dest control-flow stack entry
                   9179: is just the target address and an orig entry is just the address to be
                   9180: patched. Our locals implementation adds a word list to every orig or dest
                   9181: item. It is the list of locals visible (or assumed visible) at the point
                   9182: described by the entry. Our implementation also adds a tag to identify
                   9183: the kind of entry, in particular to differentiate between live and dead
                   9184: (reachable and unreachable) orig entries.
1.26      crook    9185: 
1.78      anton    9186: A few unusual operations have to be performed on locals word lists:
1.44      crook    9187: 
1.5       anton    9188: 
1.78      anton    9189: doc-common-list
                   9190: doc-sub-list?
                   9191: doc-list-size
1.52      anton    9192: 
                   9193: 
1.78      anton    9194: Several features of our locals word list implementation make these
                   9195: operations easy to implement: The locals word lists are organised as
                   9196: linked lists; the tails of these lists are shared, if the lists
                   9197: contain some of the same locals; and the address of a name is greater
                   9198: than the address of the names behind it in the list.
1.5       anton    9199: 
1.78      anton    9200: Another important implementation detail is the variable
                   9201: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   9202: determine if they can be reached directly or only through the branch
                   9203: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   9204: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   9205: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5       anton    9206: 
1.78      anton    9207: Counted loops are similar to other loops in most respects, but
                   9208: @code{LEAVE} requires special attention: It performs basically the same
                   9209: service as @code{AHEAD}, but it does not create a control-flow stack
                   9210: entry. Therefore the information has to be stored elsewhere;
                   9211: traditionally, the information was stored in the target fields of the
                   9212: branches created by the @code{LEAVE}s, by organizing these fields into a
                   9213: linked list. Unfortunately, this clever trick does not provide enough
                   9214: space for storing our extended control flow information. Therefore, we
                   9215: introduce another stack, the leave stack. It contains the control-flow
                   9216: stack entries for all unresolved @code{LEAVE}s.
1.44      crook    9217: 
1.78      anton    9218: Local names are kept until the end of the colon definition, even if
                   9219: they are no longer visible in any control-flow path. In a few cases
                   9220: this may lead to increased space needs for the locals name area, but
                   9221: usually less than reclaiming this space would cost in code size.
1.5       anton    9222: 
1.44      crook    9223: 
1.78      anton    9224: @node ANS Forth locals,  , Gforth locals, Locals
                   9225: @subsection ANS Forth locals
                   9226: @cindex locals, ANS Forth style
1.5       anton    9227: 
1.78      anton    9228: The ANS Forth locals wordset does not define a syntax for locals, but
                   9229: words that make it possible to define various syntaxes. One of the
                   9230: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   9231: wordset, i.e.:
1.29      crook    9232: 
                   9233: @example
1.78      anton    9234: @{ local1 local2 ... -- comment @}
                   9235: @end example
                   9236: @noindent
                   9237: or
                   9238: @example
                   9239: @{ local1 local2 ... @}
1.29      crook    9240: @end example
                   9241: 
1.78      anton    9242: The order of the locals corresponds to the order in a stack comment. The
                   9243: restrictions are:
1.5       anton    9244: 
1.78      anton    9245: @itemize @bullet
                   9246: @item
                   9247: Locals can only be cell-sized values (no type specifiers are allowed).
                   9248: @item
                   9249: Locals can be defined only outside control structures.
                   9250: @item
                   9251: Locals can interfere with explicit usage of the return stack. For the
                   9252: exact (and long) rules, see the standard. If you don't use return stack
                   9253: accessing words in a definition using locals, you will be all right. The
                   9254: purpose of this rule is to make locals implementation on the return
                   9255: stack easier.
                   9256: @item
                   9257: The whole definition must be in one line.
                   9258: @end itemize
1.5       anton    9259: 
1.78      anton    9260: Locals defined in ANS Forth behave like @code{VALUE}s
                   9261: (@pxref{Values}). I.e., they are initialized from the stack. Using their
                   9262: name produces their value. Their value can be changed using @code{TO}.
1.77      anton    9263: 
1.78      anton    9264: Since the syntax above is supported by Gforth directly, you need not do
                   9265: anything to use it. If you want to port a program using this syntax to
                   9266: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   9267: syntax on the other system.
1.5       anton    9268: 
1.78      anton    9269: Note that a syntax shown in the standard, section A.13 looks
                   9270: similar, but is quite different in having the order of locals
                   9271: reversed. Beware!
1.5       anton    9272: 
1.78      anton    9273: The ANS Forth locals wordset itself consists of one word:
1.5       anton    9274: 
1.78      anton    9275: doc-(local)
1.5       anton    9276: 
1.78      anton    9277: The ANS Forth locals extension wordset defines a syntax using
                   9278: @code{locals|}, but it is so awful that we strongly recommend not to use
                   9279: it. We have implemented this syntax to make porting to Gforth easy, but
                   9280: do not document it here. The problem with this syntax is that the locals
                   9281: are defined in an order reversed with respect to the standard stack
                   9282: comment notation, making programs harder to read, and easier to misread
                   9283: and miswrite. The only merit of this syntax is that it is easy to
                   9284: implement using the ANS Forth locals wordset.
1.53      anton    9285: 
                   9286: 
1.78      anton    9287: @c ----------------------------------------------------------
                   9288: @node Structures, Object-oriented Forth, Locals, Words
                   9289: @section  Structures
                   9290: @cindex structures
                   9291: @cindex records
1.53      anton    9292: 
1.78      anton    9293: This section presents the structure package that comes with Gforth. A
                   9294: version of the package implemented in ANS Forth is available in
                   9295: @file{compat/struct.fs}. This package was inspired by a posting on
                   9296: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   9297: possibly John Hayes). A version of this section has been published in
                   9298: M. Anton Ertl,
                   9299: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
                   9300: Another Forth Structures Package}, Forth Dimensions 19(3), pages
                   9301: 13--16. Marcel Hendrix provided helpful comments.
1.53      anton    9302: 
1.78      anton    9303: @menu
                   9304: * Why explicit structure support?::  
                   9305: * Structure Usage::             
                   9306: * Structure Naming Convention::  
                   9307: * Structure Implementation::    
                   9308: * Structure Glossary::          
                   9309: @end menu
1.55      anton    9310: 
1.78      anton    9311: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   9312: @subsection Why explicit structure support?
1.53      anton    9313: 
1.78      anton    9314: @cindex address arithmetic for structures
                   9315: @cindex structures using address arithmetic
                   9316: If we want to use a structure containing several fields, we could simply
                   9317: reserve memory for it, and access the fields using address arithmetic
                   9318: (@pxref{Address arithmetic}). As an example, consider a structure with
                   9319: the following fields
1.57      anton    9320: 
1.78      anton    9321: @table @code
                   9322: @item a
                   9323: is a float
                   9324: @item b
                   9325: is a cell
                   9326: @item c
                   9327: is a float
                   9328: @end table
1.57      anton    9329: 
1.78      anton    9330: Given the (float-aligned) base address of the structure we get the
                   9331: address of the field
1.52      anton    9332: 
1.78      anton    9333: @table @code
                   9334: @item a
                   9335: without doing anything further.
                   9336: @item b
                   9337: with @code{float+}
                   9338: @item c
                   9339: with @code{float+ cell+ faligned}
                   9340: @end table
1.52      anton    9341: 
1.78      anton    9342: It is easy to see that this can become quite tiring. 
1.52      anton    9343: 
1.78      anton    9344: Moreover, it is not very readable, because seeing a
                   9345: @code{cell+} tells us neither which kind of structure is
                   9346: accessed nor what field is accessed; we have to somehow infer the kind
                   9347: of structure, and then look up in the documentation, which field of
                   9348: that structure corresponds to that offset.
1.53      anton    9349: 
1.78      anton    9350: Finally, this kind of address arithmetic also causes maintenance
                   9351: troubles: If you add or delete a field somewhere in the middle of the
                   9352: structure, you have to find and change all computations for the fields
                   9353: afterwards.
1.52      anton    9354: 
1.78      anton    9355: So, instead of using @code{cell+} and friends directly, how
                   9356: about storing the offsets in constants:
1.52      anton    9357: 
1.78      anton    9358: @example
                   9359: 0 constant a-offset
                   9360: 0 float+ constant b-offset
                   9361: 0 float+ cell+ faligned c-offset
                   9362: @end example
1.64      pazsan   9363: 
1.78      anton    9364: Now we can get the address of field @code{x} with @code{x-offset
                   9365: +}. This is much better in all respects. Of course, you still
                   9366: have to change all later offset definitions if you add a field. You can
                   9367: fix this by declaring the offsets in the following way:
1.57      anton    9368: 
1.78      anton    9369: @example
                   9370: 0 constant a-offset
                   9371: a-offset float+ constant b-offset
                   9372: b-offset cell+ faligned constant c-offset
                   9373: @end example
1.57      anton    9374: 
1.78      anton    9375: Since we always use the offsets with @code{+}, we could use a defining
                   9376: word @code{cfield} that includes the @code{+} in the action of the
                   9377: defined word:
1.64      pazsan   9378: 
1.78      anton    9379: @example
                   9380: : cfield ( n "name" -- )
                   9381:     create ,
                   9382: does> ( name execution: addr1 -- addr2 )
                   9383:     @@ + ;
1.64      pazsan   9384: 
1.78      anton    9385: 0 cfield a
                   9386: 0 a float+ cfield b
                   9387: 0 b cell+ faligned cfield c
                   9388: @end example
1.64      pazsan   9389: 
1.78      anton    9390: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64      pazsan   9391: 
1.78      anton    9392: The structure field words now can be used quite nicely. However,
                   9393: their definition is still a bit cumbersome: We have to repeat the
                   9394: name, the information about size and alignment is distributed before
                   9395: and after the field definitions etc.  The structure package presented
                   9396: here addresses these problems.
1.64      pazsan   9397: 
1.78      anton    9398: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   9399: @subsection Structure Usage
                   9400: @cindex structure usage
1.57      anton    9401: 
1.78      anton    9402: @cindex @code{field} usage
                   9403: @cindex @code{struct} usage
                   9404: @cindex @code{end-struct} usage
                   9405: You can define a structure for a (data-less) linked list with:
1.57      anton    9406: @example
1.78      anton    9407: struct
                   9408:     cell% field list-next
                   9409: end-struct list%
1.57      anton    9410: @end example
                   9411: 
1.78      anton    9412: With the address of the list node on the stack, you can compute the
                   9413: address of the field that contains the address of the next node with
                   9414: @code{list-next}. E.g., you can determine the length of a list
                   9415: with:
1.57      anton    9416: 
                   9417: @example
1.78      anton    9418: : list-length ( list -- n )
                   9419: \ "list" is a pointer to the first element of a linked list
                   9420: \ "n" is the length of the list
                   9421:     0 BEGIN ( list1 n1 )
                   9422:         over
                   9423:     WHILE ( list1 n1 )
                   9424:         1+ swap list-next @@ swap
                   9425:     REPEAT
                   9426:     nip ;
1.57      anton    9427: @end example
                   9428: 
1.78      anton    9429: You can reserve memory for a list node in the dictionary with
                   9430: @code{list% %allot}, which leaves the address of the list node on the
                   9431: stack. For the equivalent allocation on the heap you can use @code{list%
                   9432: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   9433: use @code{list% %allocate}). You can get the the size of a list
                   9434: node with @code{list% %size} and its alignment with @code{list%
                   9435: %alignment}.
                   9436: 
                   9437: Note that in ANS Forth the body of a @code{create}d word is
                   9438: @code{aligned} but not necessarily @code{faligned};
                   9439: therefore, if you do a:
1.57      anton    9440: 
                   9441: @example
1.78      anton    9442: create @emph{name} foo% %allot drop
1.57      anton    9443: @end example
                   9444: 
1.78      anton    9445: @noindent
                   9446: then the memory alloted for @code{foo%} is guaranteed to start at the
                   9447: body of @code{@emph{name}} only if @code{foo%} contains only character,
                   9448: cell and double fields.  Therefore, if your structure contains floats,
                   9449: better use
1.57      anton    9450: 
                   9451: @example
1.78      anton    9452: foo% %allot constant @emph{name}
1.57      anton    9453: @end example
                   9454: 
1.78      anton    9455: @cindex structures containing structures
                   9456: You can include a structure @code{foo%} as a field of
                   9457: another structure, like this:
1.65      anton    9458: @example
1.78      anton    9459: struct
                   9460: ...
                   9461:     foo% field ...
                   9462: ...
                   9463: end-struct ...
1.65      anton    9464: @end example
1.52      anton    9465: 
1.78      anton    9466: @cindex structure extension
                   9467: @cindex extended records
                   9468: Instead of starting with an empty structure, you can extend an
                   9469: existing structure. E.g., a plain linked list without data, as defined
                   9470: above, is hardly useful; You can extend it to a linked list of integers,
                   9471: like this:@footnote{This feature is also known as @emph{extended
                   9472: records}. It is the main innovation in the Oberon language; in other
                   9473: words, adding this feature to Modula-2 led Wirth to create a new
                   9474: language, write a new compiler etc.  Adding this feature to Forth just
                   9475: required a few lines of code.}
1.52      anton    9476: 
1.78      anton    9477: @example
                   9478: list%
                   9479:     cell% field intlist-int
                   9480: end-struct intlist%
                   9481: @end example
1.55      anton    9482: 
1.78      anton    9483: @code{intlist%} is a structure with two fields:
                   9484: @code{list-next} and @code{intlist-int}.
1.55      anton    9485: 
1.78      anton    9486: @cindex structures containing arrays
                   9487: You can specify an array type containing @emph{n} elements of
                   9488: type @code{foo%} like this:
1.55      anton    9489: 
                   9490: @example
1.78      anton    9491: foo% @emph{n} *
1.56      anton    9492: @end example
1.55      anton    9493: 
1.78      anton    9494: You can use this array type in any place where you can use a normal
                   9495: type, e.g., when defining a @code{field}, or with
                   9496: @code{%allot}.
                   9497: 
                   9498: @cindex first field optimization
                   9499: The first field is at the base address of a structure and the word for
                   9500: this field (e.g., @code{list-next}) actually does not change the address
                   9501: on the stack. You may be tempted to leave it away in the interest of
                   9502: run-time and space efficiency. This is not necessary, because the
                   9503: structure package optimizes this case: If you compile a first-field
                   9504: words, no code is generated. So, in the interest of readability and
                   9505: maintainability you should include the word for the field when accessing
                   9506: the field.
1.52      anton    9507: 
                   9508: 
1.78      anton    9509: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   9510: @subsection Structure Naming Convention
                   9511: @cindex structure naming convention
1.52      anton    9512: 
1.78      anton    9513: The field names that come to (my) mind are often quite generic, and,
                   9514: if used, would cause frequent name clashes. E.g., many structures
                   9515: probably contain a @code{counter} field. The structure names
                   9516: that come to (my) mind are often also the logical choice for the names
                   9517: of words that create such a structure.
1.52      anton    9518: 
1.78      anton    9519: Therefore, I have adopted the following naming conventions: 
1.52      anton    9520: 
1.78      anton    9521: @itemize @bullet
                   9522: @cindex field naming convention
                   9523: @item
                   9524: The names of fields are of the form
                   9525: @code{@emph{struct}-@emph{field}}, where
                   9526: @code{@emph{struct}} is the basic name of the structure, and
                   9527: @code{@emph{field}} is the basic name of the field. You can
                   9528: think of field words as converting the (address of the)
                   9529: structure into the (address of the) field.
1.52      anton    9530: 
1.78      anton    9531: @cindex structure naming convention
                   9532: @item
                   9533: The names of structures are of the form
                   9534: @code{@emph{struct}%}, where
                   9535: @code{@emph{struct}} is the basic name of the structure.
                   9536: @end itemize
1.52      anton    9537: 
1.78      anton    9538: This naming convention does not work that well for fields of extended
                   9539: structures; e.g., the integer list structure has a field
                   9540: @code{intlist-int}, but has @code{list-next}, not
                   9541: @code{intlist-next}.
1.53      anton    9542: 
1.78      anton    9543: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   9544: @subsection Structure Implementation
                   9545: @cindex structure implementation
                   9546: @cindex implementation of structures
1.52      anton    9547: 
1.78      anton    9548: The central idea in the implementation is to pass the data about the
                   9549: structure being built on the stack, not in some global
                   9550: variable. Everything else falls into place naturally once this design
                   9551: decision is made.
1.53      anton    9552: 
1.78      anton    9553: The type description on the stack is of the form @emph{align
                   9554: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   9555: very simple.
1.53      anton    9556: 
1.78      anton    9557: @code{field} is a defining word that uses @code{Create}
                   9558: and @code{DOES>}. The body of the field contains the offset
                   9559: of the field, and the normal @code{DOES>} action is simply:
1.53      anton    9560: 
                   9561: @example
1.78      anton    9562: @@ +
1.53      anton    9563: @end example
                   9564: 
1.78      anton    9565: @noindent
                   9566: i.e., add the offset to the address, giving the stack effect
                   9567: @i{addr1 -- addr2} for a field.
                   9568: 
                   9569: @cindex first field optimization, implementation
                   9570: This simple structure is slightly complicated by the optimization
                   9571: for fields with offset 0, which requires a different
                   9572: @code{DOES>}-part (because we cannot rely on there being
                   9573: something on the stack if such a field is invoked during
                   9574: compilation). Therefore, we put the different @code{DOES>}-parts
                   9575: in separate words, and decide which one to invoke based on the
                   9576: offset. For a zero offset, the field is basically a noop; it is
                   9577: immediate, and therefore no code is generated when it is compiled.
1.53      anton    9578: 
1.78      anton    9579: @node Structure Glossary,  , Structure Implementation, Structures
                   9580: @subsection Structure Glossary
                   9581: @cindex structure glossary
1.53      anton    9582: 
1.5       anton    9583: 
1.78      anton    9584: doc-%align
                   9585: doc-%alignment
                   9586: doc-%alloc
                   9587: doc-%allocate
                   9588: doc-%allot
                   9589: doc-cell%
                   9590: doc-char%
                   9591: doc-dfloat%
                   9592: doc-double%
                   9593: doc-end-struct
                   9594: doc-field
                   9595: doc-float%
                   9596: doc-naligned
                   9597: doc-sfloat%
                   9598: doc-%size
                   9599: doc-struct
1.54      anton    9600: 
                   9601: 
1.26      crook    9602: @c -------------------------------------------------------------
1.78      anton    9603: @node Object-oriented Forth, Programming Tools, Structures, Words
                   9604: @section Object-oriented Forth
                   9605: 
                   9606: Gforth comes with three packages for object-oriented programming:
                   9607: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   9608: is preloaded, so you have to @code{include} them before use. The most
                   9609: important differences between these packages (and others) are discussed
                   9610: in @ref{Comparison with other object models}. All packages are written
                   9611: in ANS Forth and can be used with any other ANS Forth.
1.5       anton    9612: 
1.78      anton    9613: @menu
                   9614: * Why object-oriented programming?::  
                   9615: * Object-Oriented Terminology::  
                   9616: * Objects::                     
                   9617: * OOF::                         
                   9618: * Mini-OOF::                    
                   9619: * Comparison with other object models::  
                   9620: @end menu
1.5       anton    9621: 
1.78      anton    9622: @c ----------------------------------------------------------------
                   9623: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   9624: @subsection Why object-oriented programming?
                   9625: @cindex object-oriented programming motivation
                   9626: @cindex motivation for object-oriented programming
1.44      crook    9627: 
1.78      anton    9628: Often we have to deal with several data structures (@emph{objects}),
                   9629: that have to be treated similarly in some respects, but differently in
                   9630: others. Graphical objects are the textbook example: circles, triangles,
                   9631: dinosaurs, icons, and others, and we may want to add more during program
                   9632: development. We want to apply some operations to any graphical object,
                   9633: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   9634: has to do something different for every kind of object.
                   9635: @comment TODO add some other operations eg perimeter, area
                   9636: @comment and tie in to concrete examples later..
1.5       anton    9637: 
1.78      anton    9638: We could implement @code{draw} as a big @code{CASE}
                   9639: control structure that executes the appropriate code depending on the
                   9640: kind of object to be drawn. This would be not be very elegant, and,
                   9641: moreover, we would have to change @code{draw} every time we add
                   9642: a new kind of graphical object (say, a spaceship).
1.44      crook    9643: 
1.78      anton    9644: What we would rather do is: When defining spaceships, we would tell
                   9645: the system: ``Here's how you @code{draw} a spaceship; you figure
                   9646: out the rest''.
1.5       anton    9647: 
1.78      anton    9648: This is the problem that all systems solve that (rightfully) call
                   9649: themselves object-oriented; the object-oriented packages presented here
                   9650: solve this problem (and not much else).
                   9651: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44      crook    9652: 
1.78      anton    9653: @c ------------------------------------------------------------------------
                   9654: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   9655: @subsection Object-Oriented Terminology
                   9656: @cindex object-oriented terminology
                   9657: @cindex terminology for object-oriented programming
1.5       anton    9658: 
1.78      anton    9659: This section is mainly for reference, so you don't have to understand
                   9660: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   9661: short:
1.44      crook    9662: 
1.78      anton    9663: @table @emph
                   9664: @cindex class
                   9665: @item class
                   9666: a data structure definition with some extras.
1.5       anton    9667: 
1.78      anton    9668: @cindex object
                   9669: @item object
                   9670: an instance of the data structure described by the class definition.
1.5       anton    9671: 
1.78      anton    9672: @cindex instance variables
                   9673: @item instance variables
                   9674: fields of the data structure.
1.5       anton    9675: 
1.78      anton    9676: @cindex selector
                   9677: @cindex method selector
                   9678: @cindex virtual function
                   9679: @item selector
                   9680: (or @emph{method selector}) a word (e.g.,
                   9681: @code{draw}) that performs an operation on a variety of data
                   9682: structures (classes). A selector describes @emph{what} operation to
                   9683: perform. In C++ terminology: a (pure) virtual function.
1.5       anton    9684: 
1.78      anton    9685: @cindex method
                   9686: @item method
                   9687: the concrete definition that performs the operation
                   9688: described by the selector for a specific class. A method specifies
                   9689: @emph{how} the operation is performed for a specific class.
1.5       anton    9690: 
1.78      anton    9691: @cindex selector invocation
                   9692: @cindex message send
                   9693: @cindex invoking a selector
                   9694: @item selector invocation
                   9695: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   9696: is used for determining which method is used. In Smalltalk terminology:
                   9697: a message (consisting of the selector and the other arguments) is sent
                   9698: to the object.
1.5       anton    9699: 
1.78      anton    9700: @cindex receiving object
                   9701: @item receiving object
                   9702: the object used for determining the method executed by a selector
                   9703: invocation. In the @file{objects.fs} model, it is the object that is on
                   9704: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   9705: the Smalltalk @emph{message} terminology.)
1.5       anton    9706: 
1.78      anton    9707: @cindex child class
                   9708: @cindex parent class
                   9709: @cindex inheritance
                   9710: @item child class
                   9711: a class that has (@emph{inherits}) all properties (instance variables,
                   9712: selectors, methods) from a @emph{parent class}. In Smalltalk
                   9713: terminology: The subclass inherits from the superclass. In C++
                   9714: terminology: The derived class inherits from the base class.
1.5       anton    9715: 
1.78      anton    9716: @end table
1.5       anton    9717: 
1.78      anton    9718: @c If you wonder about the message sending terminology, it comes from
                   9719: @c a time when each object had it's own task and objects communicated via
                   9720: @c message passing; eventually the Smalltalk developers realized that
                   9721: @c they can do most things through simple (indirect) calls. They kept the
                   9722: @c terminology.
1.5       anton    9723: 
1.78      anton    9724: @c --------------------------------------------------------------
                   9725: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   9726: @subsection The @file{objects.fs} model
                   9727: @cindex objects
                   9728: @cindex object-oriented programming
1.26      crook    9729: 
1.78      anton    9730: @cindex @file{objects.fs}
                   9731: @cindex @file{oof.fs}
1.26      crook    9732: 
1.78      anton    9733: This section describes the @file{objects.fs} package. This material also
                   9734: has been published in M. Anton Ertl,
                   9735: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
                   9736: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
                   9737: 37--43.
                   9738: @c McKewan's and Zsoter's packages
1.26      crook    9739: 
1.78      anton    9740: This section assumes that you have read @ref{Structures}.
1.5       anton    9741: 
1.78      anton    9742: The techniques on which this model is based have been used to implement
                   9743: the parser generator, Gray, and have also been used in Gforth for
                   9744: implementing the various flavours of word lists (hashed or not,
                   9745: case-sensitive or not, special-purpose word lists for locals etc.).
1.5       anton    9746: 
                   9747: 
1.26      crook    9748: @menu
1.78      anton    9749: * Properties of the Objects model::  
                   9750: * Basic Objects Usage::         
                   9751: * The Objects base class::      
                   9752: * Creating objects::            
                   9753: * Object-Oriented Programming Style::  
                   9754: * Class Binding::               
                   9755: * Method conveniences::         
                   9756: * Classes and Scoping::         
                   9757: * Dividing classes::            
                   9758: * Object Interfaces::           
                   9759: * Objects Implementation::      
                   9760: * Objects Glossary::            
1.26      crook    9761: @end menu
1.5       anton    9762: 
1.78      anton    9763: Marcel Hendrix provided helpful comments on this section.
1.5       anton    9764: 
1.78      anton    9765: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   9766: @subsubsection Properties of the @file{objects.fs} model
                   9767: @cindex @file{objects.fs} properties
1.5       anton    9768: 
1.78      anton    9769: @itemize @bullet
                   9770: @item
                   9771: It is straightforward to pass objects on the stack. Passing
                   9772: selectors on the stack is a little less convenient, but possible.
1.44      crook    9773: 
1.78      anton    9774: @item
                   9775: Objects are just data structures in memory, and are referenced by their
                   9776: address. You can create words for objects with normal defining words
                   9777: like @code{constant}. Likewise, there is no difference between instance
                   9778: variables that contain objects and those that contain other data.
1.5       anton    9779: 
1.78      anton    9780: @item
                   9781: Late binding is efficient and easy to use.
1.44      crook    9782: 
1.78      anton    9783: @item
                   9784: It avoids parsing, and thus avoids problems with state-smartness
                   9785: and reduced extensibility; for convenience there are a few parsing
                   9786: words, but they have non-parsing counterparts. There are also a few
                   9787: defining words that parse. This is hard to avoid, because all standard
                   9788: defining words parse (except @code{:noname}); however, such
                   9789: words are not as bad as many other parsing words, because they are not
                   9790: state-smart.
1.5       anton    9791: 
1.78      anton    9792: @item
                   9793: It does not try to incorporate everything. It does a few things and does
                   9794: them well (IMO). In particular, this model was not designed to support
                   9795: information hiding (although it has features that may help); you can use
                   9796: a separate package for achieving this.
1.5       anton    9797: 
1.78      anton    9798: @item
                   9799: It is layered; you don't have to learn and use all features to use this
                   9800: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   9801: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
                   9802: are optional and independent of each other.
1.5       anton    9803: 
1.78      anton    9804: @item
                   9805: An implementation in ANS Forth is available.
1.5       anton    9806: 
1.78      anton    9807: @end itemize
1.5       anton    9808: 
1.44      crook    9809: 
1.78      anton    9810: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   9811: @subsubsection Basic @file{objects.fs} Usage
                   9812: @cindex basic objects usage
                   9813: @cindex objects, basic usage
1.5       anton    9814: 
1.78      anton    9815: You can define a class for graphical objects like this:
1.44      crook    9816: 
1.78      anton    9817: @cindex @code{class} usage
                   9818: @cindex @code{end-class} usage
                   9819: @cindex @code{selector} usage
1.5       anton    9820: @example
1.78      anton    9821: object class \ "object" is the parent class
                   9822:   selector draw ( x y graphical -- )
                   9823: end-class graphical
                   9824: @end example
                   9825: 
                   9826: This code defines a class @code{graphical} with an
                   9827: operation @code{draw}.  We can perform the operation
                   9828: @code{draw} on any @code{graphical} object, e.g.:
                   9829: 
                   9830: @example
                   9831: 100 100 t-rex draw
1.26      crook    9832: @end example
1.5       anton    9833: 
1.78      anton    9834: @noindent
                   9835: where @code{t-rex} is a word (say, a constant) that produces a
                   9836: graphical object.
                   9837: 
                   9838: @comment TODO add a 2nd operation eg perimeter.. and use for
                   9839: @comment a concrete example
1.5       anton    9840: 
1.78      anton    9841: @cindex abstract class
                   9842: How do we create a graphical object? With the present definitions,
                   9843: we cannot create a useful graphical object. The class
                   9844: @code{graphical} describes graphical objects in general, but not
                   9845: any concrete graphical object type (C++ users would call it an
                   9846: @emph{abstract class}); e.g., there is no method for the selector
                   9847: @code{draw} in the class @code{graphical}.
1.5       anton    9848: 
1.78      anton    9849: For concrete graphical objects, we define child classes of the
                   9850: class @code{graphical}, e.g.:
1.5       anton    9851: 
1.78      anton    9852: @cindex @code{overrides} usage
                   9853: @cindex @code{field} usage in class definition
1.26      crook    9854: @example
1.78      anton    9855: graphical class \ "graphical" is the parent class
                   9856:   cell% field circle-radius
1.5       anton    9857: 
1.78      anton    9858: :noname ( x y circle -- )
                   9859:   circle-radius @@ draw-circle ;
                   9860: overrides draw
1.5       anton    9861: 
1.78      anton    9862: :noname ( n-radius circle -- )
                   9863:   circle-radius ! ;
                   9864: overrides construct
1.5       anton    9865: 
1.78      anton    9866: end-class circle
                   9867: @end example
1.44      crook    9868: 
1.78      anton    9869: Here we define a class @code{circle} as a child of @code{graphical},
                   9870: with field @code{circle-radius} (which behaves just like a field
                   9871: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   9872: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   9873: defined in @code{object}, the parent class of @code{graphical}).
1.5       anton    9874: 
1.78      anton    9875: Now we can create a circle on the heap (i.e.,
                   9876: @code{allocate}d memory) with:
1.44      crook    9877: 
1.78      anton    9878: @cindex @code{heap-new} usage
1.5       anton    9879: @example
1.78      anton    9880: 50 circle heap-new constant my-circle
1.5       anton    9881: @end example
                   9882: 
1.78      anton    9883: @noindent
                   9884: @code{heap-new} invokes @code{construct}, thus
                   9885: initializing the field @code{circle-radius} with 50. We can draw
                   9886: this new circle at (100,100) with:
1.5       anton    9887: 
                   9888: @example
1.78      anton    9889: 100 100 my-circle draw
1.5       anton    9890: @end example
                   9891: 
1.78      anton    9892: @cindex selector invocation, restrictions
                   9893: @cindex class definition, restrictions
                   9894: Note: You can only invoke a selector if the object on the TOS
                   9895: (the receiving object) belongs to the class where the selector was
                   9896: defined or one of its descendents; e.g., you can invoke
                   9897: @code{draw} only for objects belonging to @code{graphical}
                   9898: or its descendents (e.g., @code{circle}).  Immediately before
                   9899: @code{end-class}, the search order has to be the same as
                   9900: immediately after @code{class}.
                   9901: 
                   9902: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   9903: @subsubsection The @file{object.fs} base class
                   9904: @cindex @code{object} class
                   9905: 
                   9906: When you define a class, you have to specify a parent class.  So how do
                   9907: you start defining classes? There is one class available from the start:
                   9908: @code{object}. It is ancestor for all classes and so is the
                   9909: only class that has no parent. It has two selectors: @code{construct}
                   9910: and @code{print}.
                   9911: 
                   9912: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   9913: @subsubsection Creating objects
                   9914: @cindex creating objects
                   9915: @cindex object creation
                   9916: @cindex object allocation options
                   9917: 
                   9918: @cindex @code{heap-new} discussion
                   9919: @cindex @code{dict-new} discussion
                   9920: @cindex @code{construct} discussion
                   9921: You can create and initialize an object of a class on the heap with
                   9922: @code{heap-new} ( ... class -- object ) and in the dictionary
                   9923: (allocation with @code{allot}) with @code{dict-new} (
                   9924: ... class -- object ). Both words invoke @code{construct}, which
                   9925: consumes the stack items indicated by "..." above.
                   9926: 
                   9927: @cindex @code{init-object} discussion
                   9928: @cindex @code{class-inst-size} discussion
                   9929: If you want to allocate memory for an object yourself, you can get its
                   9930: alignment and size with @code{class-inst-size 2@@} ( class --
                   9931: align size ). Once you have memory for an object, you can initialize
                   9932: it with @code{init-object} ( ... class object -- );
                   9933: @code{construct} does only a part of the necessary work.
                   9934: 
                   9935: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   9936: @subsubsection Object-Oriented Programming Style
                   9937: @cindex object-oriented programming style
                   9938: @cindex programming style, object-oriented
1.5       anton    9939: 
1.78      anton    9940: This section is not exhaustive.
1.5       anton    9941: 
1.78      anton    9942: @cindex stack effects of selectors
                   9943: @cindex selectors and stack effects
                   9944: In general, it is a good idea to ensure that all methods for the
                   9945: same selector have the same stack effect: when you invoke a selector,
                   9946: you often have no idea which method will be invoked, so, unless all
                   9947: methods have the same stack effect, you will not know the stack effect
                   9948: of the selector invocation.
1.5       anton    9949: 
1.78      anton    9950: One exception to this rule is methods for the selector
                   9951: @code{construct}. We know which method is invoked, because we
                   9952: specify the class to be constructed at the same place. Actually, I
                   9953: defined @code{construct} as a selector only to give the users a
                   9954: convenient way to specify initialization. The way it is used, a
                   9955: mechanism different from selector invocation would be more natural
                   9956: (but probably would take more code and more space to explain).
1.5       anton    9957: 
1.78      anton    9958: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   9959: @subsubsection Class Binding
                   9960: @cindex class binding
                   9961: @cindex early binding
1.5       anton    9962: 
1.78      anton    9963: @cindex late binding
                   9964: Normal selector invocations determine the method at run-time depending
                   9965: on the class of the receiving object. This run-time selection is called
                   9966: @i{late binding}.
1.5       anton    9967: 
1.78      anton    9968: Sometimes it's preferable to invoke a different method. For example,
                   9969: you might want to use the simple method for @code{print}ing
                   9970: @code{object}s instead of the possibly long-winded @code{print} method
                   9971: of the receiver class. You can achieve this by replacing the invocation
                   9972: of @code{print} with:
1.5       anton    9973: 
1.78      anton    9974: @cindex @code{[bind]} usage
1.5       anton    9975: @example
1.78      anton    9976: [bind] object print
1.5       anton    9977: @end example
                   9978: 
1.78      anton    9979: @noindent
                   9980: in compiled code or:
                   9981: 
                   9982: @cindex @code{bind} usage
1.5       anton    9983: @example
1.78      anton    9984: bind object print
1.5       anton    9985: @end example
                   9986: 
1.78      anton    9987: @cindex class binding, alternative to
                   9988: @noindent
                   9989: in interpreted code. Alternatively, you can define the method with a
                   9990: name (e.g., @code{print-object}), and then invoke it through the
                   9991: name. Class binding is just a (often more convenient) way to achieve
                   9992: the same effect; it avoids name clutter and allows you to invoke
                   9993: methods directly without naming them first.
1.5       anton    9994: 
1.78      anton    9995: @cindex superclass binding
                   9996: @cindex parent class binding
                   9997: A frequent use of class binding is this: When we define a method
                   9998: for a selector, we often want the method to do what the selector does
                   9999: in the parent class, and a little more. There is a special word for
                   10000: this purpose: @code{[parent]}; @code{[parent]
                   10001: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   10002: selector}}, where @code{@emph{parent}} is the parent
                   10003: class of the current class. E.g., a method definition might look like:
1.44      crook    10004: 
1.78      anton    10005: @cindex @code{[parent]} usage
                   10006: @example
                   10007: :noname
                   10008:   dup [parent] foo \ do parent's foo on the receiving object
                   10009:   ... \ do some more
                   10010: ; overrides foo
                   10011: @end example
1.6       pazsan   10012: 
1.78      anton    10013: @cindex class binding as optimization
                   10014: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10015: March 1997), Andrew McKewan presents class binding as an optimization
                   10016: technique. I recommend not using it for this purpose unless you are in
                   10017: an emergency. Late binding is pretty fast with this model anyway, so the
                   10018: benefit of using class binding is small; the cost of using class binding
                   10019: where it is not appropriate is reduced maintainability.
1.44      crook    10020: 
1.78      anton    10021: While we are at programming style questions: You should bind
                   10022: selectors only to ancestor classes of the receiving object. E.g., say,
                   10023: you know that the receiving object is of class @code{foo} or its
                   10024: descendents; then you should bind only to @code{foo} and its
                   10025: ancestors.
1.12      anton    10026: 
1.78      anton    10027: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10028: @subsubsection Method conveniences
                   10029: @cindex method conveniences
1.44      crook    10030: 
1.78      anton    10031: In a method you usually access the receiving object pretty often.  If
                   10032: you define the method as a plain colon definition (e.g., with
                   10033: @code{:noname}), you may have to do a lot of stack
                   10034: gymnastics. To avoid this, you can define the method with @code{m:
                   10035: ... ;m}. E.g., you could define the method for
                   10036: @code{draw}ing a @code{circle} with
1.6       pazsan   10037: 
1.78      anton    10038: @cindex @code{this} usage
                   10039: @cindex @code{m:} usage
                   10040: @cindex @code{;m} usage
                   10041: @example
                   10042: m: ( x y circle -- )
                   10043:   ( x y ) this circle-radius @@ draw-circle ;m
                   10044: @end example
1.6       pazsan   10045: 
1.78      anton    10046: @cindex @code{exit} in @code{m: ... ;m}
                   10047: @cindex @code{exitm} discussion
                   10048: @cindex @code{catch} in @code{m: ... ;m}
                   10049: When this method is executed, the receiver object is removed from the
                   10050: stack; you can access it with @code{this} (admittedly, in this
                   10051: example the use of @code{m: ... ;m} offers no advantage). Note
                   10052: that I specify the stack effect for the whole method (i.e. including
                   10053: the receiver object), not just for the code between @code{m:}
                   10054: and @code{;m}. You cannot use @code{exit} in
                   10055: @code{m:...;m}; instead, use
                   10056: @code{exitm}.@footnote{Moreover, for any word that calls
                   10057: @code{catch} and was defined before loading
                   10058: @code{objects.fs}, you have to redefine it like I redefined
                   10059: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12      anton    10060: 
1.78      anton    10061: @cindex @code{inst-var} usage
                   10062: You will frequently use sequences of the form @code{this
                   10063: @emph{field}} (in the example above: @code{this
                   10064: circle-radius}). If you use the field only in this way, you can
                   10065: define it with @code{inst-var} and eliminate the
                   10066: @code{this} before the field name. E.g., the @code{circle}
                   10067: class above could also be defined with:
1.6       pazsan   10068: 
1.78      anton    10069: @example
                   10070: graphical class
                   10071:   cell% inst-var radius
1.6       pazsan   10072: 
1.78      anton    10073: m: ( x y circle -- )
                   10074:   radius @@ draw-circle ;m
                   10075: overrides draw
1.6       pazsan   10076: 
1.78      anton    10077: m: ( n-radius circle -- )
                   10078:   radius ! ;m
                   10079: overrides construct
1.6       pazsan   10080: 
1.78      anton    10081: end-class circle
                   10082: @end example
1.6       pazsan   10083: 
1.78      anton    10084: @code{radius} can only be used in @code{circle} and its
                   10085: descendent classes and inside @code{m:...;m}.
1.6       pazsan   10086: 
1.78      anton    10087: @cindex @code{inst-value} usage
                   10088: You can also define fields with @code{inst-value}, which is
                   10089: to @code{inst-var} what @code{value} is to
                   10090: @code{variable}.  You can change the value of such a field with
                   10091: @code{[to-inst]}.  E.g., we could also define the class
                   10092: @code{circle} like this:
1.44      crook    10093: 
1.78      anton    10094: @example
                   10095: graphical class
                   10096:   inst-value radius
1.6       pazsan   10097: 
1.78      anton    10098: m: ( x y circle -- )
                   10099:   radius draw-circle ;m
                   10100: overrides draw
1.44      crook    10101: 
1.78      anton    10102: m: ( n-radius circle -- )
                   10103:   [to-inst] radius ;m
                   10104: overrides construct
1.6       pazsan   10105: 
1.78      anton    10106: end-class circle
                   10107: @end example
1.6       pazsan   10108: 
1.78      anton    10109: @c !! :m is easy to confuse with m:.  Another name would be better.
1.6       pazsan   10110: 
1.78      anton    10111: @c Finally, you can define named methods with @code{:m}.  One use of this
                   10112: @c feature is the definition of words that occur only in one class and are
                   10113: @c not intended to be overridden, but which still need method context
                   10114: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   10115: @c would be bound frequently, if defined anonymously.
1.6       pazsan   10116: 
                   10117: 
1.78      anton    10118: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
                   10119: @subsubsection Classes and Scoping
                   10120: @cindex classes and scoping
                   10121: @cindex scoping and classes
1.6       pazsan   10122: 
1.78      anton    10123: Inheritance is frequent, unlike structure extension. This exacerbates
                   10124: the problem with the field name convention (@pxref{Structure Naming
                   10125: Convention}): One always has to remember in which class the field was
                   10126: originally defined; changing a part of the class structure would require
                   10127: changes for renaming in otherwise unaffected code.
1.6       pazsan   10128: 
1.78      anton    10129: @cindex @code{inst-var} visibility
                   10130: @cindex @code{inst-value} visibility
                   10131: To solve this problem, I added a scoping mechanism (which was not in my
                   10132: original charter): A field defined with @code{inst-var} (or
                   10133: @code{inst-value}) is visible only in the class where it is defined and in
                   10134: the descendent classes of this class.  Using such fields only makes
                   10135: sense in @code{m:}-defined methods in these classes anyway.
1.6       pazsan   10136: 
1.78      anton    10137: This scoping mechanism allows us to use the unadorned field name,
                   10138: because name clashes with unrelated words become much less likely.
1.6       pazsan   10139: 
1.78      anton    10140: @cindex @code{protected} discussion
                   10141: @cindex @code{private} discussion
                   10142: Once we have this mechanism, we can also use it for controlling the
                   10143: visibility of other words: All words defined after
                   10144: @code{protected} are visible only in the current class and its
                   10145: descendents. @code{public} restores the compilation
                   10146: (i.e. @code{current}) word list that was in effect before. If you
                   10147: have several @code{protected}s without an intervening
                   10148: @code{public} or @code{set-current}, @code{public}
                   10149: will restore the compilation word list in effect before the first of
                   10150: these @code{protected}s.
1.6       pazsan   10151: 
1.78      anton    10152: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   10153: @subsubsection Dividing classes
                   10154: @cindex Dividing classes
                   10155: @cindex @code{methods}...@code{end-methods}
1.6       pazsan   10156: 
1.78      anton    10157: You may want to do the definition of methods separate from the
                   10158: definition of the class, its selectors, fields, and instance variables,
                   10159: i.e., separate the implementation from the definition.  You can do this
                   10160: in the following way:
1.6       pazsan   10161: 
1.78      anton    10162: @example
                   10163: graphical class
                   10164:   inst-value radius
                   10165: end-class circle
1.6       pazsan   10166: 
1.78      anton    10167: ... \ do some other stuff
1.6       pazsan   10168: 
1.78      anton    10169: circle methods \ now we are ready
1.44      crook    10170: 
1.78      anton    10171: m: ( x y circle -- )
                   10172:   radius draw-circle ;m
                   10173: overrides draw
1.6       pazsan   10174: 
1.78      anton    10175: m: ( n-radius circle -- )
                   10176:   [to-inst] radius ;m
                   10177: overrides construct
1.44      crook    10178: 
1.78      anton    10179: end-methods
                   10180: @end example
1.7       pazsan   10181: 
1.78      anton    10182: You can use several @code{methods}...@code{end-methods} sections.  The
                   10183: only things you can do to the class in these sections are: defining
                   10184: methods, and overriding the class's selectors.  You must not define new
                   10185: selectors or fields.
1.7       pazsan   10186: 
1.78      anton    10187: Note that you often have to override a selector before using it.  In
                   10188: particular, you usually have to override @code{construct} with a new
                   10189: method before you can invoke @code{heap-new} and friends.  E.g., you
                   10190: must not create a circle before the @code{overrides construct} sequence
                   10191: in the example above.
1.7       pazsan   10192: 
1.78      anton    10193: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
                   10194: @subsubsection Object Interfaces
                   10195: @cindex object interfaces
                   10196: @cindex interfaces for objects
1.7       pazsan   10197: 
1.78      anton    10198: In this model you can only call selectors defined in the class of the
                   10199: receiving objects or in one of its ancestors. If you call a selector
                   10200: with a receiving object that is not in one of these classes, the
                   10201: result is undefined; if you are lucky, the program crashes
                   10202: immediately.
1.7       pazsan   10203: 
1.78      anton    10204: @cindex selectors common to hardly-related classes
                   10205: Now consider the case when you want to have a selector (or several)
                   10206: available in two classes: You would have to add the selector to a
                   10207: common ancestor class, in the worst case to @code{object}. You
                   10208: may not want to do this, e.g., because someone else is responsible for
                   10209: this ancestor class.
1.7       pazsan   10210: 
1.78      anton    10211: The solution for this problem is interfaces. An interface is a
                   10212: collection of selectors. If a class implements an interface, the
                   10213: selectors become available to the class and its descendents. A class
                   10214: can implement an unlimited number of interfaces. For the problem
                   10215: discussed above, we would define an interface for the selector(s), and
                   10216: both classes would implement the interface.
1.7       pazsan   10217: 
1.78      anton    10218: As an example, consider an interface @code{storage} for
                   10219: writing objects to disk and getting them back, and a class
                   10220: @code{foo} that implements it. The code would look like this:
1.7       pazsan   10221: 
1.78      anton    10222: @cindex @code{interface} usage
                   10223: @cindex @code{end-interface} usage
                   10224: @cindex @code{implementation} usage
                   10225: @example
                   10226: interface
                   10227:   selector write ( file object -- )
                   10228:   selector read1 ( file object -- )
                   10229: end-interface storage
1.13      pazsan   10230: 
1.78      anton    10231: bar class
                   10232:   storage implementation
1.13      pazsan   10233: 
1.78      anton    10234: ... overrides write
                   10235: ... overrides read1
                   10236: ...
                   10237: end-class foo
                   10238: @end example
1.13      pazsan   10239: 
1.78      anton    10240: @noindent
                   10241: (I would add a word @code{read} @i{( file -- object )} that uses
                   10242: @code{read1} internally, but that's beyond the point illustrated
                   10243: here.)
1.13      pazsan   10244: 
1.78      anton    10245: Note that you cannot use @code{protected} in an interface; and
                   10246: of course you cannot define fields.
1.13      pazsan   10247: 
1.78      anton    10248: In the Neon model, all selectors are available for all classes;
                   10249: therefore it does not need interfaces. The price you pay in this model
                   10250: is slower late binding, and therefore, added complexity to avoid late
                   10251: binding.
1.13      pazsan   10252: 
1.78      anton    10253: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   10254: @subsubsection @file{objects.fs} Implementation
                   10255: @cindex @file{objects.fs} implementation
1.13      pazsan   10256: 
1.78      anton    10257: @cindex @code{object-map} discussion
                   10258: An object is a piece of memory, like one of the data structures
                   10259: described with @code{struct...end-struct}. It has a field
                   10260: @code{object-map} that points to the method map for the object's
                   10261: class.
1.13      pazsan   10262: 
1.78      anton    10263: @cindex method map
                   10264: @cindex virtual function table
                   10265: The @emph{method map}@footnote{This is Self terminology; in C++
                   10266: terminology: virtual function table.} is an array that contains the
                   10267: execution tokens (@i{xt}s) of the methods for the object's class. Each
                   10268: selector contains an offset into a method map.
1.13      pazsan   10269: 
1.78      anton    10270: @cindex @code{selector} implementation, class
                   10271: @code{selector} is a defining word that uses
                   10272: @code{CREATE} and @code{DOES>}. The body of the
                   10273: selector contains the offset; the @code{DOES>} action for a
                   10274: class selector is, basically:
1.8       pazsan   10275: 
                   10276: @example
1.78      anton    10277: ( object addr ) @@ over object-map @@ + @@ execute
1.13      pazsan   10278: @end example
                   10279: 
1.78      anton    10280: Since @code{object-map} is the first field of the object, it
                   10281: does not generate any code. As you can see, calling a selector has a
                   10282: small, constant cost.
1.26      crook    10283: 
1.78      anton    10284: @cindex @code{current-interface} discussion
                   10285: @cindex class implementation and representation
                   10286: A class is basically a @code{struct} combined with a method
                   10287: map. During the class definition the alignment and size of the class
                   10288: are passed on the stack, just as with @code{struct}s, so
                   10289: @code{field} can also be used for defining class
                   10290: fields. However, passing more items on the stack would be
                   10291: inconvenient, so @code{class} builds a data structure in memory,
                   10292: which is accessed through the variable
                   10293: @code{current-interface}. After its definition is complete, the
                   10294: class is represented on the stack by a pointer (e.g., as parameter for
                   10295: a child class definition).
1.26      crook    10296: 
1.78      anton    10297: A new class starts off with the alignment and size of its parent,
                   10298: and a copy of the parent's method map. Defining new fields extends the
                   10299: size and alignment; likewise, defining new selectors extends the
                   10300: method map. @code{overrides} just stores a new @i{xt} in the method
                   10301: map at the offset given by the selector.
1.13      pazsan   10302: 
1.78      anton    10303: @cindex class binding, implementation
                   10304: Class binding just gets the @i{xt} at the offset given by the selector
                   10305: from the class's method map and @code{compile,}s (in the case of
                   10306: @code{[bind]}) it.
1.13      pazsan   10307: 
1.78      anton    10308: @cindex @code{this} implementation
                   10309: @cindex @code{catch} and @code{this}
                   10310: @cindex @code{this} and @code{catch}
                   10311: I implemented @code{this} as a @code{value}. At the
                   10312: start of an @code{m:...;m} method the old @code{this} is
                   10313: stored to the return stack and restored at the end; and the object on
                   10314: the TOS is stored @code{TO this}. This technique has one
                   10315: disadvantage: If the user does not leave the method via
                   10316: @code{;m}, but via @code{throw} or @code{exit},
                   10317: @code{this} is not restored (and @code{exit} may
                   10318: crash). To deal with the @code{throw} problem, I have redefined
                   10319: @code{catch} to save and restore @code{this}; the same
                   10320: should be done with any word that can catch an exception. As for
                   10321: @code{exit}, I simply forbid it (as a replacement, there is
                   10322: @code{exitm}).
1.13      pazsan   10323: 
1.78      anton    10324: @cindex @code{inst-var} implementation
                   10325: @code{inst-var} is just the same as @code{field}, with
                   10326: a different @code{DOES>} action:
1.13      pazsan   10327: @example
1.78      anton    10328: @@ this +
1.8       pazsan   10329: @end example
1.78      anton    10330: Similar for @code{inst-value}.
1.8       pazsan   10331: 
1.78      anton    10332: @cindex class scoping implementation
                   10333: Each class also has a word list that contains the words defined with
                   10334: @code{inst-var} and @code{inst-value}, and its protected
                   10335: words. It also has a pointer to its parent. @code{class} pushes
                   10336: the word lists of the class and all its ancestors onto the search order stack,
                   10337: and @code{end-class} drops them.
1.20      pazsan   10338: 
1.78      anton    10339: @cindex interface implementation
                   10340: An interface is like a class without fields, parent and protected
                   10341: words; i.e., it just has a method map. If a class implements an
                   10342: interface, its method map contains a pointer to the method map of the
                   10343: interface. The positive offsets in the map are reserved for class
                   10344: methods, therefore interface map pointers have negative
                   10345: offsets. Interfaces have offsets that are unique throughout the
                   10346: system, unlike class selectors, whose offsets are only unique for the
                   10347: classes where the selector is available (invokable).
1.20      pazsan   10348: 
1.78      anton    10349: This structure means that interface selectors have to perform one
                   10350: indirection more than class selectors to find their method. Their body
                   10351: contains the interface map pointer offset in the class method map, and
                   10352: the method offset in the interface method map. The
                   10353: @code{does>} action for an interface selector is, basically:
1.20      pazsan   10354: 
                   10355: @example
1.78      anton    10356: ( object selector-body )
                   10357: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   10358: swap object-map @@ + @@ ( object selector-body map )
                   10359: swap selector-offset @@ + @@ execute
1.20      pazsan   10360: @end example
                   10361: 
1.78      anton    10362: where @code{object-map} and @code{selector-offset} are
                   10363: first fields and generate no code.
1.20      pazsan   10364: 
1.78      anton    10365: As a concrete example, consider the following code:
1.20      pazsan   10366: 
                   10367: @example
1.78      anton    10368: interface
                   10369:   selector if1sel1
                   10370:   selector if1sel2
                   10371: end-interface if1
1.20      pazsan   10372: 
1.78      anton    10373: object class
                   10374:   if1 implementation
                   10375:   selector cl1sel1
                   10376:   cell% inst-var cl1iv1
1.20      pazsan   10377: 
1.78      anton    10378: ' m1 overrides construct
                   10379: ' m2 overrides if1sel1
                   10380: ' m3 overrides if1sel2
                   10381: ' m4 overrides cl1sel2
                   10382: end-class cl1
1.20      pazsan   10383: 
1.78      anton    10384: create obj1 object dict-new drop
                   10385: create obj2 cl1    dict-new drop
                   10386: @end example
1.20      pazsan   10387: 
1.78      anton    10388: The data structure created by this code (including the data structure
                   10389: for @code{object}) is shown in the
                   10390: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
                   10391: @comment TODO add this diagram..
1.20      pazsan   10392: 
1.78      anton    10393: @node Objects Glossary,  , Objects Implementation, Objects
                   10394: @subsubsection @file{objects.fs} Glossary
                   10395: @cindex @file{objects.fs} Glossary
1.20      pazsan   10396: 
                   10397: 
1.78      anton    10398: doc---objects-bind
                   10399: doc---objects-<bind>
                   10400: doc---objects-bind'
                   10401: doc---objects-[bind]
                   10402: doc---objects-class
                   10403: doc---objects-class->map
                   10404: doc---objects-class-inst-size
                   10405: doc---objects-class-override!
1.79      anton    10406: doc---objects-class-previous
                   10407: doc---objects-class>order
1.78      anton    10408: doc---objects-construct
                   10409: doc---objects-current'
                   10410: doc---objects-[current]
                   10411: doc---objects-current-interface
                   10412: doc---objects-dict-new
                   10413: doc---objects-end-class
                   10414: doc---objects-end-class-noname
                   10415: doc---objects-end-interface
                   10416: doc---objects-end-interface-noname
                   10417: doc---objects-end-methods
                   10418: doc---objects-exitm
                   10419: doc---objects-heap-new
                   10420: doc---objects-implementation
                   10421: doc---objects-init-object
                   10422: doc---objects-inst-value
                   10423: doc---objects-inst-var
                   10424: doc---objects-interface
                   10425: doc---objects-m:
                   10426: doc---objects-:m
                   10427: doc---objects-;m
                   10428: doc---objects-method
                   10429: doc---objects-methods
                   10430: doc---objects-object
                   10431: doc---objects-overrides
                   10432: doc---objects-[parent]
                   10433: doc---objects-print
                   10434: doc---objects-protected
                   10435: doc---objects-public
                   10436: doc---objects-selector
                   10437: doc---objects-this
                   10438: doc---objects-<to-inst>
                   10439: doc---objects-[to-inst]
                   10440: doc---objects-to-this
                   10441: doc---objects-xt-new
1.20      pazsan   10442: 
                   10443: 
1.78      anton    10444: @c -------------------------------------------------------------
                   10445: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   10446: @subsection The @file{oof.fs} model
                   10447: @cindex oof
                   10448: @cindex object-oriented programming
1.20      pazsan   10449: 
1.78      anton    10450: @cindex @file{objects.fs}
                   10451: @cindex @file{oof.fs}
1.20      pazsan   10452: 
1.78      anton    10453: This section describes the @file{oof.fs} package.
1.20      pazsan   10454: 
1.78      anton    10455: The package described in this section has been used in bigFORTH since 1991, and
                   10456: used for two large applications: a chromatographic system used to
                   10457: create new medicaments, and a graphic user interface library (MINOS).
1.20      pazsan   10458: 
1.78      anton    10459: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   10460: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   10461: 10(2), 1994.
1.20      pazsan   10462: 
1.78      anton    10463: @menu
                   10464: * Properties of the OOF model::  
                   10465: * Basic OOF Usage::             
                   10466: * The OOF base class::          
                   10467: * Class Declaration::           
                   10468: * Class Implementation::        
                   10469: @end menu
1.20      pazsan   10470: 
1.78      anton    10471: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   10472: @subsubsection Properties of the @file{oof.fs} model
                   10473: @cindex @file{oof.fs} properties
1.20      pazsan   10474: 
1.78      anton    10475: @itemize @bullet
                   10476: @item
                   10477: This model combines object oriented programming with information
                   10478: hiding. It helps you writing large application, where scoping is
                   10479: necessary, because it provides class-oriented scoping.
1.20      pazsan   10480: 
1.78      anton    10481: @item
                   10482: Named objects, object pointers, and object arrays can be created,
                   10483: selector invocation uses the ``object selector'' syntax. Selector invocation
                   10484: to objects and/or selectors on the stack is a bit less convenient, but
                   10485: possible.
1.44      crook    10486: 
1.78      anton    10487: @item
                   10488: Selector invocation and instance variable usage of the active object is
                   10489: straightforward, since both make use of the active object.
1.44      crook    10490: 
1.78      anton    10491: @item
                   10492: Late binding is efficient and easy to use.
1.20      pazsan   10493: 
1.78      anton    10494: @item
                   10495: State-smart objects parse selectors. However, extensibility is provided
                   10496: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20      pazsan   10497: 
1.78      anton    10498: @item
                   10499: An implementation in ANS Forth is available.
1.20      pazsan   10500: 
1.78      anton    10501: @end itemize
1.23      crook    10502: 
                   10503: 
1.78      anton    10504: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   10505: @subsubsection Basic @file{oof.fs} Usage
                   10506: @cindex @file{oof.fs} usage
1.23      crook    10507: 
1.78      anton    10508: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23      crook    10509: 
1.78      anton    10510: You can define a class for graphical objects like this:
1.23      crook    10511: 
1.78      anton    10512: @cindex @code{class} usage
                   10513: @cindex @code{class;} usage
                   10514: @cindex @code{method} usage
                   10515: @example
                   10516: object class graphical \ "object" is the parent class
                   10517:   method draw ( x y graphical -- )
                   10518: class;
                   10519: @end example
1.23      crook    10520: 
1.78      anton    10521: This code defines a class @code{graphical} with an
                   10522: operation @code{draw}.  We can perform the operation
                   10523: @code{draw} on any @code{graphical} object, e.g.:
1.23      crook    10524: 
1.78      anton    10525: @example
                   10526: 100 100 t-rex draw
                   10527: @end example
1.23      crook    10528: 
1.78      anton    10529: @noindent
                   10530: where @code{t-rex} is an object or object pointer, created with e.g.
                   10531: @code{graphical : t-rex}.
1.23      crook    10532: 
1.78      anton    10533: @cindex abstract class
                   10534: How do we create a graphical object? With the present definitions,
                   10535: we cannot create a useful graphical object. The class
                   10536: @code{graphical} describes graphical objects in general, but not
                   10537: any concrete graphical object type (C++ users would call it an
                   10538: @emph{abstract class}); e.g., there is no method for the selector
                   10539: @code{draw} in the class @code{graphical}.
1.23      crook    10540: 
1.78      anton    10541: For concrete graphical objects, we define child classes of the
                   10542: class @code{graphical}, e.g.:
1.23      crook    10543: 
1.78      anton    10544: @example
                   10545: graphical class circle \ "graphical" is the parent class
                   10546:   cell var circle-radius
                   10547: how:
                   10548:   : draw ( x y -- )
                   10549:     circle-radius @@ draw-circle ;
1.23      crook    10550: 
1.78      anton    10551:   : init ( n-radius -- (
                   10552:     circle-radius ! ;
                   10553: class;
                   10554: @end example
1.1       anton    10555: 
1.78      anton    10556: Here we define a class @code{circle} as a child of @code{graphical},
                   10557: with a field @code{circle-radius}; it defines new methods for the
                   10558: selectors @code{draw} and @code{init} (@code{init} is defined in
                   10559: @code{object}, the parent class of @code{graphical}).
1.1       anton    10560: 
1.78      anton    10561: Now we can create a circle in the dictionary with:
1.1       anton    10562: 
1.78      anton    10563: @example
                   10564: 50 circle : my-circle
                   10565: @end example
1.21      crook    10566: 
1.78      anton    10567: @noindent
                   10568: @code{:} invokes @code{init}, thus initializing the field
                   10569: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   10570: with:
1.1       anton    10571: 
1.78      anton    10572: @example
                   10573: 100 100 my-circle draw
                   10574: @end example
1.1       anton    10575: 
1.78      anton    10576: @cindex selector invocation, restrictions
                   10577: @cindex class definition, restrictions
                   10578: Note: You can only invoke a selector if the receiving object belongs to
                   10579: the class where the selector was defined or one of its descendents;
                   10580: e.g., you can invoke @code{draw} only for objects belonging to
                   10581: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   10582: mechanism will check if you try to invoke a selector that is not
                   10583: defined in this class hierarchy, so you'll get an error at compilation
                   10584: time.
1.1       anton    10585: 
                   10586: 
1.78      anton    10587: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   10588: @subsubsection The @file{oof.fs} base class
                   10589: @cindex @file{oof.fs} base class
1.1       anton    10590: 
1.78      anton    10591: When you define a class, you have to specify a parent class.  So how do
                   10592: you start defining classes? There is one class available from the start:
                   10593: @code{object}. You have to use it as ancestor for all classes. It is the
                   10594: only class that has no parent. Classes are also objects, except that
                   10595: they don't have instance variables; class manipulation such as
                   10596: inheritance or changing definitions of a class is handled through
                   10597: selectors of the class @code{object}.
1.1       anton    10598: 
1.78      anton    10599: @code{object} provides a number of selectors:
1.1       anton    10600: 
1.78      anton    10601: @itemize @bullet
                   10602: @item
                   10603: @code{class} for subclassing, @code{definitions} to add definitions
                   10604: later on, and @code{class?} to get type informations (is the class a
                   10605: subclass of the class passed on the stack?).
1.1       anton    10606: 
1.78      anton    10607: doc---object-class
                   10608: doc---object-definitions
                   10609: doc---object-class?
1.1       anton    10610: 
                   10611: 
1.26      crook    10612: @item
1.78      anton    10613: @code{init} and @code{dispose} as constructor and destructor of the
                   10614: object. @code{init} is invocated after the object's memory is allocated,
                   10615: while @code{dispose} also handles deallocation. Thus if you redefine
                   10616: @code{dispose}, you have to call the parent's dispose with @code{super
                   10617: dispose}, too.
                   10618: 
                   10619: doc---object-init
                   10620: doc---object-dispose
                   10621: 
1.1       anton    10622: 
1.26      crook    10623: @item
1.78      anton    10624: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   10625: @code{[]} to create named and unnamed objects and object arrays or
                   10626: object pointers.
                   10627: 
                   10628: doc---object-new
                   10629: doc---object-new[]
                   10630: doc---object-:
                   10631: doc---object-ptr
                   10632: doc---object-asptr
                   10633: doc---object-[]
                   10634: 
1.1       anton    10635: 
1.26      crook    10636: @item
1.78      anton    10637: @code{::} and @code{super} for explicit scoping. You should use explicit
                   10638: scoping only for super classes or classes with the same set of instance
                   10639: variables. Explicitly-scoped selectors use early binding.
1.21      crook    10640: 
1.78      anton    10641: doc---object-::
                   10642: doc---object-super
1.21      crook    10643: 
                   10644: 
1.26      crook    10645: @item
1.78      anton    10646: @code{self} to get the address of the object
1.21      crook    10647: 
1.78      anton    10648: doc---object-self
1.21      crook    10649: 
                   10650: 
1.78      anton    10651: @item
                   10652: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   10653: pointers and instance defers.
1.21      crook    10654: 
1.78      anton    10655: doc---object-bind
                   10656: doc---object-bound
                   10657: doc---object-link
                   10658: doc---object-is
1.21      crook    10659: 
                   10660: 
1.78      anton    10661: @item
                   10662: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   10663: form the stack, and @code{postpone} to generate selector invocation code.
1.21      crook    10664: 
1.78      anton    10665: doc---object-'
                   10666: doc---object-postpone
1.21      crook    10667: 
                   10668: 
1.78      anton    10669: @item
                   10670: @code{with} and @code{endwith} to select the active object from the
                   10671: stack, and enable its scope. Using @code{with} and @code{endwith}
                   10672: also allows you to create code using selector @code{postpone} without being
                   10673: trapped by the state-smart objects.
1.21      crook    10674: 
1.78      anton    10675: doc---object-with
                   10676: doc---object-endwith
1.21      crook    10677: 
                   10678: 
1.78      anton    10679: @end itemize
1.21      crook    10680: 
1.78      anton    10681: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   10682: @subsubsection Class Declaration
                   10683: @cindex class declaration
1.21      crook    10684: 
1.78      anton    10685: @itemize @bullet
                   10686: @item
                   10687: Instance variables
1.21      crook    10688: 
1.78      anton    10689: doc---oof-var
1.21      crook    10690: 
                   10691: 
1.78      anton    10692: @item
                   10693: Object pointers
1.21      crook    10694: 
1.78      anton    10695: doc---oof-ptr
                   10696: doc---oof-asptr
1.21      crook    10697: 
                   10698: 
1.78      anton    10699: @item
                   10700: Instance defers
1.21      crook    10701: 
1.78      anton    10702: doc---oof-defer
1.21      crook    10703: 
                   10704: 
1.78      anton    10705: @item
                   10706: Method selectors
1.21      crook    10707: 
1.78      anton    10708: doc---oof-early
                   10709: doc---oof-method
1.21      crook    10710: 
                   10711: 
1.78      anton    10712: @item
                   10713: Class-wide variables
1.21      crook    10714: 
1.78      anton    10715: doc---oof-static
1.21      crook    10716: 
                   10717: 
1.78      anton    10718: @item
                   10719: End declaration
1.1       anton    10720: 
1.78      anton    10721: doc---oof-how:
                   10722: doc---oof-class;
1.21      crook    10723: 
                   10724: 
1.78      anton    10725: @end itemize
1.21      crook    10726: 
1.78      anton    10727: @c -------------------------------------------------------------
                   10728: @node Class Implementation,  , Class Declaration, OOF
                   10729: @subsubsection Class Implementation
                   10730: @cindex class implementation
1.21      crook    10731: 
1.78      anton    10732: @c -------------------------------------------------------------
                   10733: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   10734: @subsection The @file{mini-oof.fs} model
                   10735: @cindex mini-oof
1.21      crook    10736: 
1.78      anton    10737: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79      anton    10738: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78      anton    10739: and reduces to the bare minimum of features. This is based on a posting
                   10740: of Bernd Paysan in comp.lang.forth.
1.21      crook    10741: 
1.78      anton    10742: @menu
                   10743: * Basic Mini-OOF Usage::        
                   10744: * Mini-OOF Example::            
                   10745: * Mini-OOF Implementation::     
                   10746: @end menu
1.21      crook    10747: 
1.78      anton    10748: @c -------------------------------------------------------------
                   10749: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
                   10750: @subsubsection Basic @file{mini-oof.fs} Usage
                   10751: @cindex mini-oof usage
1.21      crook    10752: 
1.78      anton    10753: There is a base class (@code{class}, which allocates one cell for the
                   10754: object pointer) plus seven other words: to define a method, a variable,
                   10755: a class; to end a class, to resolve binding, to allocate an object and
                   10756: to compile a class method.
                   10757: @comment TODO better description of the last one
1.26      crook    10758: 
1.21      crook    10759: 
1.78      anton    10760: doc-object
                   10761: doc-method
                   10762: doc-var
                   10763: doc-class
                   10764: doc-end-class
                   10765: doc-defines
                   10766: doc-new
                   10767: doc-::
1.21      crook    10768: 
                   10769: 
                   10770: 
1.78      anton    10771: @c -------------------------------------------------------------
                   10772: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   10773: @subsubsection Mini-OOF Example
                   10774: @cindex mini-oof example
1.1       anton    10775: 
1.78      anton    10776: A short example shows how to use this package. This example, in slightly
                   10777: extended form, is supplied as @file{moof-exm.fs}
                   10778: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20      pazsan   10779: 
1.26      crook    10780: @example
1.78      anton    10781: object class
                   10782:   method init
                   10783:   method draw
                   10784: end-class graphical
1.26      crook    10785: @end example
1.20      pazsan   10786: 
1.78      anton    10787: This code defines a class @code{graphical} with an
                   10788: operation @code{draw}.  We can perform the operation
                   10789: @code{draw} on any @code{graphical} object, e.g.:
1.20      pazsan   10790: 
1.26      crook    10791: @example
1.78      anton    10792: 100 100 t-rex draw
1.26      crook    10793: @end example
1.12      anton    10794: 
1.78      anton    10795: where @code{t-rex} is an object or object pointer, created with e.g.
                   10796: @code{graphical new Constant t-rex}.
1.12      anton    10797: 
1.78      anton    10798: For concrete graphical objects, we define child classes of the
                   10799: class @code{graphical}, e.g.:
1.12      anton    10800: 
1.26      crook    10801: @example
                   10802: graphical class
1.78      anton    10803:   cell var circle-radius
                   10804: end-class circle \ "graphical" is the parent class
1.12      anton    10805: 
1.78      anton    10806: :noname ( x y -- )
                   10807:   circle-radius @@ draw-circle ; circle defines draw
                   10808: :noname ( r -- )
                   10809:   circle-radius ! ; circle defines init
                   10810: @end example
1.12      anton    10811: 
1.78      anton    10812: There is no implicit init method, so we have to define one. The creation
                   10813: code of the object now has to call init explicitely.
1.21      crook    10814: 
1.78      anton    10815: @example
                   10816: circle new Constant my-circle
                   10817: 50 my-circle init
1.12      anton    10818: @end example
                   10819: 
1.78      anton    10820: It is also possible to add a function to create named objects with
                   10821: automatic call of @code{init}, given that all objects have @code{init}
                   10822: on the same place:
1.38      anton    10823: 
1.78      anton    10824: @example
                   10825: : new: ( .. o "name" -- )
                   10826:     new dup Constant init ;
                   10827: 80 circle new: large-circle
                   10828: @end example
1.12      anton    10829: 
1.78      anton    10830: We can draw this new circle at (100,100) with:
1.12      anton    10831: 
1.78      anton    10832: @example
                   10833: 100 100 my-circle draw
                   10834: @end example
1.12      anton    10835: 
1.78      anton    10836: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
                   10837: @subsubsection @file{mini-oof.fs} Implementation
1.12      anton    10838: 
1.78      anton    10839: Object-oriented systems with late binding typically use a
                   10840: ``vtable''-approach: the first variable in each object is a pointer to a
                   10841: table, which contains the methods as function pointers. The vtable
                   10842: may also contain other information.
1.12      anton    10843: 
1.79      anton    10844: So first, let's declare selectors:
1.37      anton    10845: 
                   10846: @example
1.79      anton    10847: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
1.78      anton    10848:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
                   10849: @end example
1.37      anton    10850: 
1.79      anton    10851: During selector declaration, the number of selectors and instance
                   10852: variables is on the stack (in address units). @code{method} creates one
                   10853: selector and increments the selector number. To execute a selector, it
1.78      anton    10854: takes the object, fetches the vtable pointer, adds the offset, and
1.79      anton    10855: executes the method @i{xt} stored there. Each selector takes the object
                   10856: it is invoked with as top of stack parameter; it passes the parameters
                   10857: (including the object) unchanged to the appropriate method which should
1.78      anton    10858: consume that object.
1.37      anton    10859: 
1.78      anton    10860: Now, we also have to declare instance variables
1.37      anton    10861: 
1.78      anton    10862: @example
1.79      anton    10863: : var ( m v size "name" -- m v' ) Create  over , +
1.78      anton    10864:   DOES> ( o -- addr ) @@ + ;
1.37      anton    10865: @end example
                   10866: 
1.78      anton    10867: As before, a word is created with the current offset. Instance
                   10868: variables can have different sizes (cells, floats, doubles, chars), so
                   10869: all we do is take the size and add it to the offset. If your machine
                   10870: has alignment restrictions, put the proper @code{aligned} or
                   10871: @code{faligned} before the variable, to adjust the variable
                   10872: offset. That's why it is on the top of stack.
1.37      anton    10873: 
1.78      anton    10874: We need a starting point (the base object) and some syntactic sugar:
1.37      anton    10875: 
1.78      anton    10876: @example
                   10877: Create object  1 cells , 2 cells ,
1.79      anton    10878: : class ( class -- class selectors vars ) dup 2@@ ;
1.78      anton    10879: @end example
1.12      anton    10880: 
1.78      anton    10881: For inheritance, the vtable of the parent object has to be
                   10882: copied when a new, derived class is declared. This gives all the
                   10883: methods of the parent class, which can be overridden, though.
1.12      anton    10884: 
1.78      anton    10885: @example
1.79      anton    10886: : end-class  ( class selectors vars "name" -- )
1.78      anton    10887:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   10888:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
                   10889: @end example
1.12      anton    10890: 
1.78      anton    10891: The first line creates the vtable, initialized with
                   10892: @code{noop}s. The second line is the inheritance mechanism, it
                   10893: copies the xts from the parent vtable.
1.12      anton    10894: 
1.78      anton    10895: We still have no way to define new methods, let's do that now:
1.12      anton    10896: 
1.26      crook    10897: @example
1.79      anton    10898: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78      anton    10899: @end example
1.12      anton    10900: 
1.78      anton    10901: To allocate a new object, we need a word, too:
1.12      anton    10902: 
1.78      anton    10903: @example
                   10904: : new ( class -- o )  here over @@ allot swap over ! ;
1.12      anton    10905: @end example
                   10906: 
1.78      anton    10907: Sometimes derived classes want to access the method of the
                   10908: parent object. There are two ways to achieve this with Mini-OOF:
                   10909: first, you could use named words, and second, you could look up the
                   10910: vtable of the parent object.
1.12      anton    10911: 
1.78      anton    10912: @example
                   10913: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
                   10914: @end example
1.12      anton    10915: 
                   10916: 
1.78      anton    10917: Nothing can be more confusing than a good example, so here is
                   10918: one. First let's declare a text object (called
                   10919: @code{button}), that stores text and position:
1.12      anton    10920: 
1.78      anton    10921: @example
                   10922: object class
                   10923:   cell var text
                   10924:   cell var len
                   10925:   cell var x
                   10926:   cell var y
                   10927:   method init
                   10928:   method draw
                   10929: end-class button
                   10930: @end example
1.12      anton    10931: 
1.78      anton    10932: @noindent
                   10933: Now, implement the two methods, @code{draw} and @code{init}:
1.21      crook    10934: 
1.26      crook    10935: @example
1.78      anton    10936: :noname ( o -- )
                   10937:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
                   10938:  button defines draw
                   10939: :noname ( addr u o -- )
                   10940:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
                   10941:  button defines init
1.26      crook    10942: @end example
1.12      anton    10943: 
1.78      anton    10944: @noindent
                   10945: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79      anton    10946: new data and no new selectors:
1.78      anton    10947: 
                   10948: @example
                   10949: button class
                   10950: end-class bold-button
1.12      anton    10951: 
1.78      anton    10952: : bold   27 emit ." [1m" ;
                   10953: : normal 27 emit ." [0m" ;
                   10954: @end example
1.1       anton    10955: 
1.78      anton    10956: @noindent
                   10957: The class @code{bold-button} has a different draw method to
                   10958: @code{button}, but the new method is defined in terms of the draw method
                   10959: for @code{button}:
1.20      pazsan   10960: 
1.78      anton    10961: @example
                   10962: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   10963: @end example
1.21      crook    10964: 
1.78      anton    10965: @noindent
1.79      anton    10966: Finally, create two objects and apply selectors:
1.21      crook    10967: 
1.26      crook    10968: @example
1.78      anton    10969: button new Constant foo
                   10970: s" thin foo" foo init
                   10971: page
                   10972: foo draw
                   10973: bold-button new Constant bar
                   10974: s" fat bar" bar init
                   10975: 1 bar y !
                   10976: bar draw
1.26      crook    10977: @end example
1.21      crook    10978: 
                   10979: 
1.78      anton    10980: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   10981: @subsection Comparison with other object models
                   10982: @cindex comparison of object models
                   10983: @cindex object models, comparison
                   10984: 
                   10985: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   10986: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   10987: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   10988: relation of the object models described here to two well-known and two
                   10989: closely-related (by the use of method maps) models.  Andras Zsoter
                   10990: helped us with this section.
                   10991: 
                   10992: @cindex Neon model
                   10993: The most popular model currently seems to be the Neon model (see
                   10994: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   10995: 1997) by Andrew McKewan) but this model has a number of limitations
                   10996: @footnote{A longer version of this critique can be
                   10997: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   10998: Dimensions, May 1997) by Anton Ertl.}:
                   10999: 
                   11000: @itemize @bullet
                   11001: @item
                   11002: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11003: to pass objects on the stack.
1.21      crook    11004: 
1.78      anton    11005: @item
                   11006: It requires that the selector parses the input stream (at
1.79      anton    11007: compile time); this leads to reduced extensibility and to bugs that are
1.78      anton    11008: hard to find.
1.21      crook    11009: 
1.78      anton    11010: @item
1.79      anton    11011: It allows using every selector on every object; this eliminates the
                   11012: need for interfaces, but makes it harder to create efficient
                   11013: implementations.
1.78      anton    11014: @end itemize
1.21      crook    11015: 
1.78      anton    11016: @cindex Pountain's object-oriented model
                   11017: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11018: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11019: object-oriented programming, because it hardly deals with late
                   11020: binding. Instead, it focuses on features like information hiding and
                   11021: overloading that are characteristic of modular languages like Ada (83).
1.26      crook    11022: 
1.78      anton    11023: @cindex Zsoter's object-oriented model
1.79      anton    11024: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
                   11025: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
                   11026: describes a model that makes heavy use of an active object (like
                   11027: @code{this} in @file{objects.fs}): The active object is not only used
                   11028: for accessing all fields, but also specifies the receiving object of
                   11029: every selector invocation; you have to change the active object
                   11030: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   11031: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   11032: the method entry point is unnecessary with Zsoter's model, because the
                   11033: receiving object is the active object already. On the other hand, the
                   11034: explicit change is absolutely necessary in that model, because otherwise
                   11035: no one could ever change the active object. An ANS Forth implementation
                   11036: of this model is available through
                   11037: @uref{http://www.forth.org/oopf.html}.
1.21      crook    11038: 
1.78      anton    11039: @cindex @file{oof.fs}, differences to other models
                   11040: The @file{oof.fs} model combines information hiding and overloading
                   11041: resolution (by keeping names in various word lists) with object-oriented
                   11042: programming. It sets the active object implicitly on method entry, but
                   11043: also allows explicit changing (with @code{>o...o>} or with
                   11044: @code{with...endwith}). It uses parsing and state-smart objects and
                   11045: classes for resolving overloading and for early binding: the object or
                   11046: class parses the selector and determines the method from this. If the
                   11047: selector is not parsed by an object or class, it performs a call to the
                   11048: selector for the active object (late binding), like Zsoter's model.
                   11049: Fields are always accessed through the active object. The big
                   11050: disadvantage of this model is the parsing and the state-smartness, which
                   11051: reduces extensibility and increases the opportunities for subtle bugs;
                   11052: essentially, you are only safe if you never tick or @code{postpone} an
                   11053: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21      crook    11054: 
1.78      anton    11055: @cindex @file{mini-oof.fs}, differences to other models
                   11056: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11057: version of the @file{objects.fs} model, but syntactically it is a
                   11058: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21      crook    11059: 
                   11060: 
1.78      anton    11061: @c -------------------------------------------------------------
                   11062: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
                   11063: @section Programming Tools
                   11064: @cindex programming tools
1.21      crook    11065: 
1.78      anton    11066: @c !! move this and assembler down below OO stuff.
1.21      crook    11067: 
1.78      anton    11068: @menu
                   11069: * Examining::                   
                   11070: * Forgetting words::            
                   11071: * Debugging::                   Simple and quick.
                   11072: * Assertions::                  Making your programs self-checking.
                   11073: * Singlestep Debugger::         Executing your program word by word.
                   11074: @end menu
1.21      crook    11075: 
1.78      anton    11076: @node Examining, Forgetting words, Programming Tools, Programming Tools
                   11077: @subsection Examining data and code
                   11078: @cindex examining data and code
                   11079: @cindex data examination
                   11080: @cindex code examination
1.44      crook    11081: 
1.78      anton    11082: The following words inspect the stack non-destructively:
1.21      crook    11083: 
1.78      anton    11084: doc-.s
                   11085: doc-f.s
1.44      crook    11086: 
1.78      anton    11087: There is a word @code{.r} but it does @i{not} display the return stack!
                   11088: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21      crook    11089: 
1.78      anton    11090: doc-depth
                   11091: doc-fdepth
                   11092: doc-clearstack
1.21      crook    11093: 
1.78      anton    11094: The following words inspect memory.
1.21      crook    11095: 
1.78      anton    11096: doc-?
                   11097: doc-dump
1.21      crook    11098: 
1.78      anton    11099: And finally, @code{see} allows to inspect code:
1.21      crook    11100: 
1.78      anton    11101: doc-see
                   11102: doc-xt-see
1.21      crook    11103: 
1.78      anton    11104: @node Forgetting words, Debugging, Examining, Programming Tools
                   11105: @subsection Forgetting words
                   11106: @cindex words, forgetting
                   11107: @cindex forgeting words
1.21      crook    11108: 
1.78      anton    11109: @c  anton: other, maybe better places for this subsection: Defining Words;
                   11110: @c  Dictionary allocation.  At least a reference should be there.
1.21      crook    11111: 
1.78      anton    11112: Forth allows you to forget words (and everything that was alloted in the
                   11113: dictonary after them) in a LIFO manner.
1.21      crook    11114: 
1.78      anton    11115: doc-marker
1.21      crook    11116: 
1.78      anton    11117: The most common use of this feature is during progam development: when
                   11118: you change a source file, forget all the words it defined and load it
                   11119: again (since you also forget everything defined after the source file
                   11120: was loaded, you have to reload that, too).  Note that effects like
                   11121: storing to variables and destroyed system words are not undone when you
                   11122: forget words.  With a system like Gforth, that is fast enough at
                   11123: starting up and compiling, I find it more convenient to exit and restart
                   11124: Gforth, as this gives me a clean slate.
1.21      crook    11125: 
1.78      anton    11126: Here's an example of using @code{marker} at the start of a source file
                   11127: that you are debugging; it ensures that you only ever have one copy of
                   11128: the file's definitions compiled at any time:
1.21      crook    11129: 
1.78      anton    11130: @example
                   11131: [IFDEF] my-code
                   11132:     my-code
                   11133: [ENDIF]
1.26      crook    11134: 
1.78      anton    11135: marker my-code
                   11136: init-included-files
1.21      crook    11137: 
1.78      anton    11138: \ .. definitions start here
                   11139: \ .
                   11140: \ .
                   11141: \ end
                   11142: @end example
1.21      crook    11143: 
1.26      crook    11144: 
1.78      anton    11145: @node Debugging, Assertions, Forgetting words, Programming Tools
                   11146: @subsection Debugging
                   11147: @cindex debugging
1.21      crook    11148: 
1.78      anton    11149: Languages with a slow edit/compile/link/test development loop tend to
                   11150: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21      crook    11151: 
1.78      anton    11152: A much better (faster) way in fast-compiling languages is to add
                   11153: printing code at well-selected places, let the program run, look at
                   11154: the output, see where things went wrong, add more printing code, etc.,
                   11155: until the bug is found.
1.21      crook    11156: 
1.78      anton    11157: The simple debugging aids provided in @file{debugs.fs}
                   11158: are meant to support this style of debugging.
1.21      crook    11159: 
1.78      anton    11160: The word @code{~~} prints debugging information (by default the source
                   11161: location and the stack contents). It is easy to insert. If you use Emacs
                   11162: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   11163: query-replace them with nothing). The deferred words
                   11164: @code{printdebugdata} and @code{printdebugline} control the output of
                   11165: @code{~~}. The default source location output format works well with
                   11166: Emacs' compilation mode, so you can step through the program at the
                   11167: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   11168: is that you can step in any direction and you know where the crash has
                   11169: happened or where the strange data has occurred).
1.21      crook    11170: 
1.78      anton    11171: doc-~~
                   11172: doc-printdebugdata
                   11173: doc-printdebugline
1.21      crook    11174: 
1.78      anton    11175: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   11176: @subsection Assertions
                   11177: @cindex assertions
1.21      crook    11178: 
1.78      anton    11179: It is a good idea to make your programs self-checking, especially if you
                   11180: make an assumption that may become invalid during maintenance (for
                   11181: example, that a certain field of a data structure is never zero). Gforth
                   11182: supports @dfn{assertions} for this purpose. They are used like this:
1.21      crook    11183: 
                   11184: @example
1.78      anton    11185: assert( @i{flag} )
1.26      crook    11186: @end example
                   11187: 
1.78      anton    11188: The code between @code{assert(} and @code{)} should compute a flag, that
                   11189: should be true if everything is alright and false otherwise. It should
                   11190: not change anything else on the stack. The overall stack effect of the
                   11191: assertion is @code{( -- )}. E.g.
1.21      crook    11192: 
1.26      crook    11193: @example
1.78      anton    11194: assert( 1 1 + 2 = ) \ what we learn in school
                   11195: assert( dup 0<> ) \ assert that the top of stack is not zero
                   11196: assert( false ) \ this code should not be reached
1.21      crook    11197: @end example
                   11198: 
1.78      anton    11199: The need for assertions is different at different times. During
                   11200: debugging, we want more checking, in production we sometimes care more
                   11201: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   11202: becomes a comment. Depending on the importance of an assertion and the
                   11203: time it takes to check it, you may want to turn off some assertions and
                   11204: keep others turned on. Gforth provides several levels of assertions for
                   11205: this purpose:
                   11206: 
                   11207: 
                   11208: doc-assert0(
                   11209: doc-assert1(
                   11210: doc-assert2(
                   11211: doc-assert3(
                   11212: doc-assert(
                   11213: doc-)
1.21      crook    11214: 
                   11215: 
1.78      anton    11216: The variable @code{assert-level} specifies the highest assertions that
                   11217: are turned on. I.e., at the default @code{assert-level} of one,
                   11218: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   11219: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26      crook    11220: 
1.78      anton    11221: The value of @code{assert-level} is evaluated at compile-time, not at
                   11222: run-time. Therefore you cannot turn assertions on or off at run-time;
                   11223: you have to set the @code{assert-level} appropriately before compiling a
                   11224: piece of code. You can compile different pieces of code at different
                   11225: @code{assert-level}s (e.g., a trusted library at level 1 and
                   11226: newly-written code at level 3).
1.26      crook    11227: 
                   11228: 
1.78      anton    11229: doc-assert-level
1.26      crook    11230: 
                   11231: 
1.78      anton    11232: If an assertion fails, a message compatible with Emacs' compilation mode
                   11233: is produced and the execution is aborted (currently with @code{ABORT"}.
                   11234: If there is interest, we will introduce a special throw code. But if you
                   11235: intend to @code{catch} a specific condition, using @code{throw} is
                   11236: probably more appropriate than an assertion).
1.44      crook    11237: 
1.78      anton    11238: Definitions in ANS Forth for these assertion words are provided
                   11239: in @file{compat/assert.fs}.
1.26      crook    11240: 
1.44      crook    11241: 
1.78      anton    11242: @node Singlestep Debugger,  , Assertions, Programming Tools
                   11243: @subsection Singlestep Debugger
                   11244: @cindex singlestep Debugger
                   11245: @cindex debugging Singlestep
1.44      crook    11246: 
1.78      anton    11247: When you create a new word there's often the need to check whether it
                   11248: behaves correctly or not. You can do this by typing @code{dbg
                   11249: badword}. A debug session might look like this:
1.26      crook    11250: 
1.78      anton    11251: @example
                   11252: : badword 0 DO i . LOOP ;  ok
                   11253: 2 dbg badword 
                   11254: : badword  
                   11255: Scanning code...
1.44      crook    11256: 
1.78      anton    11257: Nesting debugger ready!
1.44      crook    11258: 
1.78      anton    11259: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   11260: 400D4740  8049F68 DO             -> [ 0 ] 
                   11261: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   11262: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   11263: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   11264: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   11265: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   11266: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   11267: 400D4758  804B384 ;              ->  ok
                   11268: @end example
1.21      crook    11269: 
1.78      anton    11270: Each line displayed is one step. You always have to hit return to
                   11271: execute the next word that is displayed. If you don't want to execute
                   11272: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   11273: an overview what keys are available:
1.44      crook    11274: 
1.78      anton    11275: @table @i
1.44      crook    11276: 
1.78      anton    11277: @item @key{RET}
                   11278: Next; Execute the next word.
1.21      crook    11279: 
1.78      anton    11280: @item n
                   11281: Nest; Single step through next word.
1.44      crook    11282: 
1.78      anton    11283: @item u
                   11284: Unnest; Stop debugging and execute rest of word. If we got to this word
                   11285: with nest, continue debugging with the calling word.
1.44      crook    11286: 
1.78      anton    11287: @item d
                   11288: Done; Stop debugging and execute rest.
1.21      crook    11289: 
1.78      anton    11290: @item s
                   11291: Stop; Abort immediately.
1.44      crook    11292: 
1.78      anton    11293: @end table
1.44      crook    11294: 
1.78      anton    11295: Debugging large application with this mechanism is very difficult, because
                   11296: you have to nest very deeply into the program before the interesting part
                   11297: begins. This takes a lot of time. 
1.26      crook    11298: 
1.78      anton    11299: To do it more directly put a @code{BREAK:} command into your source code.
                   11300: When program execution reaches @code{BREAK:} the single step debugger is
                   11301: invoked and you have all the features described above.
1.44      crook    11302: 
1.78      anton    11303: If you have more than one part to debug it is useful to know where the
                   11304: program has stopped at the moment. You can do this by the 
                   11305: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   11306: string is typed out when the ``breakpoint'' is reached.
1.44      crook    11307: 
1.26      crook    11308: 
1.78      anton    11309: doc-dbg
                   11310: doc-break:
                   11311: doc-break"
1.44      crook    11312: 
                   11313: 
1.26      crook    11314: 
1.78      anton    11315: @c -------------------------------------------------------------
                   11316: @node Assembler and Code Words, Threading Words, Programming Tools, Words
                   11317: @section Assembler and Code Words
                   11318: @cindex assembler
                   11319: @cindex code words
1.44      crook    11320: 
1.78      anton    11321: @menu
                   11322: * Code and ;code::              
                   11323: * Common Assembler::            Assembler Syntax
                   11324: * Common Disassembler::         
                   11325: * 386 Assembler::               Deviations and special cases
                   11326: * Alpha Assembler::             Deviations and special cases
                   11327: * MIPS assembler::              Deviations and special cases
                   11328: * Other assemblers::            How to write them
                   11329: @end menu
1.21      crook    11330: 
1.78      anton    11331: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
                   11332: @subsection @code{Code} and @code{;code}
1.26      crook    11333: 
1.78      anton    11334: Gforth provides some words for defining primitives (words written in
                   11335: machine code), and for defining the machine-code equivalent of
                   11336: @code{DOES>}-based defining words. However, the machine-independent
                   11337: nature of Gforth poses a few problems: First of all, Gforth runs on
                   11338: several architectures, so it can provide no standard assembler. What's
                   11339: worse is that the register allocation not only depends on the processor,
                   11340: but also on the @code{gcc} version and options used.
1.44      crook    11341: 
1.78      anton    11342: The words that Gforth offers encapsulate some system dependences (e.g.,
                   11343: the header structure), so a system-independent assembler may be used in
                   11344: Gforth. If you do not have an assembler, you can compile machine code
                   11345: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   11346: because these words emit stuff in @i{data} space; it works because
                   11347: Gforth has unified code/data spaces. Assembler isn't likely to be
                   11348: portable anyway.}.
1.21      crook    11349: 
1.44      crook    11350: 
1.78      anton    11351: doc-assembler
                   11352: doc-init-asm
                   11353: doc-code
                   11354: doc-end-code
                   11355: doc-;code
                   11356: doc-flush-icache
1.44      crook    11357: 
1.21      crook    11358: 
1.78      anton    11359: If @code{flush-icache} does not work correctly, @code{code} words
                   11360: etc. will not work (reliably), either.
1.44      crook    11361: 
1.78      anton    11362: The typical usage of these @code{code} words can be shown most easily by
                   11363: analogy to the equivalent high-level defining words:
1.44      crook    11364: 
1.78      anton    11365: @example
                   11366: : foo                              code foo
                   11367:    <high-level Forth words>              <assembler>
                   11368: ;                                  end-code
                   11369:                                 
                   11370: : bar                              : bar
                   11371:    <high-level Forth words>           <high-level Forth words>
                   11372:    CREATE                             CREATE
                   11373:       <high-level Forth words>           <high-level Forth words>
                   11374:    DOES>                              ;code
                   11375:       <high-level Forth words>           <assembler>
                   11376: ;                                  end-code
                   11377: @end example
1.21      crook    11378: 
1.78      anton    11379: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44      crook    11380: 
1.78      anton    11381: @cindex registers of the inner interpreter
                   11382: In the assembly code you will want to refer to the inner interpreter's
                   11383: registers (e.g., the data stack pointer) and you may want to use other
                   11384: registers for temporary storage. Unfortunately, the register allocation
                   11385: is installation-dependent.
1.44      crook    11386: 
1.78      anton    11387: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
                   11388: (return stack pointer) are in different places in @code{gforth} and
                   11389: @code{gforth-fast}.  This means that you cannot write a @code{NEXT}
                   11390: routine that works on both versions; so for doing @code{NEXT}, I
                   11391: recomment jumping to @code{' noop >code-address}, which contains nothing
                   11392: but a @code{NEXT}.
1.21      crook    11393: 
1.78      anton    11394: For general accesses to the inner interpreter's registers, the easiest
                   11395: solution is to use explicit register declarations (@pxref{Explicit Reg
                   11396: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
                   11397: all of the inner interpreter's registers: You have to compile Gforth
                   11398: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
                   11399: the appropriate declarations must be present in the @code{machine.h}
                   11400: file (see @code{mips.h} for an example; you can find a full list of all
                   11401: declarable register symbols with @code{grep register engine.c}). If you
                   11402: give explicit registers to all variables that are declared at the
                   11403: beginning of @code{engine()}, you should be able to use the other
                   11404: caller-saved registers for temporary storage. Alternatively, you can use
                   11405: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
                   11406: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
                   11407: reserve a register (however, this restriction on register allocation may
                   11408: slow Gforth significantly).
1.44      crook    11409: 
1.78      anton    11410: If this solution is not viable (e.g., because @code{gcc} does not allow
                   11411: you to explicitly declare all the registers you need), you have to find
                   11412: out by looking at the code where the inner interpreter's registers
                   11413: reside and which registers can be used for temporary storage. You can
                   11414: get an assembly listing of the engine's code with @code{make engine.s}.
1.44      crook    11415: 
1.78      anton    11416: In any case, it is good practice to abstract your assembly code from the
                   11417: actual register allocation. E.g., if the data stack pointer resides in
                   11418: register @code{$17}, create an alias for this register called @code{sp},
                   11419: and use that in your assembly code.
1.21      crook    11420: 
1.78      anton    11421: @cindex code words, portable
                   11422: Another option for implementing normal and defining words efficiently
                   11423: is to add the desired functionality to the source of Gforth. For normal
                   11424: words you just have to edit @file{primitives} (@pxref{Automatic
                   11425: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   11426: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   11427: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44      crook    11428: 
1.78      anton    11429: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
                   11430: @subsection Common Assembler
1.44      crook    11431: 
1.78      anton    11432: The assemblers in Gforth generally use a postfix syntax, i.e., the
                   11433: instruction name follows the operands.
1.21      crook    11434: 
1.78      anton    11435: The operands are passed in the usual order (the same that is used in the
                   11436: manual of the architecture).  Since they all are Forth words, they have
                   11437: to be separated by spaces; you can also use Forth words to compute the
                   11438: operands.
1.44      crook    11439: 
1.78      anton    11440: The instruction names usually end with a @code{,}.  This makes it easier
                   11441: to visually separate instructions if you put several of them on one
                   11442: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21      crook    11443: 
1.78      anton    11444: Registers are usually specified by number; e.g., (decimal) @code{11}
                   11445: specifies registers R11 and F11 on the Alpha architecture (which one,
                   11446: depends on the instruction).  The usual names are also available, e.g.,
                   11447: @code{s2} for R11 on Alpha.
1.21      crook    11448: 
1.78      anton    11449: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
                   11450: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
                   11451: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
                   11452: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
                   11453: conditions are specified in a way specific to each assembler.
1.1       anton    11454: 
1.78      anton    11455: Note that the register assignments of the Gforth engine can change
                   11456: between Gforth versions, or even between different compilations of the
                   11457: same Gforth version (e.g., if you use a different GCC version).  So if
                   11458: you want to refer to Gforth's registers (e.g., the stack pointer or
                   11459: TOS), I recommend defining your own words for refering to these
                   11460: registers, and using them later on; then you can easily adapt to a
                   11461: changed register assignment.  The stability of the register assignment
                   11462: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1       anton    11463: 
1.78      anton    11464: In particular, the return stack pointer and the instruction pointer are
                   11465: in memory in @code{gforth}, and usually in registers in
                   11466: @code{gforth-fast}.  The most common use of these registers is to
                   11467: dispatch to the next word (the @code{next} routine).  A portable way to
                   11468: do this is to jump to @code{' noop >code-address} (of course, this is
                   11469: less efficient than integrating the @code{next} code and scheduling it
                   11470: well).
1.1       anton    11471: 
1.78      anton    11472: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
                   11473: @subsection Common Disassembler
1.1       anton    11474: 
1.78      anton    11475: You can disassemble a @code{code} word with @code{see}
                   11476: (@pxref{Debugging}).  You can disassemble a section of memory with
1.1       anton    11477: 
1.78      anton    11478: doc-disasm
1.44      crook    11479: 
1.78      anton    11480: The disassembler generally produces output that can be fed into the
                   11481: assembler (i.e., same syntax, etc.).  It also includes additional
                   11482: information in comments.  In particular, the address of the instruction
                   11483: is given in a comment before the instruction.
1.1       anton    11484: 
1.78      anton    11485: @code{See} may display more or less than the actual code of the word,
                   11486: because the recognition of the end of the code is unreliable.  You can
                   11487: use @code{disasm} if it did not display enough.  It may display more, if
                   11488: the code word is not immediately followed by a named word.  If you have
                   11489: something else there, you can follow the word with @code{align last @ ,}
                   11490: to ensure that the end is recognized.
1.21      crook    11491: 
1.78      anton    11492: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
                   11493: @subsection 386 Assembler
1.44      crook    11494: 
1.78      anton    11495: The 386 assembler included in Gforth was written by Bernd Paysan, it's
                   11496: available under GPL, and originally part of bigFORTH.
1.21      crook    11497: 
1.78      anton    11498: The 386 disassembler included in Gforth was written by Andrew McKewan
                   11499: and is in the public domain.
1.21      crook    11500: 
1.78      anton    11501: The disassembler displays code in prefix Intel syntax.
1.21      crook    11502: 
1.78      anton    11503: The assembler uses a postfix syntax with reversed parameters.
1.1       anton    11504: 
1.78      anton    11505: The assembler includes all instruction of the Athlon, i.e. 486 core
                   11506: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
                   11507: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
                   11508: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1       anton    11509: 
1.78      anton    11510: There are several prefixes to switch between different operation sizes,
                   11511: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
                   11512: double-word accesses. Addressing modes can be switched with @code{.wa}
                   11513: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
                   11514: need a prefix for byte register names (@code{AL} et al).
1.1       anton    11515: 
1.78      anton    11516: For floating point operations, the prefixes are @code{.fs} (IEEE
                   11517: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
                   11518: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21      crook    11519: 
1.78      anton    11520: The MMX opcodes don't have size prefixes, they are spelled out like in
                   11521: the Intel assembler. Instead of move from and to memory, there are
                   11522: PLDQ/PLDD and PSTQ/PSTD.
1.21      crook    11523: 
1.78      anton    11524: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
                   11525: ax.  Immediate values are indicated by postfixing them with @code{#},
                   11526: e.g., @code{3 #}.  Here are some examples of addressing modes:
1.21      crook    11527: 
1.26      crook    11528: @example
1.78      anton    11529: 3 #          \ immediate
                   11530: ax           \ register
                   11531: 100 di d)    \ 100[edi]
                   11532: 4 bx cx di)  \ 4[ebx][ecx]
                   11533: di ax *4 i)  \ [edi][eax*4]
                   11534: 20 ax *4 i#) \ 20[eax*4]
1.26      crook    11535: @end example
1.21      crook    11536: 
1.78      anton    11537: Some example of instructions are:
1.1       anton    11538: 
                   11539: @example
1.78      anton    11540: ax bx mov             \ move ebx,eax
                   11541: 3 # ax mov            \ mov eax,3
                   11542: 100 di ) ax mov       \ mov eax,100[edi]
                   11543: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
                   11544: .w ax bx mov          \ mov bx,ax
1.1       anton    11545: @end example
                   11546: 
1.78      anton    11547: The following forms are supported for binary instructions:
1.1       anton    11548: 
                   11549: @example
1.78      anton    11550: <reg> <reg> <inst>
                   11551: <n> # <reg> <inst>
                   11552: <mem> <reg> <inst>
                   11553: <reg> <mem> <inst>
1.1       anton    11554: @end example
                   11555: 
1.78      anton    11556: Immediate to memory is not supported.  The shift/rotate syntax is:
1.1       anton    11557: 
1.26      crook    11558: @example
1.78      anton    11559: <reg/mem> 1 # shl \ shortens to shift without immediate
                   11560: <reg/mem> 4 # shl
                   11561: <reg/mem> cl shl
1.26      crook    11562: @end example
1.1       anton    11563: 
1.78      anton    11564: Precede string instructions (@code{movs} etc.) with @code{.b} to get
                   11565: the byte version.
1.1       anton    11566: 
1.78      anton    11567: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
                   11568: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
                   11569: pc < >= <= >}. (Note that most of these words shadow some Forth words
                   11570: when @code{assembler} is in front of @code{forth} in the search path,
                   11571: e.g., in @code{code} words).  Currently the control structure words use
                   11572: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
                   11573: to shuffle them (you can also use @code{swap} etc.).
1.21      crook    11574: 
1.78      anton    11575: Here is an example of a @code{code} word (assumes that the stack pointer
                   11576: is in esi and the TOS is in ebx):
1.21      crook    11577: 
1.26      crook    11578: @example
1.78      anton    11579: code my+ ( n1 n2 -- n )
                   11580:     4 si D) bx add
                   11581:     4 # si add
                   11582:     Next
                   11583: end-code
1.26      crook    11584: @end example
1.21      crook    11585: 
1.78      anton    11586: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
                   11587: @subsection Alpha Assembler
1.21      crook    11588: 
1.78      anton    11589: The Alpha assembler and disassembler were originally written by Bernd
                   11590: Thallner.
1.26      crook    11591: 
1.78      anton    11592: The register names @code{a0}--@code{a5} are not available to avoid
                   11593: shadowing hex numbers.
1.2       jwilke   11594: 
1.78      anton    11595: Immediate forms of arithmetic instructions are distinguished by a
                   11596: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
                   11597: does not count as arithmetic instruction).
1.2       jwilke   11598: 
1.78      anton    11599: You have to specify all operands to an instruction, even those that
                   11600: other assemblers consider optional, e.g., the destination register for
                   11601: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2       jwilke   11602: 
1.78      anton    11603: You can specify conditions for @code{if,} by removing the first @code{b}
                   11604: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2       jwilke   11605: 
1.26      crook    11606: @example
1.78      anton    11607: 11 fgt if, \ if F11>0e
                   11608:   ...
                   11609: endif,
1.26      crook    11610: @end example
1.2       jwilke   11611: 
1.78      anton    11612: @code{fbgt,} gives @code{fgt}.  
                   11613: 
                   11614: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
                   11615: @subsection MIPS assembler
1.2       jwilke   11616: 
1.78      anton    11617: The MIPS assembler was originally written by Christian Pirker.
1.2       jwilke   11618: 
1.78      anton    11619: Currently the assembler and disassembler only cover the MIPS-I
                   11620: architecture (R3000), and don't support FP instructions.
1.2       jwilke   11621: 
1.78      anton    11622: The register names @code{$a0}--@code{$a3} are not available to avoid
                   11623: shadowing hex numbers.
1.2       jwilke   11624: 
1.78      anton    11625: Because there is no way to distinguish registers from immediate values,
                   11626: you have to explicitly use the immediate forms of instructions, i.e.,
                   11627: @code{addiu,}, not just @code{addu,} (@command{as} does this
                   11628: implicitly).
1.2       jwilke   11629: 
1.78      anton    11630: If the architecture manual specifies several formats for the instruction
                   11631: (e.g., for @code{jalr,}), you usually have to use the one with more
                   11632: arguments (i.e., two for @code{jalr,}).  When in doubt, see
                   11633: @code{arch/mips/testasm.fs} for an example of correct use.
1.2       jwilke   11634: 
1.78      anton    11635: Branches and jumps in the MIPS architecture have a delay slot.  You have
                   11636: to fill it yourself (the simplest way is to use @code{nop,}), the
                   11637: assembler does not do it for you (unlike @command{as}).  Even
                   11638: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
                   11639: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
                   11640: and @code{then,} just specify branch targets, they are not affected.
1.2       jwilke   11641: 
1.78      anton    11642: Note that you must not put branches, jumps, or @code{li,} into the delay
                   11643: slot: @code{li,} may expand to several instructions, and control flow
                   11644: instructions may not be put into the branch delay slot in any case.
1.2       jwilke   11645: 
1.78      anton    11646: For branches the argument specifying the target is a relative address;
                   11647: You have to add the address of the delay slot to get the absolute
                   11648: address.
1.1       anton    11649: 
1.78      anton    11650: The MIPS architecture also has load delay slots and restrictions on
                   11651: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
                   11652: yourself to satisfy these restrictions, the assembler does not do it for
                   11653: you.
1.1       anton    11654: 
1.78      anton    11655: You can specify the conditions for @code{if,} etc. by taking a
                   11656: conditional branch and leaving away the @code{b} at the start and the
                   11657: @code{,} at the end.  E.g.,
1.1       anton    11658: 
1.26      crook    11659: @example
1.78      anton    11660: 4 5 eq if,
                   11661:   ... \ do something if $4 equals $5
                   11662: then,
1.26      crook    11663: @end example
1.1       anton    11664: 
1.78      anton    11665: @node Other assemblers,  , MIPS assembler, Assembler and Code Words
                   11666: @subsection Other assemblers
                   11667: 
                   11668: If you want to contribute another assembler/disassembler, please contact
                   11669: us (@email{bug-gforth@@gnu.org}) to check if we have such an assembler
                   11670: already.  If you are writing them from scratch, please use a similar
                   11671: syntax style as the one we use (i.e., postfix, commas at the end of the
                   11672: instruction names, @pxref{Common Assembler}); make the output of the
                   11673: disassembler be valid input for the assembler, and keep the style
                   11674: similar to the style we used.
                   11675: 
                   11676: Hints on implementation: The most important part is to have a good test
                   11677: suite that contains all instructions.  Once you have that, the rest is
                   11678: easy.  For actual coding you can take a look at
                   11679: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
                   11680: the assembler and disassembler, avoiding redundancy and some potential
                   11681: bugs.  You can also look at that file (and @pxref{Advanced does> usage
                   11682: example}) to get ideas how to factor a disassembler.
                   11683: 
                   11684: Start with the disassembler, because it's easier to reuse data from the
                   11685: disassembler for the assembler than the other way round.
1.1       anton    11686: 
1.78      anton    11687: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
                   11688: how simple it can be.
1.1       anton    11689: 
1.78      anton    11690: @c -------------------------------------------------------------
                   11691: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
                   11692: @section Threading Words
                   11693: @cindex threading words
1.1       anton    11694: 
1.78      anton    11695: @cindex code address
                   11696: These words provide access to code addresses and other threading stuff
                   11697: in Gforth (and, possibly, other interpretive Forths). It more or less
                   11698: abstracts away the differences between direct and indirect threading
                   11699: (and, for direct threading, the machine dependences). However, at
                   11700: present this wordset is still incomplete. It is also pretty low-level;
                   11701: some day it will hopefully be made unnecessary by an internals wordset
                   11702: that abstracts implementation details away completely.
1.1       anton    11703: 
1.78      anton    11704: The terminology used here stems from indirect threaded Forth systems; in
                   11705: such a system, the XT of a word is represented by the CFA (code field
                   11706: address) of a word; the CFA points to a cell that contains the code
                   11707: address.  The code address is the address of some machine code that
                   11708: performs the run-time action of invoking the word (e.g., the
                   11709: @code{dovar:} routine pushes the address of the body of the word (a
                   11710: variable) on the stack
                   11711: ).
1.1       anton    11712: 
1.78      anton    11713: @cindex code address
                   11714: @cindex code field address
                   11715: In an indirect threaded Forth, you can get the code address of @i{name}
                   11716: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
                   11717: >code-address}, independent of the threading method.
1.1       anton    11718: 
1.78      anton    11719: doc-threading-method
                   11720: doc->code-address
                   11721: doc-code-address!
1.1       anton    11722: 
1.78      anton    11723: @cindex @code{does>}-handler
                   11724: @cindex @code{does>}-code
                   11725: For a word defined with @code{DOES>}, the code address usually points to
                   11726: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
                   11727: routine (in Gforth on some platforms, it can also point to the dodoes
                   11728: routine itself).  What you are typically interested in, though, is
                   11729: whether a word is a @code{DOES>}-defined word, and what Forth code it
                   11730: executes; @code{>does-code} tells you that.
1.1       anton    11731: 
1.78      anton    11732: doc->does-code
1.1       anton    11733: 
1.78      anton    11734: To create a @code{DOES>}-defined word with the following basic words,
                   11735: you have to set up a @code{DOES>}-handler with @code{does-handler!};
                   11736: @code{/does-handler} aus behind you have to place your executable Forth
                   11737: code.  Finally you have to create a word and modify its behaviour with
                   11738: @code{does-handler!}.
1.1       anton    11739: 
1.78      anton    11740: doc-does-code!
                   11741: doc-does-handler!
                   11742: doc-/does-handler
1.1       anton    11743: 
1.78      anton    11744: The code addresses produced by various defining words are produced by
                   11745: the following words:
1.1       anton    11746: 
1.78      anton    11747: doc-docol:
                   11748: doc-docon:
                   11749: doc-dovar:
                   11750: doc-douser:
                   11751: doc-dodefer:
                   11752: doc-dofield:
1.1       anton    11753: 
1.26      crook    11754: @c -------------------------------------------------------------
1.78      anton    11755: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21      crook    11756: @section Passing Commands to the Operating System
                   11757: @cindex operating system - passing commands
                   11758: @cindex shell commands
                   11759: 
                   11760: Gforth allows you to pass an arbitrary string to the host operating
                   11761: system shell (if such a thing exists) for execution.
                   11762: 
1.44      crook    11763: 
1.21      crook    11764: doc-sh
                   11765: doc-system
                   11766: doc-$?
1.23      crook    11767: doc-getenv
1.21      crook    11768: 
1.44      crook    11769: 
1.26      crook    11770: @c -------------------------------------------------------------
1.47      crook    11771: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
                   11772: @section Keeping track of Time
                   11773: @cindex time-related words
                   11774: 
                   11775: doc-ms
                   11776: doc-time&date
1.79      anton    11777: doc-utime
                   11778: doc-cputime
1.47      crook    11779: 
                   11780: 
                   11781: @c -------------------------------------------------------------
                   11782: @node Miscellaneous Words,  , Keeping track of Time, Words
1.21      crook    11783: @section Miscellaneous Words
                   11784: @cindex miscellaneous words
                   11785: 
1.29      crook    11786: @comment TODO find homes for these
                   11787: 
1.26      crook    11788: These section lists the ANS Forth words that are not documented
1.21      crook    11789: elsewhere in this manual. Ultimately, they all need proper homes.
                   11790: 
                   11791: doc-[compile]
1.68      anton    11792: doc-quit
1.44      crook    11793: 
1.26      crook    11794: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    11795: (@pxref{ANS conformance}):
1.21      crook    11796: 
                   11797: @code{EDITOR} 
                   11798: @code{EMIT?} 
                   11799: @code{FORGET} 
                   11800: 
1.24      anton    11801: @c ******************************************************************
                   11802: @node Error messages, Tools, Words, Top
                   11803: @chapter Error messages
                   11804: @cindex error messages
                   11805: @cindex backtrace
                   11806: 
                   11807: A typical Gforth error message looks like this:
                   11808: 
                   11809: @example
                   11810: in file included from :-1
                   11811: in file included from ./yyy.fs:1
                   11812: ./xxx.fs:4: Invalid memory address
                   11813: bar
                   11814: ^^^
1.79      anton    11815: Backtrace:
1.25      anton    11816: $400E664C @@
                   11817: $400E6664 foo
1.24      anton    11818: @end example
                   11819: 
                   11820: The message identifying the error is @code{Invalid memory address}.  The
                   11821: error happened when text-interpreting line 4 of the file
                   11822: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   11823: word on the line where the error happened, is pointed out (with
                   11824: @code{^^^}).
                   11825: 
                   11826: The file containing the error was included in line 1 of @file{./yyy.fs},
                   11827: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   11828: @file{yyy.fs} as command-line parameter to Gforth).
                   11829: 
                   11830: At the end of the error message you find a return stack dump that can be
                   11831: interpreted as a backtrace (possibly empty). On top you find the top of
                   11832: the return stack when the @code{throw} happened, and at the bottom you
                   11833: find the return stack entry just above the return stack of the topmost
                   11834: text interpreter.
                   11835: 
                   11836: To the right of most return stack entries you see a guess for the word
                   11837: that pushed that return stack entry as its return address. This gives a
                   11838: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   11839: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   11840: address} exception).
                   11841: 
                   11842: Note that the backtrace is not perfect: We don't know which return stack
                   11843: entries are return addresses (so we may get false positives); and in
                   11844: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   11845: address the word that pushed the return address, so for some return
                   11846: addresses you see no names in the return stack dump.
1.25      anton    11847: 
                   11848: @cindex @code{catch} and backtraces
                   11849: The return stack dump represents the return stack at the time when a
                   11850: specific @code{throw} was executed.  In programs that make use of
                   11851: @code{catch}, it is not necessarily clear which @code{throw} should be
                   11852: used for the return stack dump (e.g., consider one @code{throw} that
                   11853: indicates an error, which is caught, and during recovery another error
1.42      anton    11854: happens; which @code{throw} should be used for the stack dump?).  Gforth
1.25      anton    11855: presents the return stack dump for the first @code{throw} after the last
                   11856: executed (not returned-to) @code{catch}; this works well in the usual
                   11857: case.
                   11858: 
                   11859: @cindex @code{gforth-fast} and backtraces
                   11860: @cindex @code{gforth-fast}, difference from @code{gforth}
                   11861: @cindex backtraces with @code{gforth-fast}
                   11862: @cindex return stack dump with @code{gforth-fast}
1.79      anton    11863: @code{Gforth} is able to do a return stack dump for throws generated
1.25      anton    11864: from primitives (e.g., invalid memory address, stack empty etc.);
                   11865: @code{gforth-fast} is only able to do a return stack dump from a
                   11866: directly called @code{throw} (including @code{abort} etc.).  This is the
1.30      anton    11867: only difference (apart from a speed factor of between 1.15 (K6-2) and
1.78      anton    11868: 2 (21264)) between @code{gforth} and @code{gforth-fast}.  Given an
1.30      anton    11869: exception caused by a primitive in @code{gforth-fast}, you will
                   11870: typically see no return stack dump at all; however, if the exception is
                   11871: caught by @code{catch} (e.g., for restoring some state), and then
                   11872: @code{throw}n again, the return stack dump will be for the first such
                   11873: @code{throw}.
1.2       jwilke   11874: 
1.5       anton    11875: @c ******************************************************************
1.24      anton    11876: @node Tools, ANS conformance, Error messages, Top
1.1       anton    11877: @chapter Tools
                   11878: 
                   11879: @menu
                   11880: * ANS Report::                  Report the words used, sorted by wordset.
                   11881: @end menu
                   11882: 
                   11883: See also @ref{Emacs and Gforth}.
                   11884: 
                   11885: @node ANS Report,  , Tools, Tools
                   11886: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   11887: @cindex @file{ans-report.fs}
                   11888: @cindex report the words used in your program
                   11889: @cindex words used in your program
                   11890: 
                   11891: If you want to label a Forth program as ANS Forth Program, you must
                   11892: document which wordsets the program uses; for extension wordsets, it is
                   11893: helpful to list the words the program requires from these wordsets
                   11894: (because Forth systems are allowed to provide only some words of them).
                   11895: 
                   11896: The @file{ans-report.fs} tool makes it easy for you to determine which
                   11897: words from which wordset and which non-ANS words your application
                   11898: uses. You simply have to include @file{ans-report.fs} before loading the
                   11899: program you want to check. After loading your program, you can get the
                   11900: report with @code{print-ans-report}. A typical use is to run this as
                   11901: batch job like this:
                   11902: @example
                   11903: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   11904: @end example
                   11905: 
                   11906: The output looks like this (for @file{compat/control.fs}):
                   11907: @example
                   11908: The program uses the following words
                   11909: from CORE :
                   11910: : POSTPONE THEN ; immediate ?dup IF 0= 
                   11911: from BLOCK-EXT :
                   11912: \ 
                   11913: from FILE :
                   11914: ( 
                   11915: @end example
                   11916: 
                   11917: @subsection Caveats
                   11918: 
                   11919: Note that @file{ans-report.fs} just checks which words are used, not whether
                   11920: they are used in an ANS Forth conforming way!
                   11921: 
                   11922: Some words are defined in several wordsets in the
                   11923: standard. @file{ans-report.fs} reports them for only one of the
                   11924: wordsets, and not necessarily the one you expect. It depends on usage
                   11925: which wordset is the right one to specify. E.g., if you only use the
                   11926: compilation semantics of @code{S"}, it is a Core word; if you also use
                   11927: its interpretation semantics, it is a File word.
                   11928: 
                   11929: @c ******************************************************************
1.65      anton    11930: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1       anton    11931: @chapter ANS conformance
                   11932: @cindex ANS conformance of Gforth
                   11933: 
                   11934: To the best of our knowledge, Gforth is an
                   11935: 
                   11936: ANS Forth System
                   11937: @itemize @bullet
                   11938: @item providing the Core Extensions word set
                   11939: @item providing the Block word set
                   11940: @item providing the Block Extensions word set
                   11941: @item providing the Double-Number word set
                   11942: @item providing the Double-Number Extensions word set
                   11943: @item providing the Exception word set
                   11944: @item providing the Exception Extensions word set
                   11945: @item providing the Facility word set
1.40      anton    11946: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1       anton    11947: @item providing the File Access word set
                   11948: @item providing the File Access Extensions word set
                   11949: @item providing the Floating-Point word set
                   11950: @item providing the Floating-Point Extensions word set
                   11951: @item providing the Locals word set
                   11952: @item providing the Locals Extensions word set
                   11953: @item providing the Memory-Allocation word set
                   11954: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   11955: @item providing the Programming-Tools word set
                   11956: @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
                   11957: @item providing the Search-Order word set
                   11958: @item providing the Search-Order Extensions word set
                   11959: @item providing the String word set
                   11960: @item providing the String Extensions word set (another easy one)
                   11961: @end itemize
                   11962: 
                   11963: @cindex system documentation
                   11964: In addition, ANS Forth systems are required to document certain
                   11965: implementation choices. This chapter tries to meet these
                   11966: requirements. In many cases it gives a way to ask the system for the
                   11967: information instead of providing the information directly, in
                   11968: particular, if the information depends on the processor, the operating
                   11969: system or the installation options chosen, or if they are likely to
                   11970: change during the maintenance of Gforth.
                   11971: 
                   11972: @comment The framework for the rest has been taken from pfe.
                   11973: 
                   11974: @menu
                   11975: * The Core Words::              
                   11976: * The optional Block word set::  
                   11977: * The optional Double Number word set::  
                   11978: * The optional Exception word set::  
                   11979: * The optional Facility word set::  
                   11980: * The optional File-Access word set::  
                   11981: * The optional Floating-Point word set::  
                   11982: * The optional Locals word set::  
                   11983: * The optional Memory-Allocation word set::  
                   11984: * The optional Programming-Tools word set::  
                   11985: * The optional Search-Order word set::  
                   11986: @end menu
                   11987: 
                   11988: 
                   11989: @c =====================================================================
                   11990: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   11991: @comment  node-name,  next,  previous,  up
                   11992: @section The Core Words
                   11993: @c =====================================================================
                   11994: @cindex core words, system documentation
                   11995: @cindex system documentation, core words
                   11996: 
                   11997: @menu
                   11998: * core-idef::                   Implementation Defined Options                   
                   11999: * core-ambcond::                Ambiguous Conditions                
                   12000: * core-other::                  Other System Documentation                  
                   12001: @end menu
                   12002: 
                   12003: @c ---------------------------------------------------------------------
                   12004: @node core-idef, core-ambcond, The Core Words, The Core Words
                   12005: @subsection Implementation Defined Options
                   12006: @c ---------------------------------------------------------------------
                   12007: @cindex core words, implementation-defined options
                   12008: @cindex implementation-defined options, core words
                   12009: 
                   12010: 
                   12011: @table @i
                   12012: @item (Cell) aligned addresses:
                   12013: @cindex cell-aligned addresses
                   12014: @cindex aligned addresses
                   12015: processor-dependent. Gforth's alignment words perform natural alignment
                   12016: (e.g., an address aligned for a datum of size 8 is divisible by
                   12017: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   12018: 
                   12019: @item @code{EMIT} and non-graphic characters:
                   12020: @cindex @code{EMIT} and non-graphic characters
                   12021: @cindex non-graphic characters and @code{EMIT}
                   12022: The character is output using the C library function (actually, macro)
                   12023: @code{putc}.
                   12024: 
                   12025: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   12026: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   12027: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   12028: @cindex @code{ACCEPT}, editing
                   12029: @cindex @code{EXPECT}, editing
                   12030: This is modeled on the GNU readline library (@pxref{Readline
                   12031: Interaction, , Command Line Editing, readline, The GNU Readline
                   12032: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   12033: producing a full word completion every time you type it (instead of
1.28      crook    12034: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    12035: 
                   12036: @item character set:
                   12037: @cindex character set
                   12038: The character set of your computer and display device. Gforth is
                   12039: 8-bit-clean (but some other component in your system may make trouble).
                   12040: 
                   12041: @item Character-aligned address requirements:
                   12042: @cindex character-aligned address requirements
                   12043: installation-dependent. Currently a character is represented by a C
                   12044: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   12045: (Comments on that requested).
                   12046: 
                   12047: @item character-set extensions and matching of names:
                   12048: @cindex character-set extensions and matching of names
1.26      crook    12049: @cindex case-sensitivity for name lookup
                   12050: @cindex name lookup, case-sensitivity
                   12051: @cindex locale and case-sensitivity
1.21      crook    12052: Any character except the ASCII NUL character can be used in a
1.1       anton    12053: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47      crook    12054: matching is performed using the C library function @code{strncasecmp}, whose
1.1       anton    12055: function is probably influenced by the locale. E.g., the @code{C} locale
                   12056: does not know about accents and umlauts, so they are matched
                   12057: case-sensitively in that locale. For portability reasons it is best to
                   12058: write programs such that they work in the @code{C} locale. Then one can
                   12059: use libraries written by a Polish programmer (who might use words
                   12060: containing ISO Latin-2 encoded characters) and by a French programmer
                   12061: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   12062: funny results for some of the words (which ones, depends on the font you
                   12063: are using)). Also, the locale you prefer may not be available in other
                   12064: operating systems. Hopefully, Unicode will solve these problems one day.
                   12065: 
                   12066: @item conditions under which control characters match a space delimiter:
                   12067: @cindex space delimiters
                   12068: @cindex control characters as delimiters
                   12069: If @code{WORD} is called with the space character as a delimiter, all
                   12070: white-space characters (as identified by the C macro @code{isspace()})
                   12071: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44      crook    12072: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.79      anton    12073: like @code{PARSE} otherwise. @code{Name}, which is used by the outer
1.1       anton    12074: interpreter (aka text interpreter) by default, treats all white-space
                   12075: characters as delimiters.
                   12076: 
1.26      crook    12077: @item format of the control-flow stack:
                   12078: @cindex control-flow stack, format
                   12079: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    12080: stack item in cells is given by the constant @code{cs-item-size}. At the
                   12081: time of this writing, an item consists of a (pointer to a) locals list
                   12082: (third), an address in the code (second), and a tag for identifying the
                   12083: item (TOS). The following tags are used: @code{defstart},
                   12084: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   12085: @code{scopestart}.
                   12086: 
                   12087: @item conversion of digits > 35
                   12088: @cindex digits > 35
                   12089: The characters @code{[\]^_'} are the digits with the decimal value
                   12090: 36@minus{}41. There is no way to input many of the larger digits.
                   12091: 
                   12092: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   12093: @cindex @code{EXPECT}, display after end of input
                   12094: @cindex @code{ACCEPT}, display after end of input
                   12095: The cursor is moved to the end of the entered string. If the input is
                   12096: terminated using the @kbd{Return} key, a space is typed.
                   12097: 
                   12098: @item exception abort sequence of @code{ABORT"}:
                   12099: @cindex exception abort sequence of @code{ABORT"}
                   12100: @cindex @code{ABORT"}, exception abort sequence
                   12101: The error string is stored into the variable @code{"error} and a
                   12102: @code{-2 throw} is performed.
                   12103: 
                   12104: @item input line terminator:
                   12105: @cindex input line terminator
                   12106: @cindex line terminator on input
1.26      crook    12107: @cindex newline character on input
1.1       anton    12108: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   12109: lines. One of these characters is typically produced when you type the
                   12110: @kbd{Enter} or @kbd{Return} key.
                   12111: 
                   12112: @item maximum size of a counted string:
                   12113: @cindex maximum size of a counted string
                   12114: @cindex counted string, maximum size
                   12115: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79      anton    12116: on all platforms, but this may change.
1.1       anton    12117: 
                   12118: @item maximum size of a parsed string:
                   12119: @cindex maximum size of a parsed string
                   12120: @cindex parsed string, maximum size
                   12121: Given by the constant @code{/line}. Currently 255 characters.
                   12122: 
                   12123: @item maximum size of a definition name, in characters:
                   12124: @cindex maximum size of a definition name, in characters
                   12125: @cindex name, maximum length
                   12126: 31
                   12127: 
                   12128: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   12129: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   12130: @cindex @code{ENVIRONMENT?} string length, maximum
                   12131: 31
                   12132: 
                   12133: @item method of selecting the user input device:
                   12134: @cindex user input device, method of selecting
                   12135: The user input device is the standard input. There is currently no way to
                   12136: change it from within Gforth. However, the input can typically be
                   12137: redirected in the command line that starts Gforth.
                   12138: 
                   12139: @item method of selecting the user output device:
                   12140: @cindex user output device, method of selecting
                   12141: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    12142: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   12143: output when the user output device is a terminal, otherwise the output
                   12144: is buffered.
1.1       anton    12145: 
                   12146: @item methods of dictionary compilation:
                   12147: What are we expected to document here?
                   12148: 
                   12149: @item number of bits in one address unit:
                   12150: @cindex number of bits in one address unit
                   12151: @cindex address unit, size in bits
                   12152: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79      anton    12153: platforms.
1.1       anton    12154: 
                   12155: @item number representation and arithmetic:
                   12156: @cindex number representation and arithmetic
1.79      anton    12157: Processor-dependent. Binary two's complement on all current platforms.
1.1       anton    12158: 
                   12159: @item ranges for integer types:
                   12160: @cindex ranges for integer types
                   12161: @cindex integer types, ranges
                   12162: Installation-dependent. Make environmental queries for @code{MAX-N},
                   12163: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   12164: unsigned (and positive) types is 0. The lower bound for signed types on
                   12165: two's complement and one's complement machines machines can be computed
                   12166: by adding 1 to the upper bound.
                   12167: 
                   12168: @item read-only data space regions:
                   12169: @cindex read-only data space regions
                   12170: @cindex data-space, read-only regions
                   12171: The whole Forth data space is writable.
                   12172: 
                   12173: @item size of buffer at @code{WORD}:
                   12174: @cindex size of buffer at @code{WORD}
                   12175: @cindex @code{WORD} buffer size
                   12176: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   12177: shared with the pictured numeric output string. If overwriting
                   12178: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   12179: space, although only as much can be sensibly used as fits in a counted
                   12180: string.
                   12181: 
                   12182: @item size of one cell in address units:
                   12183: @cindex cell size
                   12184: @code{1 cells .}.
                   12185: 
                   12186: @item size of one character in address units:
                   12187: @cindex char size
1.79      anton    12188: @code{1 chars .}. 1 on all current platforms.
1.1       anton    12189: 
                   12190: @item size of the keyboard terminal buffer:
                   12191: @cindex size of the keyboard terminal buffer
                   12192: @cindex terminal buffer, size
                   12193: Varies. You can determine the size at a specific time using @code{lp@@
                   12194: tib - .}. It is shared with the locals stack and TIBs of files that
                   12195: include the current file. You can change the amount of space for TIBs
                   12196: and locals stack at Gforth startup with the command line option
                   12197: @code{-l}.
                   12198: 
                   12199: @item size of the pictured numeric output buffer:
                   12200: @cindex size of the pictured numeric output buffer
                   12201: @cindex pictured numeric output buffer, size
                   12202: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   12203: shared with @code{WORD}.
                   12204: 
                   12205: @item size of the scratch area returned by @code{PAD}:
                   12206: @cindex size of the scratch area returned by @code{PAD}
                   12207: @cindex @code{PAD} size
                   12208: The remainder of dictionary space. @code{unused pad here - - .}.
                   12209: 
                   12210: @item system case-sensitivity characteristics:
                   12211: @cindex case-sensitivity characteristics
1.26      crook    12212: Dictionary searches are case-insensitive (except in
1.1       anton    12213: @code{TABLE}s). However, as explained above under @i{character-set
                   12214: extensions}, the matching for non-ASCII characters is determined by the
                   12215: locale you are using. In the default @code{C} locale all non-ASCII
                   12216: characters are matched case-sensitively.
                   12217: 
                   12218: @item system prompt:
                   12219: @cindex system prompt
                   12220: @cindex prompt
                   12221: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   12222: 
                   12223: @item division rounding:
                   12224: @cindex division rounding
                   12225: installation dependent. @code{s" floored" environment? drop .}. We leave
                   12226: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
                   12227: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
                   12228: 
                   12229: @item values of @code{STATE} when true:
                   12230: @cindex @code{STATE} values
                   12231: -1.
                   12232: 
                   12233: @item values returned after arithmetic overflow:
                   12234: On two's complement machines, arithmetic is performed modulo
                   12235: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   12236: arithmetic (with appropriate mapping for signed types). Division by zero
                   12237: typically results in a @code{-55 throw} (Floating-point unidentified
1.80      anton    12238: fault) or @code{-10 throw} (divide by zero).
1.1       anton    12239: 
                   12240: @item whether the current definition can be found after @t{DOES>}:
                   12241: @cindex @t{DOES>}, visibility of current definition
                   12242: No.
                   12243: 
                   12244: @end table
                   12245: 
                   12246: @c ---------------------------------------------------------------------
                   12247: @node core-ambcond, core-other, core-idef, The Core Words
                   12248: @subsection Ambiguous conditions
                   12249: @c ---------------------------------------------------------------------
                   12250: @cindex core words, ambiguous conditions
                   12251: @cindex ambiguous conditions, core words
                   12252: 
                   12253: @table @i
                   12254: 
                   12255: @item a name is neither a word nor a number:
                   12256: @cindex name not found
1.26      crook    12257: @cindex undefined word
1.80      anton    12258: @code{-13 throw} (Undefined word).
1.1       anton    12259: 
                   12260: @item a definition name exceeds the maximum length allowed:
1.26      crook    12261: @cindex word name too long
1.1       anton    12262: @code{-19 throw} (Word name too long)
                   12263: 
                   12264: @item addressing a region not inside the various data spaces of the forth system:
                   12265: @cindex Invalid memory address
1.32      anton    12266: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    12267: typically readable. Accessing other addresses gives results dependent on
                   12268: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   12269: address).
                   12270: 
                   12271: @item argument type incompatible with parameter:
1.26      crook    12272: @cindex argument type mismatch
1.1       anton    12273: This is usually not caught. Some words perform checks, e.g., the control
                   12274: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   12275: mismatch).
                   12276: 
                   12277: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   12278: @cindex Interpreting a compile-only word, for @code{'} etc.
                   12279: @cindex execution token of words with undefined execution semantics
                   12280: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   12281: get an execution token for @code{compile-only-error} (which performs a
                   12282: @code{-14 throw} when executed).
                   12283: 
                   12284: @item dividing by zero:
                   12285: @cindex dividing by zero
                   12286: @cindex floating point unidentified fault, integer division
1.80      anton    12287: On some platforms, this produces a @code{-10 throw} (Division by
1.24      anton    12288: zero); on other systems, this typically results in a @code{-55 throw}
                   12289: (Floating-point unidentified fault).
1.1       anton    12290: 
                   12291: @item insufficient data stack or return stack space:
                   12292: @cindex insufficient data stack or return stack space
                   12293: @cindex stack overflow
1.26      crook    12294: @cindex address alignment exception, stack overflow
1.1       anton    12295: @cindex Invalid memory address, stack overflow
                   12296: Depending on the operating system, the installation, and the invocation
                   12297: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    12298: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   12299: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   12300: throw} (Invalid memory address) (depending on the platform and how you
                   12301: achieved the overflow) as soon as the overflow happens. If it is not
                   12302: checked, overflows typically result in mysterious illegal memory
                   12303: accesses, producing @code{-9 throw} (Invalid memory address) or
                   12304: @code{-23 throw} (Address alignment exception); they might also destroy
                   12305: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   12306: various errors in these words.
1.1       anton    12307: 
                   12308: @item insufficient space for loop control parameters:
                   12309: @cindex insufficient space for loop control parameters
1.80      anton    12310: Like other return stack overflows.
1.1       anton    12311: 
                   12312: @item insufficient space in the dictionary:
                   12313: @cindex insufficient space in the dictionary
                   12314: @cindex dictionary overflow
1.12      anton    12315: If you try to allot (either directly with @code{allot}, or indirectly
                   12316: with @code{,}, @code{create} etc.) more memory than available in the
                   12317: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   12318: to access memory beyond the end of the dictionary, the results are
                   12319: similar to stack overflows.
1.1       anton    12320: 
                   12321: @item interpreting a word with undefined interpretation semantics:
                   12322: @cindex interpreting a word with undefined interpretation semantics
                   12323: @cindex Interpreting a compile-only word
                   12324: For some words, we have defined interpretation semantics. For the
                   12325: others: @code{-14 throw} (Interpreting a compile-only word).
                   12326: 
                   12327: @item modifying the contents of the input buffer or a string literal:
                   12328: @cindex modifying the contents of the input buffer or a string literal
                   12329: These are located in writable memory and can be modified.
                   12330: 
                   12331: @item overflow of the pictured numeric output string:
                   12332: @cindex overflow of the pictured numeric output string
                   12333: @cindex pictured numeric output string, overflow
1.24      anton    12334: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    12335: 
                   12336: @item parsed string overflow:
                   12337: @cindex parsed string overflow
                   12338: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   12339: 
                   12340: @item producing a result out of range:
                   12341: @cindex result out of range
                   12342: On two's complement machines, arithmetic is performed modulo
                   12343: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
                   12344: arithmetic (with appropriate mapping for signed types). Division by zero
1.24      anton    12345: typically results in a @code{-10 throw} (divide by zero) or @code{-55
                   12346: throw} (floating point unidentified fault). @code{convert} and
                   12347: @code{>number} currently overflow silently.
1.1       anton    12348: 
                   12349: @item reading from an empty data or return stack:
                   12350: @cindex stack empty
                   12351: @cindex stack underflow
1.24      anton    12352: @cindex return stack underflow
1.1       anton    12353: The data stack is checked by the outer (aka text) interpreter after
                   12354: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   12355: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    12356: depending on operating system, installation, and invocation. If they are
                   12357: caught by a check, they typically result in @code{-4 throw} (Stack
                   12358: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   12359: (Invalid memory address), depending on the platform and which stack
                   12360: underflows and by how much. Note that even if the system uses checking
                   12361: (through the MMU), your program may have to underflow by a significant
                   12362: number of stack items to trigger the reaction (the reason for this is
                   12363: that the MMU, and therefore the checking, works with a page-size
                   12364: granularity).  If there is no checking, the symptoms resulting from an
                   12365: underflow are similar to those from an overflow.  Unbalanced return
1.80      anton    12366: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24      anton    12367: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   12368: throw}).
1.1       anton    12369: 
                   12370: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   12371: @cindex unexpected end of the input buffer
                   12372: @cindex zero-length string as a name
                   12373: @cindex Attempt to use zero-length string as a name
                   12374: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   12375: use zero-length string as a name). Words like @code{'} probably will not
                   12376: find what they search. Note that it is possible to create zero-length
                   12377: names with @code{nextname} (should it not?).
                   12378: 
                   12379: @item @code{>IN} greater than input buffer:
                   12380: @cindex @code{>IN} greater than input buffer
                   12381: The next invocation of a parsing word returns a string with length 0.
                   12382: 
                   12383: @item @code{RECURSE} appears after @code{DOES>}:
                   12384: @cindex @code{RECURSE} appears after @code{DOES>}
                   12385: Compiles a recursive call to the defining word, not to the defined word.
                   12386: 
                   12387: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   12388: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    12389: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    12390: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   12391: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   12392: the end of the file was reached), its source-id may be
                   12393: reused. Therefore, restoring an input source specification referencing a
                   12394: closed file may lead to unpredictable results instead of a @code{-12
                   12395: THROW}.
                   12396: 
                   12397: In the future, Gforth may be able to restore input source specifications
                   12398: from other than the current input source.
                   12399: 
                   12400: @item data space containing definitions gets de-allocated:
                   12401: @cindex data space containing definitions gets de-allocated
                   12402: Deallocation with @code{allot} is not checked. This typically results in
                   12403: memory access faults or execution of illegal instructions.
                   12404: 
                   12405: @item data space read/write with incorrect alignment:
                   12406: @cindex data space read/write with incorrect alignment
                   12407: @cindex alignment faults
1.26      crook    12408: @cindex address alignment exception
1.1       anton    12409: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    12410: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    12411: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   12412: (Invalid memory address). There are reportedly some processors with
1.12      anton    12413: alignment restrictions that do not report violations.
1.1       anton    12414: 
                   12415: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   12416: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   12417: Like other alignment errors.
                   12418: 
                   12419: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   12420: Like other stack underflows.
                   12421: 
                   12422: @item loop control parameters not available:
                   12423: @cindex loop control parameters not available
                   12424: Not checked. The counted loop words simply assume that the top of return
                   12425: stack items are loop control parameters and behave accordingly.
                   12426: 
                   12427: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   12428: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   12429: @cindex last word was headerless
                   12430: @code{abort" last word was headerless"}.
                   12431: 
                   12432: @item name not defined by @code{VALUE} used by @code{TO}:
                   12433: @cindex name not defined by @code{VALUE} used by @code{TO}
                   12434: @cindex @code{TO} on non-@code{VALUE}s
                   12435: @cindex Invalid name argument, @code{TO}
                   12436: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   12437: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   12438: 
                   12439: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   12440: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    12441: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    12442: @code{-13 throw} (Undefined word)
                   12443: 
                   12444: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   12445: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   12446: Gforth behaves as if they were of the same type. I.e., you can predict
                   12447: the behaviour by interpreting all parameters as, e.g., signed.
                   12448: 
                   12449: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   12450: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   12451: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   12452: compilation semantics of @code{TO}.
                   12453: 
                   12454: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    12455: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    12456: @cindex @code{WORD}, string overflow
                   12457: Not checked. The string will be ok, but the count will, of course,
                   12458: contain only the least significant bits of the length.
                   12459: 
                   12460: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   12461: @cindex @code{LSHIFT}, large shift counts
                   12462: @cindex @code{RSHIFT}, large shift counts
                   12463: Processor-dependent. Typical behaviours are returning 0 and using only
                   12464: the low bits of the shift count.
                   12465: 
                   12466: @item word not defined via @code{CREATE}:
                   12467: @cindex @code{>BODY} of non-@code{CREATE}d words
                   12468: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   12469: 
                   12470: @cindex @code{DOES>} of non-@code{CREATE}d words
                   12471: @code{DOES>} changes the execution semantics of the last defined word no
                   12472: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   12473: @code{CREATE , DOES>}.
                   12474: 
                   12475: @item words improperly used outside @code{<#} and @code{#>}:
                   12476: Not checked. As usual, you can expect memory faults.
                   12477: 
                   12478: @end table
                   12479: 
                   12480: 
                   12481: @c ---------------------------------------------------------------------
                   12482: @node core-other,  , core-ambcond, The Core Words
                   12483: @subsection Other system documentation
                   12484: @c ---------------------------------------------------------------------
                   12485: @cindex other system documentation, core words
                   12486: @cindex core words, other system documentation
                   12487: 
                   12488: @table @i
                   12489: @item nonstandard words using @code{PAD}:
                   12490: @cindex @code{PAD} use by nonstandard words
                   12491: None.
                   12492: 
                   12493: @item operator's terminal facilities available:
                   12494: @cindex operator's terminal facilities available
1.80      anton    12495: After processing the OS's command line, Gforth goes into interactive mode,
1.1       anton    12496: and you can give commands to Gforth interactively. The actual facilities
                   12497: available depend on how you invoke Gforth.
                   12498: 
                   12499: @item program data space available:
                   12500: @cindex program data space available
                   12501: @cindex data space available
                   12502: @code{UNUSED .} gives the remaining dictionary space. The total
                   12503: dictionary space can be specified with the @code{-m} switch
                   12504: (@pxref{Invoking Gforth}) when Gforth starts up.
                   12505: 
                   12506: @item return stack space available:
                   12507: @cindex return stack space available
                   12508: You can compute the total return stack space in cells with
                   12509: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   12510: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   12511: 
                   12512: @item stack space available:
                   12513: @cindex stack space available
                   12514: You can compute the total data stack space in cells with
                   12515: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   12516: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   12517: 
                   12518: @item system dictionary space required, in address units:
                   12519: @cindex system dictionary space required, in address units
                   12520: Type @code{here forthstart - .} after startup. At the time of this
                   12521: writing, this gives 80080 (bytes) on a 32-bit system.
                   12522: @end table
                   12523: 
                   12524: 
                   12525: @c =====================================================================
                   12526: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   12527: @section The optional Block word set
                   12528: @c =====================================================================
                   12529: @cindex system documentation, block words
                   12530: @cindex block words, system documentation
                   12531: 
                   12532: @menu
                   12533: * block-idef::                  Implementation Defined Options
                   12534: * block-ambcond::               Ambiguous Conditions               
                   12535: * block-other::                 Other System Documentation                 
                   12536: @end menu
                   12537: 
                   12538: 
                   12539: @c ---------------------------------------------------------------------
                   12540: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   12541: @subsection Implementation Defined Options
                   12542: @c ---------------------------------------------------------------------
                   12543: @cindex implementation-defined options, block words
                   12544: @cindex block words, implementation-defined options
                   12545: 
                   12546: @table @i
                   12547: @item the format for display by @code{LIST}:
                   12548: @cindex @code{LIST} display format
                   12549: First the screen number is displayed, then 16 lines of 64 characters,
                   12550: each line preceded by the line number.
                   12551: 
                   12552: @item the length of a line affected by @code{\}:
                   12553: @cindex length of a line affected by @code{\}
                   12554: @cindex @code{\}, line length in blocks
                   12555: 64 characters.
                   12556: @end table
                   12557: 
                   12558: 
                   12559: @c ---------------------------------------------------------------------
                   12560: @node block-ambcond, block-other, block-idef, The optional Block word set
                   12561: @subsection Ambiguous conditions
                   12562: @c ---------------------------------------------------------------------
                   12563: @cindex block words, ambiguous conditions
                   12564: @cindex ambiguous conditions, block words
                   12565: 
                   12566: @table @i
                   12567: @item correct block read was not possible:
                   12568: @cindex block read not possible
                   12569: Typically results in a @code{throw} of some OS-derived value (between
                   12570: -512 and -2048). If the blocks file was just not long enough, blanks are
                   12571: supplied for the missing portion.
                   12572: 
                   12573: @item I/O exception in block transfer:
                   12574: @cindex I/O exception in block transfer
                   12575: @cindex block transfer, I/O exception
                   12576: Typically results in a @code{throw} of some OS-derived value (between
                   12577: -512 and -2048).
                   12578: 
                   12579: @item invalid block number:
                   12580: @cindex invalid block number
                   12581: @cindex block number invalid
                   12582: @code{-35 throw} (Invalid block number)
                   12583: 
                   12584: @item a program directly alters the contents of @code{BLK}:
                   12585: @cindex @code{BLK}, altering @code{BLK}
                   12586: The input stream is switched to that other block, at the same
                   12587: position. If the storing to @code{BLK} happens when interpreting
                   12588: non-block input, the system will get quite confused when the block ends.
                   12589: 
                   12590: @item no current block buffer for @code{UPDATE}:
                   12591: @cindex @code{UPDATE}, no current block buffer
                   12592: @code{UPDATE} has no effect.
                   12593: 
                   12594: @end table
                   12595: 
                   12596: @c ---------------------------------------------------------------------
                   12597: @node block-other,  , block-ambcond, The optional Block word set
                   12598: @subsection Other system documentation
                   12599: @c ---------------------------------------------------------------------
                   12600: @cindex other system documentation, block words
                   12601: @cindex block words, other system documentation
                   12602: 
                   12603: @table @i
                   12604: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   12605: No restrictions (yet).
                   12606: 
                   12607: @item the number of blocks available for source and data:
                   12608: depends on your disk space.
                   12609: 
                   12610: @end table
                   12611: 
                   12612: 
                   12613: @c =====================================================================
                   12614: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   12615: @section The optional Double Number word set
                   12616: @c =====================================================================
                   12617: @cindex system documentation, double words
                   12618: @cindex double words, system documentation
                   12619: 
                   12620: @menu
                   12621: * double-ambcond::              Ambiguous Conditions              
                   12622: @end menu
                   12623: 
                   12624: 
                   12625: @c ---------------------------------------------------------------------
                   12626: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   12627: @subsection Ambiguous conditions
                   12628: @c ---------------------------------------------------------------------
                   12629: @cindex double words, ambiguous conditions
                   12630: @cindex ambiguous conditions, double words
                   12631: 
                   12632: @table @i
1.29      crook    12633: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   12634: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   12635: The least significant cell of @i{d} is produced.
1.1       anton    12636: 
                   12637: @end table
                   12638: 
                   12639: 
                   12640: @c =====================================================================
                   12641: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   12642: @section The optional Exception word set
                   12643: @c =====================================================================
                   12644: @cindex system documentation, exception words
                   12645: @cindex exception words, system documentation
                   12646: 
                   12647: @menu
                   12648: * exception-idef::              Implementation Defined Options              
                   12649: @end menu
                   12650: 
                   12651: 
                   12652: @c ---------------------------------------------------------------------
                   12653: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   12654: @subsection Implementation Defined Options
                   12655: @c ---------------------------------------------------------------------
                   12656: @cindex implementation-defined options, exception words
                   12657: @cindex exception words, implementation-defined options
                   12658: 
                   12659: @table @i
                   12660: @item @code{THROW}-codes used in the system:
                   12661: @cindex @code{THROW}-codes used in the system
                   12662: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    12663: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    12664: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   12665: allocation operations). The mapping from OS error numbers to throw codes
                   12666: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   12667: undefined OS errors produce a message with a strange number; e.g.,
                   12668: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   12669: @end table
                   12670: 
                   12671: @c =====================================================================
                   12672: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   12673: @section The optional Facility word set
                   12674: @c =====================================================================
                   12675: @cindex system documentation, facility words
                   12676: @cindex facility words, system documentation
                   12677: 
                   12678: @menu
                   12679: * facility-idef::               Implementation Defined Options               
                   12680: * facility-ambcond::            Ambiguous Conditions            
                   12681: @end menu
                   12682: 
                   12683: 
                   12684: @c ---------------------------------------------------------------------
                   12685: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   12686: @subsection Implementation Defined Options
                   12687: @c ---------------------------------------------------------------------
                   12688: @cindex implementation-defined options, facility words
                   12689: @cindex facility words, implementation-defined options
                   12690: 
                   12691: @table @i
                   12692: @item encoding of keyboard events (@code{EKEY}):
                   12693: @cindex keyboard events, encoding in @code{EKEY}
                   12694: @cindex @code{EKEY}, encoding of keyboard events
1.40      anton    12695: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41      anton    12696: Other keys are encoded with the constants @code{k-left}, @code{k-right},
                   12697: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
                   12698: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
                   12699: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40      anton    12700: 
1.1       anton    12701: 
                   12702: @item duration of a system clock tick:
                   12703: @cindex duration of a system clock tick
                   12704: @cindex clock tick duration
                   12705: System dependent. With respect to @code{MS}, the time is specified in
                   12706: microseconds. How well the OS and the hardware implement this, is
                   12707: another question.
                   12708: 
                   12709: @item repeatability to be expected from the execution of @code{MS}:
                   12710: @cindex repeatability to be expected from the execution of @code{MS}
                   12711: @cindex @code{MS}, repeatability to be expected
                   12712: System dependent. On Unix, a lot depends on load. If the system is
                   12713: lightly loaded, and the delay is short enough that Gforth does not get
                   12714: swapped out, the performance should be acceptable. Under MS-DOS and
                   12715: other single-tasking systems, it should be good.
                   12716: 
                   12717: @end table
                   12718: 
                   12719: 
                   12720: @c ---------------------------------------------------------------------
                   12721: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   12722: @subsection Ambiguous conditions
                   12723: @c ---------------------------------------------------------------------
                   12724: @cindex facility words, ambiguous conditions
                   12725: @cindex ambiguous conditions, facility words
                   12726: 
                   12727: @table @i
                   12728: @item @code{AT-XY} can't be performed on user output device:
                   12729: @cindex @code{AT-XY} can't be performed on user output device
                   12730: Largely terminal dependent. No range checks are done on the arguments.
                   12731: No errors are reported. You may see some garbage appearing, you may see
                   12732: simply nothing happen.
                   12733: 
                   12734: @end table
                   12735: 
                   12736: 
                   12737: @c =====================================================================
                   12738: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   12739: @section The optional File-Access word set
                   12740: @c =====================================================================
                   12741: @cindex system documentation, file words
                   12742: @cindex file words, system documentation
                   12743: 
                   12744: @menu
                   12745: * file-idef::                   Implementation Defined Options
                   12746: * file-ambcond::                Ambiguous Conditions                
                   12747: @end menu
                   12748: 
                   12749: @c ---------------------------------------------------------------------
                   12750: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   12751: @subsection Implementation Defined Options
                   12752: @c ---------------------------------------------------------------------
                   12753: @cindex implementation-defined options, file words
                   12754: @cindex file words, implementation-defined options
                   12755: 
                   12756: @table @i
                   12757: @item file access methods used:
                   12758: @cindex file access methods used
                   12759: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   12760: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   12761: @code{wb}): The file is cleared, if it exists, and created, if it does
                   12762: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   12763: @code{create-file} creates a file with 666 permissions modified by your
                   12764: umask.
                   12765: 
                   12766: @item file exceptions:
                   12767: @cindex file exceptions
                   12768: The file words do not raise exceptions (except, perhaps, memory access
                   12769: faults when you pass illegal addresses or file-ids).
                   12770: 
                   12771: @item file line terminator:
                   12772: @cindex file line terminator
                   12773: System-dependent. Gforth uses C's newline character as line
                   12774: terminator. What the actual character code(s) of this are is
                   12775: system-dependent.
                   12776: 
                   12777: @item file name format:
                   12778: @cindex file name format
                   12779: System dependent. Gforth just uses the file name format of your OS.
                   12780: 
                   12781: @item information returned by @code{FILE-STATUS}:
                   12782: @cindex @code{FILE-STATUS}, returned information
                   12783: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   12784: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   12785: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   12786: along with the returned mode.
                   12787: 
                   12788: @item input file state after an exception when including source:
                   12789: @cindex exception when including source
                   12790: All files that are left via the exception are closed.
                   12791: 
1.29      crook    12792: @item @i{ior} values and meaning:
                   12793: @cindex @i{ior} values and meaning
1.68      anton    12794: @cindex @i{wior} values and meaning
1.29      crook    12795: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    12796: intended as throw codes. They typically are in the range
                   12797: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    12798: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    12799: 
                   12800: @item maximum depth of file input nesting:
                   12801: @cindex maximum depth of file input nesting
                   12802: @cindex file input nesting, maximum depth
                   12803: limited by the amount of return stack, locals/TIB stack, and the number
                   12804: of open files available. This should not give you troubles.
                   12805: 
                   12806: @item maximum size of input line:
                   12807: @cindex maximum size of input line
                   12808: @cindex input line size, maximum
                   12809: @code{/line}. Currently 255.
                   12810: 
                   12811: @item methods of mapping block ranges to files:
                   12812: @cindex mapping block ranges to files
                   12813: @cindex files containing blocks
                   12814: @cindex blocks in files
                   12815: By default, blocks are accessed in the file @file{blocks.fb} in the
                   12816: current working directory. The file can be switched with @code{USE}.
                   12817: 
                   12818: @item number of string buffers provided by @code{S"}:
                   12819: @cindex @code{S"}, number of string buffers
                   12820: 1
                   12821: 
                   12822: @item size of string buffer used by @code{S"}:
                   12823: @cindex @code{S"}, size of string buffer
                   12824: @code{/line}. currently 255.
                   12825: 
                   12826: @end table
                   12827: 
                   12828: @c ---------------------------------------------------------------------
                   12829: @node file-ambcond,  , file-idef, The optional File-Access word set
                   12830: @subsection Ambiguous conditions
                   12831: @c ---------------------------------------------------------------------
                   12832: @cindex file words, ambiguous conditions
                   12833: @cindex ambiguous conditions, file words
                   12834: 
                   12835: @table @i
                   12836: @item attempting to position a file outside its boundaries:
                   12837: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   12838: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   12839: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   12840: 
                   12841: @item attempting to read from file positions not yet written:
                   12842: @cindex reading from file positions not yet written
                   12843: End-of-file, i.e., zero characters are read and no error is reported.
                   12844: 
1.29      crook    12845: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   12846: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    12847: An appropriate exception may be thrown, but a memory fault or other
                   12848: problem is more probable.
                   12849: 
1.29      crook    12850: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   12851: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   12852: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   12853: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    12854: thrown.
                   12855: 
                   12856: @item named file cannot be opened (@code{INCLUDED}):
                   12857: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    12858: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    12859: 
                   12860: @item requesting an unmapped block number:
                   12861: @cindex unmapped block numbers
                   12862: There are no unmapped legal block numbers. On some operating systems,
                   12863: writing a block with a large number may overflow the file system and
                   12864: have an error message as consequence.
                   12865: 
                   12866: @item using @code{source-id} when @code{blk} is non-zero:
                   12867: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   12868: @code{source-id} performs its function. Typically it will give the id of
                   12869: the source which loaded the block. (Better ideas?)
                   12870: 
                   12871: @end table
                   12872: 
                   12873: 
                   12874: @c =====================================================================
                   12875: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   12876: @section The optional Floating-Point word set
                   12877: @c =====================================================================
                   12878: @cindex system documentation, floating-point words
                   12879: @cindex floating-point words, system documentation
                   12880: 
                   12881: @menu
                   12882: * floating-idef::               Implementation Defined Options
                   12883: * floating-ambcond::            Ambiguous Conditions            
                   12884: @end menu
                   12885: 
                   12886: 
                   12887: @c ---------------------------------------------------------------------
                   12888: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   12889: @subsection Implementation Defined Options
                   12890: @c ---------------------------------------------------------------------
                   12891: @cindex implementation-defined options, floating-point words
                   12892: @cindex floating-point words, implementation-defined options
                   12893: 
                   12894: @table @i
                   12895: @item format and range of floating point numbers:
                   12896: @cindex format and range of floating point numbers
                   12897: @cindex floating point numbers, format and range
                   12898: System-dependent; the @code{double} type of C.
                   12899: 
1.29      crook    12900: @item results of @code{REPRESENT} when @i{float} is out of range:
                   12901: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    12902: System dependent; @code{REPRESENT} is implemented using the C library
                   12903: function @code{ecvt()} and inherits its behaviour in this respect.
                   12904: 
                   12905: @item rounding or truncation of floating-point numbers:
                   12906: @cindex rounding of floating-point numbers
                   12907: @cindex truncation of floating-point numbers
                   12908: @cindex floating-point numbers, rounding or truncation
                   12909: System dependent; the rounding behaviour is inherited from the hosting C
                   12910: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   12911: nearest, and break ties by rounding to even (i.e., such that the last
                   12912: bit of the mantissa is 0).
                   12913: 
                   12914: @item size of floating-point stack:
                   12915: @cindex floating-point stack size
                   12916: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   12917: the floating-point stack (in floats). You can specify this on startup
                   12918: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   12919: 
                   12920: @item width of floating-point stack:
                   12921: @cindex floating-point stack width 
                   12922: @code{1 floats}.
                   12923: 
                   12924: @end table
                   12925: 
                   12926: 
                   12927: @c ---------------------------------------------------------------------
                   12928: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   12929: @subsection Ambiguous conditions
                   12930: @c ---------------------------------------------------------------------
                   12931: @cindex floating-point words, ambiguous conditions
                   12932: @cindex ambiguous conditions, floating-point words
                   12933: 
                   12934: @table @i
                   12935: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   12936: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   12937: System-dependent. Typically results in a @code{-23 THROW} like other
                   12938: alignment violations.
                   12939: 
                   12940: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   12941: @cindex @code{f@@} used with an address that is not float aligned
                   12942: @cindex @code{f!} used with an address that is not float aligned
                   12943: System-dependent. Typically results in a @code{-23 THROW} like other
                   12944: alignment violations.
                   12945: 
                   12946: @item floating-point result out of range:
                   12947: @cindex floating-point result out of range
1.80      anton    12948: System-dependent. Can result in a @code{-43 throw} (floating point
                   12949: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
                   12950: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1       anton    12951: unidentified fault), or can produce a special value representing, e.g.,
                   12952: Infinity.
                   12953: 
                   12954: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   12955: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   12956: System-dependent. Typically results in an alignment fault like other
                   12957: alignment violations.
                   12958: 
1.35      anton    12959: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   12960: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    12961: The floating-point number is converted into decimal nonetheless.
                   12962: 
                   12963: @item Both arguments are equal to zero (@code{FATAN2}):
                   12964: @cindex @code{FATAN2}, both arguments are equal to zero
                   12965: System-dependent. @code{FATAN2} is implemented using the C library
                   12966: function @code{atan2()}.
                   12967: 
1.29      crook    12968: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   12969: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   12970: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    12971: because of small errors and the tan will be a very large (or very small)
                   12972: but finite number.
                   12973: 
1.29      crook    12974: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   12975: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    12976: The result is rounded to the nearest float.
                   12977: 
                   12978: @item dividing by zero:
                   12979: @cindex dividing by zero, floating-point
                   12980: @cindex floating-point dividing by zero
                   12981: @cindex floating-point unidentified fault, FP divide-by-zero
1.80      anton    12982: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
                   12983: (floating point divide by zero) or @code{-55 throw} (Floating-point
                   12984: unidentified fault).
1.1       anton    12985: 
                   12986: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   12987: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   12988: System dependent. On IEEE-FP based systems the number is converted into
                   12989: an infinity.
                   12990: 
1.29      crook    12991: @item @i{float}<1 (@code{FACOSH}):
                   12992: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    12993: @cindex floating-point unidentified fault, @code{FACOSH}
1.80      anton    12994: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1       anton    12995: 
1.29      crook    12996: @item @i{float}=<-1 (@code{FLNP1}):
                   12997: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    12998: @cindex floating-point unidentified fault, @code{FLNP1}
1.80      anton    12999: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   13000: negative infinity for @i{float}=-1).
1.1       anton    13001: 
1.29      crook    13002: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   13003: @cindex @code{FLN}, @i{float}=<0
                   13004: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    13005: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80      anton    13006: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   13007: negative infinity for @i{float}=0).
1.1       anton    13008: 
1.29      crook    13009: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   13010: @cindex @code{FASINH}, @i{float}<0
                   13011: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    13012: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80      anton    13013: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
                   13014: @code{fasinh} some platforms produce a NaN, others a number (bug in the
                   13015: C library?).
1.1       anton    13016: 
1.29      crook    13017: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   13018: @cindex @code{FACOS}, |@i{float}|>1
                   13019: @cindex @code{FASIN}, |@i{float}|>1
                   13020: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    13021: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80      anton    13022: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1       anton    13023: 
1.29      crook    13024: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   13025: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    13026: @cindex floating-point unidentified fault, @code{F>D}
1.80      anton    13027: Platform-dependent; typically, some double number is produced and no
                   13028: error is reported.
1.1       anton    13029: 
                   13030: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   13031: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80      anton    13032: @code{Precision} characters of the numeric output area are used.  If
                   13033: @code{precision} is too high, these words will smash the data or code
                   13034: close to @code{here}.
1.1       anton    13035: @end table
                   13036: 
                   13037: @c =====================================================================
                   13038: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   13039: @section The optional Locals word set
                   13040: @c =====================================================================
                   13041: @cindex system documentation, locals words
                   13042: @cindex locals words, system documentation
                   13043: 
                   13044: @menu
                   13045: * locals-idef::                 Implementation Defined Options                 
                   13046: * locals-ambcond::              Ambiguous Conditions              
                   13047: @end menu
                   13048: 
                   13049: 
                   13050: @c ---------------------------------------------------------------------
                   13051: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   13052: @subsection Implementation Defined Options
                   13053: @c ---------------------------------------------------------------------
                   13054: @cindex implementation-defined options, locals words
                   13055: @cindex locals words, implementation-defined options
                   13056: 
                   13057: @table @i
                   13058: @item maximum number of locals in a definition:
                   13059: @cindex maximum number of locals in a definition
                   13060: @cindex locals, maximum number in a definition
                   13061: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   13062: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   13063: characters. The number of locals in a definition is bounded by the size
                   13064: of locals-buffer, which contains the names of the locals.
                   13065: 
                   13066: @end table
                   13067: 
                   13068: 
                   13069: @c ---------------------------------------------------------------------
                   13070: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   13071: @subsection Ambiguous conditions
                   13072: @c ---------------------------------------------------------------------
                   13073: @cindex locals words, ambiguous conditions
                   13074: @cindex ambiguous conditions, locals words
                   13075: 
                   13076: @table @i
                   13077: @item executing a named local in interpretation state:
                   13078: @cindex local in interpretation state
                   13079: @cindex Interpreting a compile-only word, for a local
                   13080: Locals have no interpretation semantics. If you try to perform the
                   13081: interpretation semantics, you will get a @code{-14 throw} somewhere
                   13082: (Interpreting a compile-only word). If you perform the compilation
                   13083: semantics, the locals access will be compiled (irrespective of state).
                   13084: 
1.29      crook    13085: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    13086: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   13087: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   13088: @cindex Invalid name argument, @code{TO}
                   13089: @code{-32 throw} (Invalid name argument)
                   13090: 
                   13091: @end table
                   13092: 
                   13093: 
                   13094: @c =====================================================================
                   13095: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   13096: @section The optional Memory-Allocation word set
                   13097: @c =====================================================================
                   13098: @cindex system documentation, memory-allocation words
                   13099: @cindex memory-allocation words, system documentation
                   13100: 
                   13101: @menu
                   13102: * memory-idef::                 Implementation Defined Options                 
                   13103: @end menu
                   13104: 
                   13105: 
                   13106: @c ---------------------------------------------------------------------
                   13107: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   13108: @subsection Implementation Defined Options
                   13109: @c ---------------------------------------------------------------------
                   13110: @cindex implementation-defined options, memory-allocation words
                   13111: @cindex memory-allocation words, implementation-defined options
                   13112: 
                   13113: @table @i
1.29      crook    13114: @item values and meaning of @i{ior}:
                   13115: @cindex  @i{ior} values and meaning
                   13116: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    13117: intended as throw codes. They typically are in the range
                   13118: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    13119: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    13120: 
                   13121: @end table
                   13122: 
                   13123: @c =====================================================================
                   13124: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   13125: @section The optional Programming-Tools word set
                   13126: @c =====================================================================
                   13127: @cindex system documentation, programming-tools words
                   13128: @cindex programming-tools words, system documentation
                   13129: 
                   13130: @menu
                   13131: * programming-idef::            Implementation Defined Options            
                   13132: * programming-ambcond::         Ambiguous Conditions         
                   13133: @end menu
                   13134: 
                   13135: 
                   13136: @c ---------------------------------------------------------------------
                   13137: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   13138: @subsection Implementation Defined Options
                   13139: @c ---------------------------------------------------------------------
                   13140: @cindex implementation-defined options, programming-tools words
                   13141: @cindex programming-tools words, implementation-defined options
                   13142: 
                   13143: @table @i
                   13144: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   13145: @cindex @code{;CODE} ending sequence
                   13146: @cindex @code{CODE} ending sequence
                   13147: @code{END-CODE}
                   13148: 
                   13149: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   13150: @cindex @code{;CODE}, processing input
                   13151: @cindex @code{CODE}, processing input
                   13152: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   13153: the input is processed by the text interpreter, (starting) in interpret
                   13154: state.
                   13155: 
                   13156: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   13157: @cindex @code{ASSEMBLER}, search order capability
                   13158: The ANS Forth search order word set.
                   13159: 
                   13160: @item source and format of display by @code{SEE}:
                   13161: @cindex @code{SEE}, source and format of output
1.80      anton    13162: The source for @code{see} is the executable code used by the inner
1.1       anton    13163: interpreter.  The current @code{see} tries to output Forth source code
1.80      anton    13164: (and on some platforms, assembly code for primitives) as well as
                   13165: possible.
1.1       anton    13166: 
                   13167: @end table
                   13168: 
                   13169: @c ---------------------------------------------------------------------
                   13170: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   13171: @subsection Ambiguous conditions
                   13172: @c ---------------------------------------------------------------------
                   13173: @cindex programming-tools words, ambiguous conditions
                   13174: @cindex ambiguous conditions, programming-tools words
                   13175: 
                   13176: @table @i
                   13177: 
1.21      crook    13178: @item deleting the compilation word list (@code{FORGET}):
                   13179: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    13180: Not implemented (yet).
                   13181: 
1.29      crook    13182: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   13183: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   13184: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    13185: @cindex control-flow stack underflow
                   13186: This typically results in an @code{abort"} with a descriptive error
                   13187: message (may change into a @code{-22 throw} (Control structure mismatch)
                   13188: in the future). You may also get a memory access error. If you are
                   13189: unlucky, this ambiguous condition is not caught.
                   13190: 
1.29      crook    13191: @item @i{name} can't be found (@code{FORGET}):
                   13192: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    13193: Not implemented (yet).
                   13194: 
1.29      crook    13195: @item @i{name} not defined via @code{CREATE}:
                   13196: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    13197: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   13198: the execution semantics of the last defined word no matter how it was
                   13199: defined.
                   13200: 
                   13201: @item @code{POSTPONE} applied to @code{[IF]}:
                   13202: @cindex @code{POSTPONE} applied to @code{[IF]}
                   13203: @cindex @code{[IF]} and @code{POSTPONE}
                   13204: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   13205: equivalent to @code{[IF]}.
                   13206: 
                   13207: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   13208: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   13209: Continue in the same state of conditional compilation in the next outer
                   13210: input source. Currently there is no warning to the user about this.
                   13211: 
                   13212: @item removing a needed definition (@code{FORGET}):
                   13213: @cindex @code{FORGET}, removing a needed definition
                   13214: Not implemented (yet).
                   13215: 
                   13216: @end table
                   13217: 
                   13218: 
                   13219: @c =====================================================================
                   13220: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   13221: @section The optional Search-Order word set
                   13222: @c =====================================================================
                   13223: @cindex system documentation, search-order words
                   13224: @cindex search-order words, system documentation
                   13225: 
                   13226: @menu
                   13227: * search-idef::                 Implementation Defined Options                 
                   13228: * search-ambcond::              Ambiguous Conditions              
                   13229: @end menu
                   13230: 
                   13231: 
                   13232: @c ---------------------------------------------------------------------
                   13233: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   13234: @subsection Implementation Defined Options
                   13235: @c ---------------------------------------------------------------------
                   13236: @cindex implementation-defined options, search-order words
                   13237: @cindex search-order words, implementation-defined options
                   13238: 
                   13239: @table @i
                   13240: @item maximum number of word lists in search order:
                   13241: @cindex maximum number of word lists in search order
                   13242: @cindex search order, maximum depth
                   13243: @code{s" wordlists" environment? drop .}. Currently 16.
                   13244: 
                   13245: @item minimum search order:
                   13246: @cindex minimum search order
                   13247: @cindex search order, minimum
                   13248: @code{root root}.
                   13249: 
                   13250: @end table
                   13251: 
                   13252: @c ---------------------------------------------------------------------
                   13253: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   13254: @subsection Ambiguous conditions
                   13255: @c ---------------------------------------------------------------------
                   13256: @cindex search-order words, ambiguous conditions
                   13257: @cindex ambiguous conditions, search-order words
                   13258: 
                   13259: @table @i
1.21      crook    13260: @item changing the compilation word list (during compilation):
                   13261: @cindex changing the compilation word list (during compilation)
                   13262: @cindex compilation word list, change before definition ends
                   13263: The word is entered into the word list that was the compilation word list
1.1       anton    13264: at the start of the definition. Any changes to the name field (e.g.,
                   13265: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
                   13266: are applied to the latest defined word (as reported by @code{last} or
1.21      crook    13267: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1       anton    13268: 
                   13269: @item search order empty (@code{previous}):
                   13270: @cindex @code{previous}, search order empty
1.26      crook    13271: @cindex vocstack empty, @code{previous}
1.1       anton    13272: @code{abort" Vocstack empty"}.
                   13273: 
                   13274: @item too many word lists in search order (@code{also}):
                   13275: @cindex @code{also}, too many word lists in search order
1.26      crook    13276: @cindex vocstack full, @code{also}
1.1       anton    13277: @code{abort" Vocstack full"}.
                   13278: 
                   13279: @end table
                   13280: 
                   13281: @c ***************************************************************
1.65      anton    13282: @node Standard vs Extensions, Model, ANS conformance, Top
                   13283: @chapter Should I use Gforth extensions?
                   13284: @cindex Gforth extensions
                   13285: 
                   13286: As you read through the rest of this manual, you will see documentation
                   13287: for @i{Standard} words, and documentation for some appealing Gforth
                   13288: @i{extensions}. You might ask yourself the question: @i{``Should I
                   13289: restrict myself to the standard, or should I use the extensions?''}
                   13290: 
                   13291: The answer depends on the goals you have for the program you are working
                   13292: on:
                   13293: 
                   13294: @itemize @bullet
                   13295: 
                   13296: @item Is it just for yourself or do you want to share it with others?
                   13297: 
                   13298: @item
                   13299: If you want to share it, do the others all use Gforth?
                   13300: 
                   13301: @item
                   13302: If it is just for yourself, do you want to restrict yourself to Gforth?
                   13303: 
                   13304: @end itemize
                   13305: 
                   13306: If restricting the program to Gforth is ok, then there is no reason not
                   13307: to use extensions.  It is still a good idea to keep to the standard
                   13308: where it is easy, in case you want to reuse these parts in another
                   13309: program that you want to be portable.
                   13310: 
                   13311: If you want to be able to port the program to other Forth systems, there
                   13312: are the following points to consider:
                   13313: 
                   13314: @itemize @bullet
                   13315: 
                   13316: @item
                   13317: Most Forth systems that are being maintained support the ANS Forth
                   13318: standard.  So if your program complies with the standard, it will be
                   13319: portable among many systems.
                   13320: 
                   13321: @item
                   13322: A number of the Gforth extensions can be implemented in ANS Forth using
                   13323: public-domain files provided in the @file{compat/} directory. These are
                   13324: mentioned in the text in passing.  There is no reason not to use these
                   13325: extensions, your program will still be ANS Forth compliant; just include
                   13326: the appropriate compat files with your program.
                   13327: 
                   13328: @item
                   13329: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                   13330: analyse your program and determine what non-Standard words it relies
                   13331: upon.  However, it does not check whether you use standard words in a
                   13332: non-standard way.
                   13333: 
                   13334: @item
                   13335: Some techniques are not standardized by ANS Forth, and are hard or
                   13336: impossible to implement in a standard way, but can be implemented in
                   13337: most Forth systems easily, and usually in similar ways (e.g., accessing
                   13338: word headers).  Forth has a rich historical precedent for programmers
                   13339: taking advantage of implementation-dependent features of their tools
                   13340: (for example, relying on a knowledge of the dictionary
                   13341: structure). Sometimes these techniques are necessary to extract every
                   13342: last bit of performance from the hardware, sometimes they are just a
                   13343: programming shorthand.
                   13344: 
                   13345: @item
                   13346: Does using a Gforth extension save more work than the porting this part
                   13347: to other Forth systems (if any) will cost?
                   13348: 
                   13349: @item
                   13350: Is the additional functionality worth the reduction in portability and
                   13351: the additional porting problems?
                   13352: 
                   13353: @end itemize
                   13354: 
                   13355: In order to perform these consideratios, you need to know what's
                   13356: standard and what's not.  This manual generally states if something is
1.81    ! anton    13357: non-standard, but the authoritative source is the
        !          13358: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65      anton    13359: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
                   13360: into the thought processes of the technical committee.
                   13361: 
                   13362: Note also that portability between Forth systems is not the only
                   13363: portability issue; there is also the issue of portability between
                   13364: different platforms (processor/OS combinations).
                   13365: 
                   13366: @c ***************************************************************
                   13367: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1       anton    13368: @chapter Model
                   13369: 
                   13370: This chapter has yet to be written. It will contain information, on
                   13371: which internal structures you can rely.
                   13372: 
                   13373: @c ***************************************************************
                   13374: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   13375: @chapter Integrating Gforth into C programs
                   13376: 
                   13377: This is not yet implemented.
                   13378: 
                   13379: Several people like to use Forth as scripting language for applications
                   13380: that are otherwise written in C, C++, or some other language.
                   13381: 
                   13382: The Forth system ATLAST provides facilities for embedding it into
                   13383: applications; unfortunately it has several disadvantages: most
                   13384: importantly, it is not based on ANS Forth, and it is apparently dead
                   13385: (i.e., not developed further and not supported). The facilities
1.21      crook    13386: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    13387: making the switch should not be hard.
                   13388: 
                   13389: We also tried to design the interface such that it can easily be
                   13390: implemented by other Forth systems, so that we may one day arrive at a
                   13391: standardized interface. Such a standard interface would allow you to
                   13392: replace the Forth system without having to rewrite C code.
                   13393: 
                   13394: You embed the Gforth interpreter by linking with the library
                   13395: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   13396: global symbols in this library that belong to the interface, have the
                   13397: prefix @code{forth_}. (Global symbols that are used internally have the
                   13398: prefix @code{gforth_}).
                   13399: 
                   13400: You can include the declarations of Forth types and the functions and
                   13401: variables of the interface with @code{#include <forth.h>}.
                   13402: 
                   13403: Types.
                   13404: 
                   13405: Variables.
                   13406: 
                   13407: Data and FP Stack pointer. Area sizes.
                   13408: 
                   13409: functions.
                   13410: 
                   13411: forth_init(imagefile)
                   13412: forth_evaluate(string) exceptions?
                   13413: forth_goto(address) (or forth_execute(xt)?)
                   13414: forth_continue() (a corountining mechanism)
                   13415: 
                   13416: Adding primitives.
                   13417: 
                   13418: No checking.
                   13419: 
                   13420: Signals?
                   13421: 
                   13422: Accessing the Stacks
                   13423: 
1.26      crook    13424: @c ******************************************************************
1.1       anton    13425: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   13426: @chapter Emacs and Gforth
                   13427: @cindex Emacs and Gforth
                   13428: 
                   13429: @cindex @file{gforth.el}
                   13430: @cindex @file{forth.el}
                   13431: @cindex Rydqvist, Goran
                   13432: @cindex comment editing commands
                   13433: @cindex @code{\}, editing with Emacs
                   13434: @cindex debug tracer editing commands
                   13435: @cindex @code{~~}, removal with Emacs
                   13436: @cindex Forth mode in Emacs
                   13437: Gforth comes with @file{gforth.el}, an improved version of
                   13438: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    13439: improvements are:
                   13440: 
                   13441: @itemize @bullet
                   13442: @item
                   13443: A better (but still not perfect) handling of indentation.
                   13444: @item
                   13445: Comment paragraph filling (@kbd{M-q})
                   13446: @item
                   13447: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   13448: @item
                   13449: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41      anton    13450: @item
                   13451: Support of the @code{info-lookup} feature for looking up the
                   13452: documentation of a word.
1.26      crook    13453: @end itemize
                   13454: 
                   13455: I left the stuff I do not use alone, even though some of it only makes
                   13456: sense for TILE. To get a description of these features, enter Forth mode
                   13457: and type @kbd{C-h m}.
1.1       anton    13458: 
                   13459: @cindex source location of error or debugging output in Emacs
                   13460: @cindex error output, finding the source location in Emacs
                   13461: @cindex debugging output, finding the source location in Emacs
                   13462: In addition, Gforth supports Emacs quite well: The source code locations
                   13463: given in error messages, debugging output (from @code{~~}) and failed
                   13464: assertion messages are in the right format for Emacs' compilation mode
                   13465: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   13466: Manual}) so the source location corresponding to an error or other
                   13467: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   13468: @kbd{C-c C-c} for the error under the cursor).
                   13469: 
                   13470: @cindex @file{TAGS} file
                   13471: @cindex @file{etags.fs}
                   13472: @cindex viewing the source of a word in Emacs
1.43      anton    13473: @cindex @code{require}, placement in files
                   13474: @cindex @code{include}, placement in files
                   13475: Also, if you @code{require} @file{etags.fs}, a new @file{TAGS} file will
1.26      crook    13476: be produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    13477: contains the definitions of all words defined afterwards. You can then
                   13478: find the source for a word using @kbd{M-.}. Note that emacs can use
                   13479: several tags files at the same time (e.g., one for the Gforth sources
                   13480: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   13481: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   13482: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43      anton    13483: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
                   13484: with @file{etags.fs}, you should avoid putting definitions both before
                   13485: and after @code{require} etc., otherwise you will see the same file
                   13486: visited several times by commands like @code{tags-search}.
1.1       anton    13487: 
1.41      anton    13488: @cindex viewing the documentation of a word in Emacs
                   13489: @cindex context-sensitive help
                   13490: Moreover, for words documented in this manual, you can look up the
                   13491: glossary entry quickly by using @kbd{C-h TAB}
1.80      anton    13492: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
1.41      anton    13493: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
1.42      anton    13494: later and does not work for words containing @code{:}.
1.41      anton    13495: 
                   13496: 
1.1       anton    13497: @cindex @file{.emacs}
                   13498: To get all these benefits, add the following lines to your @file{.emacs}
                   13499: file:
                   13500: 
                   13501: @example
                   13502: (autoload 'forth-mode "gforth.el")
                   13503: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) auto-mode-alist))
                   13504: @end example
                   13505: 
1.26      crook    13506: @c ******************************************************************
1.1       anton    13507: @node Image Files, Engine, Emacs and Gforth, Top
                   13508: @chapter Image Files
1.26      crook    13509: @cindex image file
                   13510: @cindex @file{.fi} files
1.1       anton    13511: @cindex precompiled Forth code
                   13512: @cindex dictionary in persistent form
                   13513: @cindex persistent form of dictionary
                   13514: 
                   13515: An image file is a file containing an image of the Forth dictionary,
                   13516: i.e., compiled Forth code and data residing in the dictionary.  By
                   13517: convention, we use the extension @code{.fi} for image files.
                   13518: 
                   13519: @menu
1.18      anton    13520: * Image Licensing Issues::      Distribution terms for images.
                   13521: * Image File Background::       Why have image files?
1.67      anton    13522: * Non-Relocatable Image Files::  don't always work.
1.18      anton    13523: * Data-Relocatable Image Files::  are better.
1.67      anton    13524: * Fully Relocatable Image Files::  better yet.
1.18      anton    13525: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    13526: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    13527: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    13528: @end menu
                   13529: 
1.18      anton    13530: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   13531: @section Image Licensing Issues
                   13532: @cindex license for images
                   13533: @cindex image license
                   13534: 
                   13535: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   13536: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   13537: original image; i.e., according to copyright law it is a derived work of
                   13538: the original image.
                   13539: 
                   13540: Since Gforth is distributed under the GNU GPL, the newly created image
                   13541: falls under the GNU GPL, too. In particular, this means that if you
                   13542: distribute the image, you have to make all of the sources for the image
                   13543: available, including those you wrote.  For details see @ref{License, ,
                   13544: GNU General Public License (Section 3)}.
                   13545: 
                   13546: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   13547: contains only code compiled from the sources you gave it; if none of
                   13548: these sources is under the GPL, the terms discussed above do not apply
                   13549: to the image. However, if your image needs an engine (a gforth binary)
                   13550: that is under the GPL, you should make sure that you distribute both in
                   13551: a way that is at most a @emph{mere aggregation}, if you don't want the
                   13552: terms of the GPL to apply to the image.
                   13553: 
                   13554: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    13555: @section Image File Background
                   13556: @cindex image file background
                   13557: 
1.80      anton    13558: Gforth consists not only of primitives (in the engine), but also of
1.1       anton    13559: definitions written in Forth. Since the Forth compiler itself belongs to
                   13560: those definitions, it is not possible to start the system with the
1.80      anton    13561: engine and the Forth source alone. Therefore we provide the Forth
1.26      crook    13562: code as an image file in nearly executable form. When Gforth starts up,
                   13563: a C routine loads the image file into memory, optionally relocates the
                   13564: addresses, then sets up the memory (stacks etc.) according to
                   13565: information in the image file, and (finally) starts executing Forth
                   13566: code.
1.1       anton    13567: 
                   13568: The image file variants represent different compromises between the
                   13569: goals of making it easy to generate image files and making them
                   13570: portable.
                   13571: 
                   13572: @cindex relocation at run-time
1.26      crook    13573: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    13574: run-time. This avoids many of the complications discussed below (image
                   13575: files are data relocatable without further ado), but costs performance
                   13576: (one addition per memory access).
                   13577: 
                   13578: @cindex relocation at load-time
1.26      crook    13579: By contrast, the Gforth loader performs relocation at image load time. The
                   13580: loader also has to replace tokens that represent primitive calls with the
1.1       anton    13581: appropriate code-field addresses (or code addresses in the case of
                   13582: direct threading).
                   13583: 
                   13584: There are three kinds of image files, with different degrees of
                   13585: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   13586: image files.
                   13587: 
                   13588: @cindex image file loader
                   13589: @cindex relocating loader
                   13590: @cindex loader for image files
                   13591: These image file variants have several restrictions in common; they are
                   13592: caused by the design of the image file loader:
                   13593: 
                   13594: @itemize @bullet
                   13595: @item
                   13596: There is only one segment; in particular, this means, that an image file
                   13597: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    13598: them). The contents of the stacks are not represented, either.
1.1       anton    13599: 
                   13600: @item
                   13601: The only kinds of relocation supported are: adding the same offset to
                   13602: all cells that represent data addresses; and replacing special tokens
                   13603: with code addresses or with pieces of machine code.
                   13604: 
                   13605: If any complex computations involving addresses are performed, the
                   13606: results cannot be represented in the image file. Several applications that
                   13607: use such computations come to mind:
                   13608: @itemize @minus
                   13609: @item
                   13610: Hashing addresses (or data structures which contain addresses) for table
                   13611: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   13612: purpose, you will have no problem, because the hash tables are
                   13613: recomputed automatically when the system is started. If you use your own
                   13614: hash tables, you will have to do something similar.
                   13615: 
                   13616: @item
                   13617: There's a cute implementation of doubly-linked lists that uses
                   13618: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   13619: in the image file, and restore the doubly-linked representation on
                   13620: startup.@footnote{In my opinion, though, you should think thrice before
                   13621: using a doubly-linked list (whatever implementation).}
                   13622: 
                   13623: @item
                   13624: The code addresses of run-time routines like @code{docol:} cannot be
                   13625: represented in the image file (because their tokens would be replaced by
                   13626: machine code in direct threaded implementations). As a workaround,
                   13627: compute these addresses at run-time with @code{>code-address} from the
                   13628: executions tokens of appropriate words (see the definitions of
1.80      anton    13629: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1       anton    13630: 
                   13631: @item
                   13632: On many architectures addresses are represented in machine code in some
                   13633: shifted or mangled form. You cannot put @code{CODE} words that contain
                   13634: absolute addresses in this form in a relocatable image file. Workarounds
                   13635: are representing the address in some relative form (e.g., relative to
                   13636: the CFA, which is present in some register), or loading the address from
                   13637: a place where it is stored in a non-mangled form.
                   13638: @end itemize
                   13639: @end itemize
                   13640: 
                   13641: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   13642: @section Non-Relocatable Image Files
                   13643: @cindex non-relocatable image files
1.26      crook    13644: @cindex image file, non-relocatable
1.1       anton    13645: 
                   13646: These files are simple memory dumps of the dictionary. They are specific
                   13647: to the executable (i.e., @file{gforth} file) they were created
                   13648: with. What's worse, they are specific to the place on which the
                   13649: dictionary resided when the image was created. Now, there is no
                   13650: guarantee that the dictionary will reside at the same place the next
                   13651: time you start Gforth, so there's no guarantee that a non-relocatable
                   13652: image will work the next time (Gforth will complain instead of crashing,
                   13653: though).
                   13654: 
                   13655: You can create a non-relocatable image file with
                   13656: 
1.44      crook    13657: 
1.1       anton    13658: doc-savesystem
                   13659: 
1.44      crook    13660: 
1.1       anton    13661: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   13662: @section Data-Relocatable Image Files
                   13663: @cindex data-relocatable image files
1.26      crook    13664: @cindex image file, data-relocatable
1.1       anton    13665: 
                   13666: These files contain relocatable data addresses, but fixed code addresses
                   13667: (instead of tokens). They are specific to the executable (i.e.,
                   13668: @file{gforth} file) they were created with. For direct threading on some
                   13669: architectures (e.g., the i386), data-relocatable images do not work. You
                   13670: get a data-relocatable image, if you use @file{gforthmi} with a
                   13671: Gforth binary that is not doubly indirect threaded (@pxref{Fully
                   13672: Relocatable Image Files}).
                   13673: 
                   13674: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   13675: @section Fully Relocatable Image Files
                   13676: @cindex fully relocatable image files
1.26      crook    13677: @cindex image file, fully relocatable
1.1       anton    13678: 
                   13679: @cindex @file{kern*.fi}, relocatability
                   13680: @cindex @file{gforth.fi}, relocatability
                   13681: These image files have relocatable data addresses, and tokens for code
                   13682: addresses. They can be used with different binaries (e.g., with and
                   13683: without debugging) on the same machine, and even across machines with
                   13684: the same data formats (byte order, cell size, floating point
                   13685: format). However, they are usually specific to the version of Gforth
                   13686: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
                   13687: are fully relocatable.
                   13688: 
                   13689: There are two ways to create a fully relocatable image file:
                   13690: 
                   13691: @menu
1.29      crook    13692: * gforthmi::                    The normal way
1.1       anton    13693: * cross.fs::                    The hard way
                   13694: @end menu
                   13695: 
                   13696: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   13697: @subsection @file{gforthmi}
                   13698: @cindex @file{comp-i.fs}
                   13699: @cindex @file{gforthmi}
                   13700: 
                   13701: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    13702: image @i{file} that contains everything you would load by invoking
                   13703: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    13704: @example
1.29      crook    13705: gforthmi @i{file} @i{options}
1.1       anton    13706: @end example
                   13707: 
                   13708: E.g., if you want to create an image @file{asm.fi} that has the file
                   13709: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   13710: like this:
                   13711: 
                   13712: @example
                   13713: gforthmi asm.fi asm.fs
                   13714: @end example
                   13715: 
1.27      crook    13716: @file{gforthmi} is implemented as a sh script and works like this: It
                   13717: produces two non-relocatable images for different addresses and then
                   13718: compares them. Its output reflects this: first you see the output (if
1.62      crook    13719: any) of the two Gforth invocations that produce the non-relocatable image
1.27      crook    13720: files, then you see the output of the comparing program: It displays the
                   13721: offset used for data addresses and the offset used for code addresses;
1.1       anton    13722: moreover, for each cell that cannot be represented correctly in the
1.44      crook    13723: image files, it displays a line like this:
1.1       anton    13724: 
                   13725: @example
                   13726:      78DC         BFFFFA50         BFFFFA40
                   13727: @end example
                   13728: 
                   13729: This means that at offset $78dc from @code{forthstart}, one input image
                   13730: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   13731: cannot be represented correctly in the output image, you should examine
                   13732: these places in the dictionary and verify that these cells are dead
                   13733: (i.e., not read before they are written).
1.39      anton    13734: 
                   13735: @cindex --application, @code{gforthmi} option
                   13736: If you insert the option @code{--application} in front of the image file
                   13737: name, you will get an image that uses the @code{--appl-image} option
                   13738: instead of the @code{--image-file} option (@pxref{Invoking
                   13739: Gforth}). When you execute such an image on Unix (by typing the image
                   13740: name as command), the Gforth engine will pass all options to the image
                   13741: instead of trying to interpret them as engine options.
1.1       anton    13742: 
1.27      crook    13743: If you type @file{gforthmi} with no arguments, it prints some usage
                   13744: instructions.
                   13745: 
1.1       anton    13746: @cindex @code{savesystem} during @file{gforthmi}
                   13747: @cindex @code{bye} during @file{gforthmi}
                   13748: @cindex doubly indirect threaded code
1.44      crook    13749: @cindex environment variables
                   13750: @cindex @code{GFORTHD} -- environment variable
                   13751: @cindex @code{GFORTH} -- environment variable
1.1       anton    13752: @cindex @code{gforth-ditc}
1.29      crook    13753: There are a few wrinkles: After processing the passed @i{options}, the
1.1       anton    13754: words @code{savesystem} and @code{bye} must be visible. A special doubly
                   13755: indirect threaded version of the @file{gforth} executable is used for
1.62      crook    13756: creating the non-relocatable images; you can pass the exact filename of
1.1       anton    13757: this executable through the environment variable @code{GFORTHD}
                   13758: (default: @file{gforth-ditc}); if you pass a version that is not doubly
                   13759: indirect threaded, you will not get a fully relocatable image, but a
1.27      crook    13760: data-relocatable image (because there is no code address offset). The
                   13761: normal @file{gforth} executable is used for creating the relocatable
                   13762: image; you can pass the exact filename of this executable through the
                   13763: environment variable @code{GFORTH}.
1.1       anton    13764: 
                   13765: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   13766: @subsection @file{cross.fs}
                   13767: @cindex @file{cross.fs}
                   13768: @cindex cross-compiler
                   13769: @cindex metacompiler
1.47      crook    13770: @cindex target compiler
1.1       anton    13771: 
                   13772: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47      crook    13773: programming language (@pxref{Cross Compiler}).
1.1       anton    13774: 
1.47      crook    13775: @code{cross} allows you to create image files for machines with
1.1       anton    13776: different data sizes and data formats than the one used for generating
                   13777: the image file. You can also use it to create an application image that
                   13778: does not contain a Forth compiler. These features are bought with
                   13779: restrictions and inconveniences in programming. E.g., addresses have to
                   13780: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   13781: order to make the code relocatable.
                   13782: 
                   13783: 
                   13784: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   13785: @section Stack and Dictionary Sizes
                   13786: @cindex image file, stack and dictionary sizes
                   13787: @cindex dictionary size default
                   13788: @cindex stack size default
                   13789: 
                   13790: If you invoke Gforth with a command line flag for the size
                   13791: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   13792: dictionary. If you save the dictionary with @code{savesystem} or create
                   13793: an image with @file{gforthmi}, this size will become the default
                   13794: for the resulting image file. E.g., the following will create a
1.21      crook    13795: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    13796: 
                   13797: @example
                   13798: gforthmi gforth.fi -m 1M
                   13799: @end example
                   13800: 
                   13801: In other words, if you want to set the default size for the dictionary
                   13802: and the stacks of an image, just invoke @file{gforthmi} with the
                   13803: appropriate options when creating the image.
                   13804: 
                   13805: @cindex stack size, cache-friendly
                   13806: Note: For cache-friendly behaviour (i.e., good performance), you should
                   13807: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   13808: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   13809: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   13810: 
                   13811: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   13812: @section Running Image Files
                   13813: @cindex running image files
                   13814: @cindex invoking image files
                   13815: @cindex image file invocation
                   13816: 
                   13817: @cindex -i, invoke image file
                   13818: @cindex --image file, invoke image file
1.29      crook    13819: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    13820: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   13821: @example
1.29      crook    13822: gforth -i @i{image}
1.1       anton    13823: @end example
                   13824: 
                   13825: @cindex executable image file
1.26      crook    13826: @cindex image file, executable
1.1       anton    13827: If your operating system supports starting scripts with a line of the
                   13828: form @code{#! ...}, you just have to type the image file name to start
                   13829: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    13830: just a convention). I.e., to run Gforth with the image file @i{image},
                   13831: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    13832: This works because every @code{.fi} file starts with a line of this
                   13833: format:
                   13834: 
                   13835: @example
                   13836: #! /usr/local/bin/gforth-0.4.0 -i
                   13837: @end example
                   13838: 
                   13839: The file and pathname for the Gforth engine specified on this line is
                   13840: the specific Gforth executable that it was built against; i.e. the value
                   13841: of the environment variable @code{GFORTH} at the time that
                   13842: @file{gforthmi} was executed.
1.1       anton    13843: 
1.27      crook    13844: You can make use of the same shell capability to make a Forth source
                   13845: file into an executable. For example, if you place this text in a file:
1.26      crook    13846: 
                   13847: @example
                   13848: #! /usr/local/bin/gforth
                   13849: 
                   13850: ." Hello, world" CR
                   13851: bye
                   13852: @end example
                   13853: 
                   13854: @noindent
1.27      crook    13855: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    13856: directly from the command line. The sequence @code{#!} is used in two
                   13857: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    13858: system@footnote{The Unix kernel actually recognises two types of files:
                   13859: executable files and files of data, where the data is processed by an
                   13860: interpreter that is specified on the ``interpreter line'' -- the first
                   13861: line of the file, starting with the sequence #!. There may be a small
                   13862: limit (e.g., 32) on the number of characters that may be specified on
                   13863: the interpreter line.} secondly it is treated as a comment character by
                   13864: Gforth. Because of the second usage, a space is required between
1.80      anton    13865: @code{#!} and the path to the executable (moreover, some Unixes
                   13866: require the sequence @code{#! /}).
1.27      crook    13867: 
                   13868: The disadvantage of this latter technique, compared with using
1.80      anton    13869: @file{gforthmi}, is that it is slightly slower; the Forth source code is
                   13870: compiled on-the-fly, each time the program is invoked.
1.26      crook    13871: 
1.1       anton    13872: doc-#!
                   13873: 
1.44      crook    13874: 
1.1       anton    13875: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   13876: @section Modifying the Startup Sequence
                   13877: @cindex startup sequence for image file
                   13878: @cindex image file initialization sequence
                   13879: @cindex initialization sequence of image file
                   13880: 
                   13881: You can add your own initialization to the startup sequence through the
1.26      crook    13882: deferred word @code{'cold}. @code{'cold} is invoked just before the
1.80      anton    13883: image-specific command line processing (i.e., loading files and
1.26      crook    13884: evaluating (@code{-e}) strings) starts.
1.1       anton    13885: 
                   13886: A sequence for adding your initialization usually looks like this:
                   13887: 
                   13888: @example
                   13889: :noname
                   13890:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   13891:     ... \ your stuff
                   13892: ; IS 'cold
                   13893: @end example
                   13894: 
                   13895: @cindex turnkey image files
1.26      crook    13896: @cindex image file, turnkey applications
1.1       anton    13897: You can make a turnkey image by letting @code{'cold} execute a word
                   13898: (your turnkey application) that never returns; instead, it exits Gforth
                   13899: via @code{bye} or @code{throw}.
                   13900: 
                   13901: @cindex command-line arguments, access
                   13902: @cindex arguments on the command line, access
                   13903: You can access the (image-specific) command-line arguments through the
1.26      crook    13904: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1       anton    13905: access to @code{argv}.
                   13906: 
1.26      crook    13907: If @code{'cold} exits normally, Gforth processes the command-line
                   13908: arguments as files to be loaded and strings to be evaluated.  Therefore,
                   13909: @code{'cold} should remove the arguments it has used in this case.
                   13910: 
1.44      crook    13911: 
                   13912: 
1.26      crook    13913: doc-'cold
1.1       anton    13914: doc-argc
                   13915: doc-argv
                   13916: doc-arg
                   13917: 
                   13918: 
1.44      crook    13919: 
1.1       anton    13920: @c ******************************************************************
1.13      pazsan   13921: @node Engine, Binding to System Library, Image Files, Top
1.1       anton    13922: @chapter Engine
                   13923: @cindex engine
                   13924: @cindex virtual machine
                   13925: 
1.26      crook    13926: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    13927: may be helpful for finding your way in the Gforth sources.
                   13928: 
1.66      anton    13929: The ideas in this section have also been published in Bernd Paysan,
                   13930: @cite{ANS fig/GNU/??? Forth} (in German), Forth-Tagung '93 and M. Anton
                   13931: Ertl, @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
                   13932: Portable Forth Engine}}, EuroForth '93.
1.1       anton    13933: 
                   13934: @menu
                   13935: * Portability::                 
                   13936: * Threading::                   
                   13937: * Primitives::                  
                   13938: * Performance::                 
                   13939: @end menu
                   13940: 
                   13941: @node Portability, Threading, Engine, Engine
                   13942: @section Portability
                   13943: @cindex engine portability
                   13944: 
1.26      crook    13945: An important goal of the Gforth Project is availability across a wide
                   13946: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   13947: achieved this goal by manually coding the engine in assembly language
                   13948: for several then-popular processors. This approach is very
                   13949: labor-intensive and the results are short-lived due to progress in
                   13950: computer architecture.
1.1       anton    13951: 
                   13952: @cindex C, using C for the engine
                   13953: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   13954: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   13955: particularly popular for UNIX-based Forths due to the large variety of
                   13956: architectures of UNIX machines. Unfortunately an implementation in C
                   13957: does not mix well with the goals of efficiency and with using
                   13958: traditional techniques: Indirect or direct threading cannot be expressed
                   13959: in C, and switch threading, the fastest technique available in C, is
                   13960: significantly slower. Another problem with C is that it is very
                   13961: cumbersome to express double integer arithmetic.
                   13962: 
                   13963: @cindex GNU C for the engine
                   13964: @cindex long long
                   13965: Fortunately, there is a portable language that does not have these
                   13966: limitations: GNU C, the version of C processed by the GNU C compiler
                   13967: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   13968: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   13969: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   13970: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   13971: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
                   13972: double numbers@footnote{Unfortunately, long longs are not implemented
                   13973: properly on all machines (e.g., on alpha-osf1, long longs are only 64
                   13974: bits, the same size as longs (and pointers), but they should be twice as
1.4       anton    13975: long according to @pxref{Long Long, , Double-Word Integers, gcc.info, GNU
1.1       anton    13976: C Manual}). So, we had to implement doubles in C after all. Still, on
                   13977: most machines we can use long longs and achieve better performance than
                   13978: with the emulation package.}. GNU C is available for free on all
                   13979: important (and many unimportant) UNIX machines, VMS, 80386s running
                   13980: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   13981: on all these machines.
                   13982: 
                   13983: Writing in a portable language has the reputation of producing code that
                   13984: is slower than assembly. For our Forth engine we repeatedly looked at
                   13985: the code produced by the compiler and eliminated most compiler-induced
                   13986: inefficiencies by appropriate changes in the source code.
                   13987: 
                   13988: @cindex explicit register declarations
                   13989: @cindex --enable-force-reg, configuration flag
                   13990: @cindex -DFORCE_REG
                   13991: However, register allocation cannot be portably influenced by the
                   13992: programmer, leading to some inefficiencies on register-starved
                   13993: machines. We use explicit register declarations (@pxref{Explicit Reg
                   13994: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   13995: improve the speed on some machines. They are turned on by using the
                   13996: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   13997: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   13998: machine, but also on the compiler version: On some machines some
                   13999: compiler versions produce incorrect code when certain explicit register
                   14000: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   14001: 
                   14002: @node Threading, Primitives, Portability, Engine
                   14003: @section Threading
                   14004: @cindex inner interpreter implementation
                   14005: @cindex threaded code implementation
                   14006: 
                   14007: @cindex labels as values
                   14008: GNU C's labels as values extension (available since @code{gcc-2.0},
                   14009: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    14010: makes it possible to take the address of @i{label} by writing
                   14011: @code{&&@i{label}}.  This address can then be used in a statement like
                   14012: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    14013: @code{goto x}.
                   14014: 
1.26      crook    14015: @cindex @code{NEXT}, indirect threaded
1.1       anton    14016: @cindex indirect threaded inner interpreter
                   14017: @cindex inner interpreter, indirect threaded
1.26      crook    14018: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    14019: @example
                   14020: cfa = *ip++;
                   14021: ca = *cfa;
                   14022: goto *ca;
                   14023: @end example
                   14024: @cindex instruction pointer
                   14025: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   14026: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   14027: execution token and points to the code field of the next word to be
                   14028: executed; The @code{ca} (code address) fetched from there points to some
                   14029: executable code, e.g., a primitive or the colon definition handler
                   14030: @code{docol}.
                   14031: 
1.26      crook    14032: @cindex @code{NEXT}, direct threaded
1.1       anton    14033: @cindex direct threaded inner interpreter
                   14034: @cindex inner interpreter, direct threaded
                   14035: Direct threading is even simpler:
                   14036: @example
                   14037: ca = *ip++;
                   14038: goto *ca;
                   14039: @end example
                   14040: 
                   14041: Of course we have packaged the whole thing neatly in macros called
1.26      crook    14042: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    14043: 
                   14044: @menu
                   14045: * Scheduling::                  
                   14046: * Direct or Indirect Threaded?::  
                   14047: * DOES>::                       
                   14048: @end menu
                   14049: 
                   14050: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   14051: @subsection Scheduling
                   14052: @cindex inner interpreter optimization
                   14053: 
                   14054: There is a little complication: Pipelined and superscalar processors,
                   14055: i.e., RISC and some modern CISC machines can process independent
                   14056: instructions while waiting for the results of an instruction. The
                   14057: compiler usually reorders (schedules) the instructions in a way that
                   14058: achieves good usage of these delay slots. However, on our first tries
                   14059: the compiler did not do well on scheduling primitives. E.g., for
                   14060: @code{+} implemented as
                   14061: @example
                   14062: n=sp[0]+sp[1];
                   14063: sp++;
                   14064: sp[0]=n;
                   14065: NEXT;
                   14066: @end example
1.81    ! anton    14067: the @code{NEXT} comes strictly after the other code, i.e., there is
        !          14068: nearly no scheduling. After a little thought the problem becomes clear:
        !          14069: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21      crook    14070: addresses (and the version of @code{gcc} we used would not know it even
                   14071: if it was possible), so it could not move the load of the cfa above the
                   14072: store to the TOS. Indeed the pointers could be the same, if code on or
                   14073: very near the top of stack were executed. In the interest of speed we
                   14074: chose to forbid this probably unused ``feature'' and helped the compiler
1.81    ! anton    14075: in scheduling: @code{NEXT} is divided into several parts:
        !          14076: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
        !          14077: like:
1.1       anton    14078: @example
1.81    ! anton    14079: NEXT_P0;
1.1       anton    14080: n=sp[0]+sp[1];
                   14081: sp++;
                   14082: NEXT_P1;
                   14083: sp[0]=n;
                   14084: NEXT_P2;
                   14085: @end example
                   14086: 
1.81    ! anton    14087: There are various schemes that distribute the different operations of
        !          14088: NEXT between these parts in several ways; in general, different schemes
        !          14089: perform best on different processors.  We use a scheme for most
        !          14090: architectures that performs well for most processors of this
        !          14091: architecture; in the furture we may switch to benchmarking and chosing
        !          14092: the scheme on installation time.
        !          14093: 
1.1       anton    14094: 
                   14095: @node Direct or Indirect Threaded?, DOES>, Scheduling, Threading
                   14096: @subsection Direct or Indirect Threaded?
                   14097: @cindex threading, direct or indirect?
                   14098: 
                   14099: @cindex -DDIRECT_THREADED
                   14100: Both! After packaging the nasty details in macro definitions we
                   14101: realized that we could switch between direct and indirect threading by
                   14102: simply setting a compilation flag (@code{-DDIRECT_THREADED}) and
                   14103: defining a few machine-specific macros for the direct-threading case.
                   14104: On the Forth level we also offer access words that hide the
                   14105: differences between the threading methods (@pxref{Threading Words}).
                   14106: 
                   14107: Indirect threading is implemented completely machine-independently.
                   14108: Direct threading needs routines for creating jumps to the executable
1.21      crook    14109: code (e.g. to @code{docol} or @code{dodoes}). These routines are inherently
                   14110: machine-dependent, but they do not amount to many source lines. Therefore,
                   14111: even porting direct threading to a new machine requires little effort.
1.1       anton    14112: 
                   14113: @cindex --enable-indirect-threaded, configuration flag
                   14114: @cindex --enable-direct-threaded, configuration flag
                   14115: The default threading method is machine-dependent. You can enforce a
                   14116: specific threading method when building Gforth with the configuration
                   14117: flag @code{--enable-direct-threaded} or
                   14118: @code{--enable-indirect-threaded}. Note that direct threading is not
                   14119: supported on all machines.
                   14120: 
                   14121: @node DOES>,  , Direct or Indirect Threaded?, Threading
                   14122: @subsection DOES>
                   14123: @cindex @code{DOES>} implementation
                   14124: 
1.26      crook    14125: @cindex @code{dodoes} routine
                   14126: @cindex @code{DOES>}-code
1.1       anton    14127: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   14128: the chunk of code executed by every word defined by a
                   14129: @code{CREATE}...@code{DOES>} pair. The main problem here is: How to find
                   14130: the Forth code to be executed, i.e. the code after the
1.26      crook    14131: @code{DOES>} (the @code{DOES>}-code)? There are two solutions:
1.1       anton    14132: 
1.21      crook    14133: In fig-Forth the code field points directly to the @code{dodoes} and the
1.45      crook    14134: @code{DOES>}-code address is stored in the cell after the code address (i.e. at
1.29      crook    14135: @code{@i{CFA} cell+}). It may seem that this solution is illegal in
1.1       anton    14136: the Forth-79 and all later standards, because in fig-Forth this address
                   14137: lies in the body (which is illegal in these standards). However, by
                   14138: making the code field larger for all words this solution becomes legal
                   14139: again. We use this approach for the indirect threaded version and for
                   14140: direct threading on some machines. Leaving a cell unused in most words
                   14141: is a bit wasteful, but on the machines we are targeting this is hardly a
                   14142: problem. The other reason for having a code field size of two cells is
                   14143: to avoid having different image files for direct and indirect threaded
                   14144: systems (direct threaded systems require two-cell code fields on many
                   14145: machines).
                   14146: 
1.26      crook    14147: @cindex @code{DOES>}-handler
1.1       anton    14148: The other approach is that the code field points or jumps to the cell
1.26      crook    14149: after @code{DOES>}. In this variant there is a jump to @code{dodoes} at
                   14150: this address (the @code{DOES>}-handler). @code{dodoes} can then get the
                   14151: @code{DOES>}-code address by computing the code address, i.e., the address of
1.45      crook    14152: the jump to @code{dodoes}, and add the length of that jump field. A variant of
1.1       anton    14153: this is to have a call to @code{dodoes} after the @code{DOES>}; then the
                   14154: return address (which can be found in the return register on RISCs) is
1.26      crook    14155: the @code{DOES>}-code address. Since the two cells available in the code field
1.1       anton    14156: are used up by the jump to the code address in direct threading on many
                   14157: architectures, we use this approach for direct threading on these
                   14158: architectures. We did not want to add another cell to the code field.
                   14159: 
                   14160: @node Primitives, Performance, Threading, Engine
                   14161: @section Primitives
                   14162: @cindex primitives, implementation
                   14163: @cindex virtual machine instructions, implementation
                   14164: 
                   14165: @menu
                   14166: * Automatic Generation::        
                   14167: * TOS Optimization::            
                   14168: * Produced code::               
                   14169: @end menu
                   14170: 
                   14171: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   14172: @subsection Automatic Generation
                   14173: @cindex primitives, automatic generation
                   14174: 
                   14175: @cindex @file{prims2x.fs}
                   14176: Since the primitives are implemented in a portable language, there is no
                   14177: longer any need to minimize the number of primitives. On the contrary,
                   14178: having many primitives has an advantage: speed. In order to reduce the
                   14179: number of errors in primitives and to make programming them easier, we
                   14180: provide a tool, the primitive generator (@file{prims2x.fs}), that
                   14181: automatically generates most (and sometimes all) of the C code for a
                   14182: primitive from the stack effect notation.  The source for a primitive
                   14183: has the following form:
                   14184: 
                   14185: @cindex primitive source format
                   14186: @format
1.58      anton    14187: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
1.29      crook    14188: [@code{""}@i{glossary entry}@code{""}]
                   14189: @i{C code}
1.1       anton    14190: [@code{:}
1.29      crook    14191: @i{Forth code}]
1.1       anton    14192: @end format
                   14193: 
                   14194: The items in brackets are optional. The category and glossary fields
                   14195: are there for generating the documentation, the Forth code is there
                   14196: for manual implementations on machines without GNU C. E.g., the source
                   14197: for the primitive @code{+} is:
                   14198: @example
1.58      anton    14199: +    ( n1 n2 -- n )   core    plus
1.1       anton    14200: n = n1+n2;
                   14201: @end example
                   14202: 
                   14203: This looks like a specification, but in fact @code{n = n1+n2} is C
                   14204: code. Our primitive generation tool extracts a lot of information from
                   14205: the stack effect notations@footnote{We use a one-stack notation, even
                   14206: though we have separate data and floating-point stacks; The separate
                   14207: notation can be generated easily from the unified notation.}: The number
                   14208: of items popped from and pushed on the stack, their type, and by what
                   14209: name they are referred to in the C code. It then generates a C code
                   14210: prelude and postlude for each primitive. The final C code for @code{+}
                   14211: looks like this:
                   14212: 
                   14213: @example
1.46      pazsan   14214: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
1.1       anton    14215: /*  */                          /* documentation */
1.81    ! anton    14216: NAME("+")                       /* debugging output (with -DDEBUG) */
1.1       anton    14217: @{
                   14218: DEF_CA                          /* definition of variable ca (indirect threading) */
                   14219: Cell n1;                        /* definitions of variables */
                   14220: Cell n2;
                   14221: Cell n;
1.81    ! anton    14222: NEXT_P0;                        /* NEXT part 0 */
1.1       anton    14223: n1 = (Cell) sp[1];              /* input */
                   14224: n2 = (Cell) TOS;
                   14225: sp += 1;                        /* stack adjustment */
                   14226: @{
                   14227: n = n1+n2;                      /* C code taken from the source */
                   14228: @}
                   14229: NEXT_P1;                        /* NEXT part 1 */
                   14230: TOS = (Cell)n;                  /* output */
                   14231: NEXT_P2;                        /* NEXT part 2 */
                   14232: @}
                   14233: @end example
                   14234: 
                   14235: This looks long and inefficient, but the GNU C compiler optimizes quite
                   14236: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   14237: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   14238: using them as intermediate storage also adds no cost.
                   14239: 
1.26      crook    14240: There are also other optimizations that are not illustrated by this
                   14241: example: assignments between simple variables are usually for free (copy
1.1       anton    14242: propagation). If one of the stack items is not used by the primitive
                   14243: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   14244: (dead code elimination). On the other hand, there are some things that
                   14245: the compiler does not do, therefore they are performed by
                   14246: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   14247: a stack item to the place where it just came from (e.g., @code{over}).
                   14248: 
                   14249: While programming a primitive is usually easy, there are a few cases
                   14250: where the programmer has to take the actions of the generator into
                   14251: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    14252: fall through to @code{NEXT}.
1.1       anton    14253: 
                   14254: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   14255: @subsection TOS Optimization
                   14256: @cindex TOS optimization for primitives
                   14257: @cindex primitives, keeping the TOS in a register
                   14258: 
                   14259: An important optimization for stack machine emulators, e.g., Forth
                   14260: engines, is keeping  one or more of the top stack items in
1.29      crook    14261: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   14262: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    14263: @itemize @bullet
                   14264: @item
1.29      crook    14265: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    14266: due to fewer loads from and stores to the stack.
1.29      crook    14267: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   14268: @i{y<n}, due to additional moves between registers.
1.1       anton    14269: @end itemize
                   14270: 
                   14271: @cindex -DUSE_TOS
                   14272: @cindex -DUSE_NO_TOS
                   14273: In particular, keeping one item in a register is never a disadvantage,
                   14274: if there are enough registers. Keeping two items in registers is a
                   14275: disadvantage for frequent words like @code{?branch}, constants,
                   14276: variables, literals and @code{i}. Therefore our generator only produces
                   14277: code that keeps zero or one items in registers. The generated C code
                   14278: covers both cases; the selection between these alternatives is made at
                   14279: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   14280: code for @code{+} is just a simple variable name in the one-item case,
                   14281: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   14282: GNU C compiler tries to keep simple variables like @code{TOS} in
                   14283: registers, and it usually succeeds, if there are enough registers.
                   14284: 
                   14285: @cindex -DUSE_FTOS
                   14286: @cindex -DUSE_NO_FTOS
                   14287: The primitive generator performs the TOS optimization for the
                   14288: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   14289: operations the benefit of this optimization is even larger:
                   14290: floating-point operations take quite long on most processors, but can be
                   14291: performed in parallel with other operations as long as their results are
                   14292: not used. If the FP-TOS is kept in a register, this works. If
                   14293: it is kept on the stack, i.e., in memory, the store into memory has to
                   14294: wait for the result of the floating-point operation, lengthening the
                   14295: execution time of the primitive considerably.
                   14296: 
                   14297: The TOS optimization makes the automatic generation of primitives a
                   14298: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   14299: @code{TOS} is not sufficient. There are some special cases to
                   14300: consider:
                   14301: @itemize @bullet
                   14302: @item In the case of @code{dup ( w -- w w )} the generator must not
                   14303: eliminate the store to the original location of the item on the stack,
                   14304: if the TOS optimization is turned on.
                   14305: @item Primitives with stack effects of the form @code{--}
1.29      crook    14306: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   14307: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    14308: must load the TOS from the stack at the end. But for the null stack
                   14309: effect @code{--} no stores or loads should be generated.
                   14310: @end itemize
                   14311: 
                   14312: @node Produced code,  , TOS Optimization, Primitives
                   14313: @subsection Produced code
                   14314: @cindex primitives, assembly code listing
                   14315: 
                   14316: @cindex @file{engine.s}
                   14317: To see what assembly code is produced for the primitives on your machine
                   14318: with your compiler and your flag settings, type @code{make engine.s} and
1.81    ! anton    14319: look at the resulting file @file{engine.s}.  Alternatively, you can also
        !          14320: disassemble the code of primitives with @code{see} on some architectures.
1.1       anton    14321: 
                   14322: @node  Performance,  , Primitives, Engine
                   14323: @section Performance
                   14324: @cindex performance of some Forth interpreters
                   14325: @cindex engine performance
                   14326: @cindex benchmarking Forth systems
                   14327: @cindex Gforth performance
                   14328: 
                   14329: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
                   14330: impossible to write a significantly faster engine.
                   14331: 
                   14332: On register-starved machines like the 386 architecture processors
                   14333: improvements are possible, because @code{gcc} does not utilize the
                   14334: registers as well as a human, even with explicit register declarations;
                   14335: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   14336: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   14337: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40      anton    14338: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
                   14339: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
                   14340: registers fit in real registers (and we can even afford to use the TOS
                   14341: optimization), resulting in a speedup of 1.14 on the sieve over the
                   14342: earlier results.
1.1       anton    14343: 
                   14344: @cindex Win32Forth performance
                   14345: @cindex NT Forth performance
                   14346: @cindex eforth performance
                   14347: @cindex ThisForth performance
                   14348: @cindex PFE performance
                   14349: @cindex TILE performance
1.81    ! anton    14350: The potential advantage of assembly language implementations is not
        !          14351: necessarily realized in complete Forth systems: We compared Gforth-0.4.9
        !          14352: (direct threaded, compiled with @code{gcc-2.95.1} and
        !          14353: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
        !          14354: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
        !          14355: (with and without peephole (aka pinhole) optimization of the threaded
        !          14356: code); all these systems were written in assembly language. We also
        !          14357: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
        !          14358: with @code{gcc-2.6.3} with the default configuration for Linux:
        !          14359: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
        !          14360: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
        !          14361: employs peephole optimization of the threaded code) and TILE (compiled
        !          14362: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
        !          14363: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
        !          14364: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
        !          14365: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
        !          14366: then extended it to run the benchmarks, added the peephole optimizer,
        !          14367: ran the benchmarks and reported the results.
1.40      anton    14368: 
1.1       anton    14369: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   14370: matrix multiplication come from the Stanford integer benchmarks and have
                   14371: been translated into Forth by Martin Fraeman; we used the versions
                   14372: included in the TILE Forth package, but with bigger data set sizes; and
                   14373: a recursive Fibonacci number computation for benchmarking calling
                   14374: performance. The following table shows the time taken for the benchmarks
                   14375: scaled by the time taken by Gforth (in other words, it shows the speedup
                   14376: factor that Gforth achieved over the other systems).
                   14377: 
                   14378: @example
1.40      anton    14379: relative      Win32-    NT       eforth       This-      
1.1       anton    14380:   time  Gforth Forth Forth eforth  +opt   PFE Forth  TILE
1.81    ! anton    14381: sieve     1.00  1.60  1.32   1.60  0.98  1.82  3.67  9.91
        !          14382: bubble    1.00  1.55  1.66   1.75  1.04  1.78        4.58
        !          14383: matmul    1.00  1.71  1.57   1.69  0.86  1.83        4.74
        !          14384: fib       1.00  1.76  1.54   1.41  1.00  2.01  3.45  4.96
1.1       anton    14385: @end example
                   14386: 
1.26      crook    14387: You may be quite surprised by the good performance of Gforth when
                   14388: compared with systems written in assembly language. One important reason
                   14389: for the disappointing performance of these other systems is probably
                   14390: that they are not written optimally for the 486 (e.g., they use the
                   14391: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   14392: but costly method for relocating the Forth image: like @code{cforth}, it
                   14393: computes the actual addresses at run time, resulting in two address
                   14394: computations per @code{NEXT} (@pxref{Image File Background}).
                   14395: 
1.40      anton    14396: Only Eforth with the peephole optimizer performs comparable to
                   14397: Gforth. The speedups achieved with peephole optimization of threaded
                   14398: code are quite remarkable. Adding a peephole optimizer to Gforth should
                   14399: cause similar speedups.
1.1       anton    14400: 
                   14401: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   14402: explained with the self-imposed restriction of the latter systems to
                   14403: standard C, which makes efficient threading impossible (however, the
1.4       anton    14404: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    14405: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   14406: Moreover, current C compilers have a hard time optimizing other aspects
                   14407: of the ThisForth and the TILE source.
                   14408: 
1.26      crook    14409: The performance of Gforth on 386 architecture processors varies widely
                   14410: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   14411: allocate any of the virtual machine registers into real machine
                   14412: registers by itself and would not work correctly with explicit register
1.40      anton    14413: declarations, giving a 1.5 times slower engine (on a 486DX2/66 running
1.26      crook    14414: the Sieve) than the one measured above.
1.1       anton    14415: 
1.26      crook    14416: Note that there have been several releases of Win32Forth since the
                   14417: release presented here, so the results presented above may have little
1.40      anton    14418: predictive value for the performance of Win32Forth today (results for
                   14419: the current release on an i486DX2/66 are welcome).
1.1       anton    14420: 
                   14421: @cindex @file{Benchres}
1.66      anton    14422: In
                   14423: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
                   14424: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1       anton    14425: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66      anton    14426: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
                   14427: several native code systems; that version of Gforth is slower on a 486
                   14428: than the direct threaded version used here. You can find a newer version
                   14429: of these measurements at
1.47      crook    14430: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1       anton    14431: find numbers for Gforth on various machines in @file{Benchres}.
                   14432: 
1.26      crook    14433: @c ******************************************************************
1.13      pazsan   14434: @node Binding to System Library, Cross Compiler, Engine, Top
1.14      pazsan   14435: @chapter Binding to System Library
1.13      pazsan   14436: 
                   14437: @node Cross Compiler, Bugs, Binding to System Library, Top
1.14      pazsan   14438: @chapter Cross Compiler
1.47      crook    14439: @cindex @file{cross.fs}
                   14440: @cindex cross-compiler
                   14441: @cindex metacompiler
                   14442: @cindex target compiler
1.13      pazsan   14443: 
1.46      pazsan   14444: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
                   14445: mostly written in Forth, including crucial parts like the outer
                   14446: interpreter and compiler, it needs compiled Forth code to get
                   14447: started. The cross compiler allows to create new images for other
                   14448: architectures, even running under another Forth system.
1.13      pazsan   14449: 
                   14450: @menu
1.67      anton    14451: * Using the Cross Compiler::    
                   14452: * How the Cross Compiler Works::  
1.13      pazsan   14453: @end menu
                   14454: 
1.21      crook    14455: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   14456: @section Using the Cross Compiler
1.46      pazsan   14457: 
                   14458: The cross compiler uses a language that resembles Forth, but isn't. The
                   14459: main difference is that you can execute Forth code after definition,
                   14460: while you usually can't execute the code compiled by cross, because the
                   14461: code you are compiling is typically for a different computer than the
                   14462: one you are compiling on.
                   14463: 
1.81    ! anton    14464: @c anton: This chapter is somewhat different from waht I would expect: I
        !          14465: @c would expect an explanation of the cross language and how to create an
        !          14466: @c application image with it.  The section explains some aspects of
        !          14467: @c creating a Gforth kernel.
        !          14468: 
1.46      pazsan   14469: The Makefile is already set up to allow you to create kernels for new
                   14470: architectures with a simple make command. The generic kernels using the
                   14471: GCC compiled virtual machine are created in the normal build process
                   14472: with @code{make}. To create a embedded Gforth executable for e.g. the
                   14473: 8086 processor (running on a DOS machine), type
                   14474: 
                   14475: @example
                   14476: make kernl-8086.fi
                   14477: @end example
                   14478: 
                   14479: This will use the machine description from the @file{arch/8086}
                   14480: directory to create a new kernel. A machine file may look like that:
                   14481: 
                   14482: @example
                   14483: \ Parameter for target systems                         06oct92py
                   14484: 
                   14485:     4 Constant cell             \ cell size in bytes
                   14486:     2 Constant cell<<           \ cell shift to bytes
                   14487:     5 Constant cell>bit         \ cell shift to bits
                   14488:     8 Constant bits/char        \ bits per character
                   14489:     8 Constant bits/byte        \ bits per byte [default: 8]
                   14490:     8 Constant float            \ bytes per float
                   14491:     8 Constant /maxalign        \ maximum alignment in bytes
                   14492: false Constant bigendian        \ byte order
                   14493: ( true=big, false=little )
                   14494: 
                   14495: include machpc.fs               \ feature list
                   14496: @end example
                   14497: 
                   14498: This part is obligatory for the cross compiler itself, the feature list
                   14499: is used by the kernel to conditionally compile some features in and out,
                   14500: depending on whether the target supports these features.
                   14501: 
                   14502: There are some optional features, if you define your own primitives,
                   14503: have an assembler, or need special, nonstandard preparation to make the
1.81    ! anton    14504: boot process work. @code{asm-include} includes an assembler,
1.46      pazsan   14505: @code{prims-include} includes primitives, and @code{>boot} prepares for
                   14506: booting.
                   14507: 
                   14508: @example
                   14509: : asm-include    ." Include assembler" cr
                   14510:   s" arch/8086/asm.fs" included ;
                   14511: 
                   14512: : prims-include  ." Include primitives" cr
                   14513:   s" arch/8086/prim.fs" included ;
                   14514: 
                   14515: : >boot          ." Prepare booting" cr
                   14516:   s" ' boot >body into-forth 1+ !" evaluate ;
                   14517: @end example
                   14518: 
                   14519: These words are used as sort of macro during the cross compilation in
1.81    ! anton    14520: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46      pazsan   14521: be possible --- but more complicated --- to write a new kernel project
                   14522: file, too.
                   14523: 
                   14524: @file{kernel/main.fs} expects the machine description file name on the
                   14525: stack; the cross compiler itself (@file{cross.fs}) assumes that either
                   14526: @code{mach-file} leaves a counted string on the stack, or
                   14527: @code{machine-file} leaves an address, count pair of the filename on the
                   14528: stack.
                   14529: 
                   14530: The feature list is typically controlled using @code{SetValue}, generic
                   14531: files that are used by several projects can use @code{DefaultValue}
                   14532: instead. Both functions work like @code{Value}, when the value isn't
                   14533: defined, but @code{SetValue} works like @code{to} if the value is
                   14534: defined, and @code{DefaultValue} doesn't set anything, if the value is
                   14535: defined.
                   14536: 
                   14537: @example
                   14538: \ generic mach file for pc gforth                       03sep97jaw
                   14539: 
                   14540: true DefaultValue NIL  \ relocating
                   14541: 
                   14542: >ENVIRON
                   14543: 
                   14544: true DefaultValue file          \ controls the presence of the
                   14545:                                 \ file access wordset
                   14546: true DefaultValue OS            \ flag to indicate a operating system
                   14547: 
                   14548: true DefaultValue prims         \ true: primitives are c-code
                   14549: 
                   14550: true DefaultValue floating      \ floating point wordset is present
                   14551: 
                   14552: true DefaultValue glocals       \ gforth locals are present
                   14553:                                 \ will be loaded
                   14554: true DefaultValue dcomps        \ double number comparisons
                   14555: 
                   14556: true DefaultValue hash          \ hashing primitives are loaded/present
                   14557: 
                   14558: true DefaultValue xconds        \ used together with glocals,
                   14559:                                 \ special conditionals supporting gforths'
                   14560:                                 \ local variables
                   14561: true DefaultValue header        \ save a header information
                   14562: 
                   14563: true DefaultValue backtrace     \ enables backtrace code
                   14564: 
                   14565: false DefaultValue ec
                   14566: false DefaultValue crlf
                   14567: 
                   14568: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
                   14569: 
                   14570: &16 KB          DefaultValue stack-size
                   14571: &15 KB &512 +   DefaultValue fstack-size
                   14572: &15 KB          DefaultValue rstack-size
                   14573: &14 KB &512 +   DefaultValue lstack-size
                   14574: @end example
1.13      pazsan   14575: 
1.48      anton    14576: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
1.14      pazsan   14577: @section How the Cross Compiler Works
1.13      pazsan   14578: 
                   14579: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    14580: @appendix Bugs
1.1       anton    14581: @cindex bug reporting
                   14582: 
1.21      crook    14583: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    14584: 
                   14585: If you find a bug, please send a bug report to
1.33      anton    14586: @email{bug-gforth@@gnu.org}. A bug report should include this
1.21      crook    14587: information:
                   14588: 
                   14589: @itemize @bullet
                   14590: @item
1.81    ! anton    14591: A program (or a sequence of keyboard commands) that reproduces the bug.
        !          14592: @item
        !          14593: A description of what you think constitutes the buggy behaviour.
        !          14594: @item
1.21      crook    14595: The Gforth version used (it is announced at the start of an
                   14596: interactive Gforth session).
                   14597: @item
                   14598: The machine and operating system (on Unix
                   14599: systems @code{uname -a} will report this information).
                   14600: @item
1.81    ! anton    14601: The installation options (you can find the configure options at the
        !          14602: start of @file{config.status}) and configuration (@code{configure}
        !          14603: output or @file{config.cache}).
1.21      crook    14604: @item
                   14605: A complete list of changes (if any) you (or your installer) have made to the
                   14606: Gforth sources.
                   14607: @end itemize
1.1       anton    14608: 
                   14609: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   14610: to Report Bugs, gcc.info, GNU C Manual}.
                   14611: 
                   14612: 
1.21      crook    14613: @node Origin, Forth-related information, Bugs, Top
                   14614: @appendix Authors and Ancestors of Gforth
1.1       anton    14615: 
                   14616: @section Authors and Contributors
                   14617: @cindex authors of Gforth
                   14618: @cindex contributors to Gforth
                   14619: 
                   14620: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81    ! anton    14621: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
        !          14622: lot to the manual.  Assemblers and disassemblers were contributed by
        !          14623: Andrew McKewan, Christian Pirker, and Bernd Thallner.  Lennart Benschop
        !          14624: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
        !          14625: inspired us with their continuous feedback. Lennart Benshop contributed
1.1       anton    14626: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
                   14627: support for calling C libraries. Helpful comments also came from Paul
                   14628: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.58      anton    14629: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, and
                   14630: Robert Epprecht. Since the release of Gforth-0.2.1 there were also
                   14631: helpful comments from many others; thank you all, sorry for not listing
                   14632: you here (but digging through my mailbox to extract your names is on my
1.81    ! anton    14633: to-do list).
1.1       anton    14634: 
                   14635: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   14636: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    14637: was developed across the Internet, and its authors did not meet
1.20      pazsan   14638: physically for the first 4 years of development.
1.1       anton    14639: 
                   14640: @section Pedigree
1.26      crook    14641: @cindex pedigree of Gforth
1.1       anton    14642: 
1.81    ! anton    14643: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
        !          14644: significant part of the design of Gforth was prescribed by ANS Forth.
1.1       anton    14645: 
1.20      pazsan   14646: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    14647: 32 bit native code version of VolksForth for the Atari ST, written
                   14648: mostly by Dietrich Weineck.
                   14649: 
1.81    ! anton    14650: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
        !          14651: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
        !          14652: the mid-80s and ported to the Atari ST in 1986.  It descends from F83.
1.1       anton    14653: 
                   14654: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   14655: Forth-83 standard. !! Pedigree? When?
                   14656: 
                   14657: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   14658: 1979. Robert Selzer and Bill Ragsdale developed the original
                   14659: implementation of fig-Forth for the 6502 based on microForth.
                   14660: 
                   14661: The principal architect of microForth was Dean Sanderson. microForth was
                   14662: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   14663: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   14664: Z80.
                   14665: 
                   14666: All earlier Forth systems were custom-made, usually by Charles Moore,
                   14667: who discovered (as he puts it) Forth during the late 60s. The first full
                   14668: Forth existed in 1971.
                   14669: 
1.81    ! anton    14670: A part of the information in this section comes from
        !          14671: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
        !          14672: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
        !          14673: Charles H. Moore, presented at the HOPL-II conference and preprinted in
        !          14674: SIGPLAN Notices 28(3), 1993.  You can find more historical and
        !          14675: genealogical information about Forth there.
1.1       anton    14676: 
1.81    ! anton    14677: @c ------------------------------------------------------------------
1.21      crook    14678: @node Forth-related information, Word Index, Origin, Top
                   14679: @appendix Other Forth-related information
                   14680: @cindex Forth-related information
                   14681: 
1.81    ! anton    14682: @c anton: I threw most of this stuff out, because it can be found through
        !          14683: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21      crook    14684: 
                   14685: @cindex comp.lang.forth
                   14686: @cindex frequently asked questions
1.81    ! anton    14687: There is an active news group (comp.lang.forth) discussing Forth
        !          14688: (including Gforth) and Forth-related issues. Its
        !          14689: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
        !          14690: (frequently asked questions and their answers) contains a lot of
        !          14691: information on Forth.  You should read it before posting to
        !          14692: comp.lang.forth.
1.21      crook    14693: 
1.81    ! anton    14694: The ANS Forth standard is most usable in its
        !          14695: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21      crook    14696: 
1.81    ! anton    14697: @c ------------------------------------------------------------------
        !          14698: @node Word Index, Concept Index, Forth-related information, Top
1.1       anton    14699: @unnumbered Word Index
                   14700: 
1.26      crook    14701: This index is a list of Forth words that have ``glossary'' entries
                   14702: within this manual. Each word is listed with its stack effect and
                   14703: wordset.
1.1       anton    14704: 
                   14705: @printindex fn
                   14706: 
1.81    ! anton    14707: @c anton: the name index seems superfluous given the word and concept indices.
        !          14708: 
        !          14709: @c @node Name Index, Concept Index, Word Index, Top
        !          14710: @c @unnumbered Name Index
1.41      anton    14711: 
1.81    ! anton    14712: @c This index is a list of Forth words that have ``glossary'' entries
        !          14713: @c within this manual.
1.41      anton    14714: 
1.81    ! anton    14715: @c @printindex ky
1.41      anton    14716: 
1.81    ! anton    14717: @node Concept Index,  , Word Index, Top
1.1       anton    14718: @unnumbered Concept and Word Index
                   14719: 
1.26      crook    14720: Not all entries listed in this index are present verbatim in the
                   14721: text. This index also duplicates, in abbreviated form, all of the words
                   14722: listed in the Word Index (only the names are listed for the words here).
1.1       anton    14723: 
                   14724: @printindex cp
                   14725: 
                   14726: @contents
                   14727: @bye
1.81    ! anton    14728: 
        !          14729: 
1.1       anton    14730: 

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