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

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.113     anton      14: @c
                     15: @c Karl Berry writes:
                     16: @c  If they don't like the all-caps for @var Info output, all I can say is
                     17: @c  that it's always been that way, and the usage of all-caps for
                     18: @c  metavariables has a long tradition.  I think it's best to just let it be
                     19: @c  what it is, for the sake of consistency among manuals.
                     20: @c
1.29      crook      21: @comment .. would be useful to have a word that identified all deferred words
                     22: @comment should semantics stuff in intro be moved to another section
                     23: 
1.66      anton      24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28      crook      25: 
1.1       anton      26: @comment %**start of header (This is for running Texinfo on a region.)
                     27: @setfilename gforth.info
1.113     anton      28: @include version.texi
1.1       anton      29: @settitle Gforth Manual
1.113     anton      30: @c @syncodeindex pg cp
1.49      anton      31: 
1.12      anton      32: @macro progstyle {}
                     33: Programming style note:
1.3       anton      34: @end macro
1.48      anton      35: 
                     36: @macro assignment {}
                     37: @table @i
                     38: @item Assignment:
                     39: @end macro
                     40: @macro endassignment {}
                     41: @end table
                     42: @end macro
                     43: 
1.29      crook      44: @comment macros for beautifying glossary entries
                     45: @macro GLOSS-START {}
                     46: @iftex
                     47: @ninerm
                     48: @end iftex
                     49: @end macro
                     50: 
                     51: @macro GLOSS-END {}
                     52: @iftex
                     53: @rm
                     54: @end iftex
                     55: @end macro
                     56: 
1.113     anton      57: @comment %**end of header (This is for running Texinfo on a region.)
                     58: @copying
1.125     anton      59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
                     60: a fast and portable implementation of the ANS Forth language.  It
                     61: serves as reference manual, but it also contains an introduction to
                     62: Forth and a Forth tutorial.
1.29      crook      63: 
1.234     anton      64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008,2009,2010,2011 Free Software Foundation, Inc.
1.29      crook      65: 
1.113     anton      66: @quotation
                     67: Permission is granted to copy, distribute and/or modify this document
                     68: under the terms of the GNU Free Documentation License, Version 1.1 or
                     69: any later version published by the Free Software Foundation; with no
                     70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
                     71: and with the Back-Cover Texts as in (a) below.  A copy of the
                     72: license is included in the section entitled ``GNU Free Documentation
                     73: License.''
                     74: 
                     75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
                     76: this GNU Manual, like GNU software.  Copies published by the Free
                     77: Software Foundation raise funds for GNU development.''
                     78: @end quotation
                     79: @end copying
1.10      anton      80: 
1.113     anton      81: @dircategory Software development
                     82: @direntry
                     83: * Gforth: (gforth).             A fast interpreter for the Forth language.
                     84: @end direntry
                     85: @c The Texinfo manual also recommends doing this, but for Gforth it may
                     86: @c  not make much sense
                     87: @c @dircategory Individual utilities
                     88: @c @direntry
                     89: @c * Gforth: (gforth)Invoking Gforth.      gforth, gforth-fast, gforthmi
                     90: @c @end direntry
1.1       anton      91: 
                     92: @titlepage
1.113     anton      93: @title Gforth
                     94: @subtitle for version @value{VERSION}, @value{UPDATED}
                     95: @author Neal Crook
                     96: @author Anton Ertl
1.114     anton      97: @author David Kuehling
1.113     anton      98: @author Bernd Paysan
                     99: @author Jens Wilke
1.1       anton     100: @page
                    101: @vskip 0pt plus 1filll
1.113     anton     102: @insertcopying
                    103: @end titlepage
1.1       anton     104: 
1.113     anton     105: @contents
1.1       anton     106: 
1.113     anton     107: @ifnottex
                    108: @node Top, Goals, (dir), (dir)
                    109: @top Gforth
1.1       anton     110: 
1.113     anton     111: @insertcopying
1.49      anton     112: @end ifnottex
1.1       anton     113: 
                    114: @menu
1.26      crook     115: * Goals::                       About the Gforth Project
1.29      crook     116: * Gforth Environment::          Starting (and exiting) Gforth
1.48      anton     117: * Tutorial::                    Hands-on Forth Tutorial
1.21      crook     118: * Introduction::                An introduction to ANS Forth
1.1       anton     119: * Words::                       Forth words available in Gforth
1.24      anton     120: * Error messages::              How to interpret them
1.1       anton     121: * Tools::                       Programming tools
                    122: * ANS conformance::             Implementation-defined options etc.
1.65      anton     123: * Standard vs Extensions::      Should I use extensions?
1.1       anton     124: * Model::                       The abstract machine of Gforth
                    125: * Integrating Gforth::          Forth as scripting language for applications
                    126: * Emacs and Gforth::            The Gforth Mode
                    127: * Image Files::                 @code{.fi} files contain compiled code
                    128: * Engine::                      The inner interpreter and the primitives
1.13      pazsan    129: * Cross Compiler::              The Cross Compiler
1.1       anton     130: * Bugs::                        How to report them
                    131: * Origin::                      Authors and ancestors of Gforth
1.21      crook     132: * Forth-related information::   Books and places to look on the WWW
1.113     anton     133: * Licenses::                    
1.1       anton     134: * Word Index::                  An item for each Forth word
                    135: * Concept Index::               A menu covering many topics
1.12      anton     136: 
1.91      anton     137: @detailmenu
                    138:  --- The Detailed Node Listing ---
1.12      anton     139: 
1.29      crook     140: Gforth Environment
                    141: 
1.32      anton     142: * Invoking Gforth::             Getting in
                    143: * Leaving Gforth::              Getting out
                    144: * Command-line editing::        
1.48      anton     145: * Environment variables::       that affect how Gforth starts up
1.32      anton     146: * Gforth Files::                What gets installed and where
1.112     anton     147: * Gforth in pipes::             
1.204     anton     148: * Startup speed::               When 14ms is not fast enough ...
1.48      anton     149: 
                    150: Forth Tutorial
                    151: 
                    152: * Starting Gforth Tutorial::    
                    153: * Syntax Tutorial::             
                    154: * Crash Course Tutorial::       
                    155: * Stack Tutorial::              
                    156: * Arithmetics Tutorial::        
                    157: * Stack Manipulation Tutorial::  
                    158: * Using files for Forth code Tutorial::  
                    159: * Comments Tutorial::           
                    160: * Colon Definitions Tutorial::  
                    161: * Decompilation Tutorial::      
                    162: * Stack-Effect Comments Tutorial::  
                    163: * Types Tutorial::              
                    164: * Factoring Tutorial::          
                    165: * Designing the stack effect Tutorial::  
                    166: * Local Variables Tutorial::    
                    167: * Conditional execution Tutorial::  
                    168: * Flags and Comparisons Tutorial::  
                    169: * General Loops Tutorial::      
                    170: * Counted loops Tutorial::      
                    171: * Recursion Tutorial::          
                    172: * Leaving definitions or loops Tutorial::  
                    173: * Return Stack Tutorial::       
                    174: * Memory Tutorial::             
                    175: * Characters and Strings Tutorial::  
                    176: * Alignment Tutorial::          
1.190     anton     177: * Floating Point Tutorial::     
1.87      anton     178: * Files Tutorial::              
1.48      anton     179: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                    180: * Execution Tokens Tutorial::   
                    181: * Exceptions Tutorial::         
                    182: * Defining Words Tutorial::     
                    183: * Arrays and Records Tutorial::  
                    184: * POSTPONE Tutorial::           
                    185: * Literal Tutorial::            
                    186: * Advanced macros Tutorial::    
                    187: * Compilation Tokens Tutorial::  
                    188: * Wordlists and Search Order Tutorial::  
1.29      crook     189: 
1.24      anton     190: An Introduction to ANS Forth
                    191: 
1.67      anton     192: * Introducing the Text Interpreter::  
                    193: * Stacks and Postfix notation::  
                    194: * Your first definition::       
                    195: * How does that work?::         
                    196: * Forth is written in Forth::   
                    197: * Review - elements of a Forth system::  
                    198: * Where to go next::            
                    199: * Exercises::                   
1.24      anton     200: 
1.12      anton     201: Forth Words
                    202: 
                    203: * Notation::                    
1.65      anton     204: * Case insensitivity::          
                    205: * Comments::                    
                    206: * Boolean Flags::               
1.12      anton     207: * Arithmetic::                  
                    208: * Stack Manipulation::          
                    209: * Memory::                      
                    210: * Control Structures::          
                    211: * Defining Words::              
1.65      anton     212: * Interpretation and Compilation Semantics::  
1.47      crook     213: * Tokens for Words::            
1.81      anton     214: * Compiling words::             
1.65      anton     215: * The Text Interpreter::        
1.111     anton     216: * The Input Stream::            
1.65      anton     217: * Word Lists::                  
                    218: * Environmental Queries::       
1.12      anton     219: * Files::                       
                    220: * Blocks::                      
                    221: * Other I/O::                   
1.121     anton     222: * OS command line arguments::   
1.78      anton     223: * Locals::                      
                    224: * Structures::                  
                    225: * Object-oriented Forth::       
1.12      anton     226: * Programming Tools::           
1.150     anton     227: * C Interface::                 
1.12      anton     228: * Assembler and Code Words::    
                    229: * Threading Words::             
1.65      anton     230: * Passing Commands to the OS::  
                    231: * Keeping track of Time::       
                    232: * Miscellaneous Words::         
1.12      anton     233: 
                    234: Arithmetic
                    235: 
                    236: * Single precision::            
1.67      anton     237: * Double precision::            Double-cell integer arithmetic
1.12      anton     238: * Bitwise operations::          
1.67      anton     239: * Numeric comparison::          
1.32      anton     240: * Mixed precision::             Operations with single and double-cell integers
1.12      anton     241: * Floating Point::              
                    242: 
                    243: Stack Manipulation
                    244: 
                    245: * Data stack::                  
                    246: * Floating point stack::        
                    247: * Return stack::                
                    248: * Locals stack::                
                    249: * Stack pointer manipulation::  
                    250: 
                    251: Memory
                    252: 
1.32      anton     253: * Memory model::                
                    254: * Dictionary allocation::       
                    255: * Heap Allocation::             
                    256: * Memory Access::               
                    257: * Address arithmetic::          
                    258: * Memory Blocks::               
1.12      anton     259: 
                    260: Control Structures
                    261: 
1.41      anton     262: * Selection::                   IF ... ELSE ... ENDIF
                    263: * Simple Loops::                BEGIN ...
1.32      anton     264: * Counted Loops::               DO
1.67      anton     265: * Arbitrary control structures::  
                    266: * Calls and returns::           
1.12      anton     267: * Exception Handling::          
                    268: 
                    269: Defining Words
                    270: 
1.67      anton     271: * CREATE::                      
1.44      crook     272: * Variables::                   Variables and user variables
1.67      anton     273: * Constants::                   
1.44      crook     274: * Values::                      Initialised variables
1.67      anton     275: * Colon Definitions::           
1.44      crook     276: * Anonymous Definitions::       Definitions without names
1.236     anton     277: * Quotations::                  
1.71      anton     278: * Supplying names::             Passing definition names as strings
1.67      anton     279: * User-defined Defining Words::  
1.170     pazsan    280: * Deferred Words::              Allow forward references
1.67      anton     281: * Aliases::                     
1.47      crook     282: 
1.63      anton     283: User-defined Defining Words
                    284: 
                    285: * CREATE..DOES> applications::  
                    286: * CREATE..DOES> details::       
                    287: * Advanced does> usage example::  
1.155     anton     288: * Const-does>::                 
1.63      anton     289: 
1.47      crook     290: Interpretation and Compilation Semantics
                    291: 
1.67      anton     292: * Combined words::              
1.12      anton     293: 
1.71      anton     294: Tokens for Words
                    295: 
                    296: * Execution token::             represents execution/interpretation semantics
                    297: * Compilation token::           represents compilation semantics
                    298: * Name token::                  represents named words
                    299: 
1.82      anton     300: Compiling words
                    301: 
                    302: * Literals::                    Compiling data values
                    303: * Macros::                      Compiling words
                    304: 
1.21      crook     305: The Text Interpreter
                    306: 
1.67      anton     307: * Input Sources::               
                    308: * Number Conversion::           
                    309: * Interpret/Compile states::    
                    310: * Interpreter Directives::      
1.21      crook     311: 
1.26      crook     312: Word Lists
                    313: 
1.75      anton     314: * Vocabularies::                
1.67      anton     315: * Why use word lists?::         
1.75      anton     316: * Word list example::           
1.26      crook     317: 
                    318: Files
                    319: 
1.48      anton     320: * Forth source files::          
                    321: * General files::               
1.167     anton     322: * Redirection::                 
1.48      anton     323: * Search Paths::                
                    324: 
                    325: Search Paths
                    326: 
1.75      anton     327: * Source Search Paths::         
1.26      crook     328: * General Search Paths::        
                    329: 
                    330: Other I/O
                    331: 
1.32      anton     332: * Simple numeric output::       Predefined formats
                    333: * Formatted numeric output::    Formatted (pictured) output
                    334: * String Formats::              How Forth stores strings in memory
1.67      anton     335: * Displaying characters and strings::  Other stuff
1.236     anton     336: * String words::                Gforth's little string library
1.178     anton     337: * Terminal output::             Cursor positioning etc.
1.181     anton     338: * Single-key input::            
                    339: * Line input and conversion::   
1.112     anton     340: * Pipes::                       How to create your own pipes
1.149     pazsan    341: * Xchars and Unicode::          Non-ASCII characters
1.26      crook     342: 
                    343: Locals
                    344: 
                    345: * Gforth locals::               
                    346: * ANS Forth locals::            
                    347: 
                    348: Gforth locals
                    349: 
                    350: * Where are locals visible by name?::  
                    351: * How long do locals live?::    
1.78      anton     352: * Locals programming style::    
                    353: * Locals implementation::       
1.26      crook     354: 
1.12      anton     355: Structures
                    356: 
                    357: * Why explicit structure support?::  
                    358: * Structure Usage::             
                    359: * Structure Naming Convention::  
                    360: * Structure Implementation::    
                    361: * Structure Glossary::          
1.183     anton     362: * Forth200x Structures::        
1.12      anton     363: 
                    364: Object-oriented Forth
                    365: 
1.48      anton     366: * Why object-oriented programming?::  
                    367: * Object-Oriented Terminology::  
                    368: * Objects::                     
                    369: * OOF::                         
                    370: * Mini-OOF::                    
1.23      crook     371: * Comparison with other object models::  
1.12      anton     372: 
1.24      anton     373: The @file{objects.fs} model
1.12      anton     374: 
                    375: * Properties of the Objects model::  
                    376: * Basic Objects Usage::         
1.41      anton     377: * The Objects base class::      
1.12      anton     378: * Creating objects::            
                    379: * Object-Oriented Programming Style::  
                    380: * Class Binding::               
                    381: * Method conveniences::         
                    382: * Classes and Scoping::         
1.41      anton     383: * Dividing classes::            
1.12      anton     384: * Object Interfaces::           
                    385: * Objects Implementation::      
                    386: * Objects Glossary::            
                    387: 
1.24      anton     388: The @file{oof.fs} model
1.12      anton     389: 
1.67      anton     390: * Properties of the OOF model::  
                    391: * Basic OOF Usage::             
                    392: * The OOF base class::          
                    393: * Class Declaration::           
                    394: * Class Implementation::        
1.12      anton     395: 
1.24      anton     396: The @file{mini-oof.fs} model
1.23      crook     397: 
1.48      anton     398: * Basic Mini-OOF Usage::        
                    399: * Mini-OOF Example::            
                    400: * Mini-OOF Implementation::     
1.23      crook     401: 
1.78      anton     402: Programming Tools
                    403: 
1.150     anton     404: * Examining::                   Data and Code.
                    405: * Forgetting words::            Usually before reloading.
1.78      anton     406: * Debugging::                   Simple and quick.
                    407: * Assertions::                  Making your programs self-checking.
                    408: * Singlestep Debugger::         Executing your program word by word.
                    409: 
1.155     anton     410: C Interface
                    411: 
                    412: * Calling C Functions::         
                    413: * Declaring C Functions::       
1.180     anton     414: * Calling C function pointers::  
1.196     anton     415: * Defining library interfaces::  
                    416: * Declaring OS-level libraries::  
1.155     anton     417: * Callbacks::                   
1.178     anton     418: * C interface internals::       
1.155     anton     419: * Low-Level C Interface Words::  
                    420: 
1.78      anton     421: Assembler and Code Words
                    422: 
1.221     anton     423: * Assembler Definitions::       Definitions in assembly language
1.78      anton     424: * Common Assembler::            Assembler Syntax
                    425: * Common Disassembler::         
                    426: * 386 Assembler::               Deviations and special cases
1.221     anton     427: * AMD64 Assembler::             
1.78      anton     428: * Alpha Assembler::             Deviations and special cases
                    429: * MIPS assembler::              Deviations and special cases
1.167     anton     430: * PowerPC assembler::           Deviations and special cases
1.193     dvdkhlng  431: * ARM Assembler::               Deviations and special cases
1.78      anton     432: * Other assemblers::            How to write them
                    433: 
1.12      anton     434: Tools
                    435: 
                    436: * ANS Report::                  Report the words used, sorted by wordset.
1.127     anton     437: * Stack depth changes::         Where does this stack item come from?
1.12      anton     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: 
1.109     anton     507: Emacs and Gforth
                    508: 
                    509: * Installing gforth.el::        Making Emacs aware of Forth.
                    510: * Emacs Tags::                  Viewing the source of a word in Emacs.
                    511: * Hilighting::                  Making Forth code look prettier.
                    512: * Auto-Indentation::            Customizing auto-indentation.
                    513: * Blocks Files::                Reading and writing blocks files.
                    514: 
1.12      anton     515: Image Files
                    516: 
1.24      anton     517: * Image Licensing Issues::      Distribution terms for images.
                    518: * Image File Background::       Why have image files?
1.67      anton     519: * Non-Relocatable Image Files::  don't always work.
1.24      anton     520: * Data-Relocatable Image Files::  are better.
1.67      anton     521: * Fully Relocatable Image Files::  better yet.
1.24      anton     522: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     523: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     524: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     525: 
                    526: Fully Relocatable Image Files
                    527: 
1.27      crook     528: * gforthmi::                    The normal way
1.12      anton     529: * cross.fs::                    The hard way
                    530: 
                    531: Engine
                    532: 
                    533: * Portability::                 
                    534: * Threading::                   
                    535: * Primitives::                  
                    536: * Performance::                 
                    537: 
                    538: Threading
                    539: 
                    540: * Scheduling::                  
                    541: * Direct or Indirect Threaded?::  
1.109     anton     542: * Dynamic Superinstructions::   
1.12      anton     543: * DOES>::                       
                    544: 
                    545: Primitives
                    546: 
                    547: * Automatic Generation::        
                    548: * TOS Optimization::            
                    549: * Produced code::               
1.13      pazsan    550: 
                    551: Cross Compiler
                    552: 
1.67      anton     553: * Using the Cross Compiler::    
                    554: * How the Cross Compiler Works::  
1.13      pazsan    555: 
1.113     anton     556: Licenses
                    557: 
                    558: * GNU Free Documentation License::  License for copying this manual.
1.192     anton     559: * Copying::                     GPL (for copying this software).
1.113     anton     560: 
1.24      anton     561: @end detailmenu
1.1       anton     562: @end menu
                    563: 
1.113     anton     564: @c ----------------------------------------------------------
1.1       anton     565: @iftex
                    566: @unnumbered Preface
                    567: @cindex Preface
1.21      crook     568: This manual documents Gforth. Some introductory material is provided for
                    569: readers who are unfamiliar with Forth or who are migrating to Gforth
                    570: from other Forth compilers. However, this manual is primarily a
                    571: reference manual.
1.1       anton     572: @end iftex
                    573: 
1.28      crook     574: @comment TODO much more blurb here.
1.26      crook     575: 
                    576: @c ******************************************************************
1.113     anton     577: @node Goals, Gforth Environment, Top, Top
1.26      crook     578: @comment node-name,     next,           previous, up
                    579: @chapter Goals of Gforth
                    580: @cindex goals of the Gforth project
                    581: The goal of the Gforth Project is to develop a standard model for
                    582: ANS Forth. This can be split into several subgoals:
                    583: 
                    584: @itemize @bullet
                    585: @item
                    586: Gforth should conform to the ANS Forth Standard.
                    587: @item
                    588: It should be a model, i.e. it should define all the
                    589: implementation-dependent things.
                    590: @item
                    591: It should become standard, i.e. widely accepted and used. This goal
                    592: is the most difficult one.
                    593: @end itemize
                    594: 
                    595: To achieve these goals Gforth should be
                    596: @itemize @bullet
                    597: @item
                    598: Similar to previous models (fig-Forth, F83)
                    599: @item
                    600: Powerful. It should provide for all the things that are considered
                    601: necessary today and even some that are not yet considered necessary.
                    602: @item
                    603: Efficient. It should not get the reputation of being exceptionally
                    604: slow.
                    605: @item
                    606: Free.
                    607: @item
                    608: Available on many machines/easy to port.
                    609: @end itemize
                    610: 
                    611: Have we achieved these goals? Gforth conforms to the ANS Forth
                    612: standard. It may be considered a model, but we have not yet documented
                    613: which parts of the model are stable and which parts we are likely to
                    614: change. It certainly has not yet become a de facto standard, but it
                    615: appears to be quite popular. It has some similarities to and some
                    616: differences from previous models. It has some powerful features, but not
                    617: yet everything that we envisioned. We certainly have achieved our
1.65      anton     618: execution speed goals (@pxref{Performance})@footnote{However, in 1998
                    619: the bar was raised when the major commercial Forth vendors switched to
                    620: native code compilers.}.  It is free and available on many machines.
1.29      crook     621: 
1.26      crook     622: @c ******************************************************************
1.48      anton     623: @node Gforth Environment, Tutorial, Goals, Top
1.29      crook     624: @chapter Gforth Environment
                    625: @cindex Gforth environment
1.21      crook     626: 
1.45      crook     627: Note: ultimately, the Gforth man page will be auto-generated from the
1.29      crook     628: material in this chapter.
1.21      crook     629: 
                    630: @menu
1.29      crook     631: * Invoking Gforth::             Getting in
                    632: * Leaving Gforth::              Getting out
                    633: * Command-line editing::        
1.48      anton     634: * Environment variables::       that affect how Gforth starts up
1.29      crook     635: * Gforth Files::                What gets installed and where
1.112     anton     636: * Gforth in pipes::             
1.204     anton     637: * Startup speed::               When 14ms is not fast enough ...
1.21      crook     638: @end menu
                    639: 
1.49      anton     640: For related information about the creation of images see @ref{Image Files}.
1.29      crook     641: 
1.21      crook     642: @comment ----------------------------------------------
1.48      anton     643: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29      crook     644: @section Invoking Gforth
                    645: @cindex invoking Gforth
                    646: @cindex running Gforth
                    647: @cindex command-line options
                    648: @cindex options on the command line
                    649: @cindex flags on the command line
1.21      crook     650: 
1.30      anton     651: Gforth is made up of two parts; an executable ``engine'' (named
1.109     anton     652: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30      anton     653: will usually just say @code{gforth} -- this automatically loads the
                    654: default image file @file{gforth.fi}. In many other cases the default
                    655: Gforth image will be invoked like this:
1.21      crook     656: @example
1.30      anton     657: gforth [file | -e forth-code] ...
1.21      crook     658: @end example
1.29      crook     659: @noindent
                    660: This interprets the contents of the files and the Forth code in the order they
                    661: are given.
1.21      crook     662: 
1.109     anton     663: In addition to the @command{gforth} engine, there is also an engine
                    664: called @command{gforth-fast}, which is faster, but gives less
                    665: informative error messages (@pxref{Error messages}) and may catch some
1.166     anton     666: errors (in particular, stack underflows and integer division errors)
                    667: later or not at all.  You should use it for debugged,
1.109     anton     668: performance-critical programs.
                    669: 
                    670: Moreover, there is an engine called @command{gforth-itc}, which is
                    671: useful in some backwards-compatibility situations (@pxref{Direct or
                    672: Indirect Threaded?}).
1.30      anton     673: 
1.29      crook     674: In general, the command line looks like this:
1.21      crook     675: 
                    676: @example
1.30      anton     677: gforth[-fast] [engine options] [image options]
1.21      crook     678: @end example
                    679: 
1.30      anton     680: The engine options must come before the rest of the command
1.29      crook     681: line. They are:
1.26      crook     682: 
1.29      crook     683: @table @code
                    684: @cindex -i, command-line option
                    685: @cindex --image-file, command-line option
                    686: @item --image-file @i{file}
                    687: @itemx -i @i{file}
                    688: Loads the Forth image @i{file} instead of the default
                    689: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook     690: 
1.39      anton     691: @cindex --appl-image, command-line option
                    692: @item --appl-image @i{file}
                    693: Loads the image @i{file} and leaves all further command-line arguments
1.65      anton     694: to the image (instead of processing them as engine options).  This is
                    695: useful for building executable application images on Unix, built with
1.39      anton     696: @code{gforthmi --application ...}.
                    697: 
1.29      crook     698: @cindex --path, command-line option
                    699: @cindex -p, command-line option
                    700: @item --path @i{path}
                    701: @itemx -p @i{path}
                    702: Uses @i{path} for searching the image file and Forth source code files
                    703: instead of the default in the environment variable @code{GFORTHPATH} or
                    704: the path specified at installation time (e.g.,
                    705: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                    706: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook     707: 
1.29      crook     708: @cindex --dictionary-size, command-line option
                    709: @cindex -m, command-line option
                    710: @cindex @i{size} parameters for command-line options
                    711: @cindex size of the dictionary and the stacks
                    712: @item --dictionary-size @i{size}
                    713: @itemx -m @i{size}
                    714: Allocate @i{size} space for the Forth dictionary space instead of
                    715: using the default specified in the image (typically 256K). The
                    716: @i{size} specification for this and subsequent options consists of
                    717: an integer and a unit (e.g.,
                    718: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                    719: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                    720: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                    721: @code{e} is used.
1.21      crook     722: 
1.29      crook     723: @cindex --data-stack-size, command-line option
                    724: @cindex -d, command-line option
                    725: @item --data-stack-size @i{size}
                    726: @itemx -d @i{size}
                    727: Allocate @i{size} space for the data stack instead of using the
                    728: default specified in the image (typically 16K).
1.21      crook     729: 
1.29      crook     730: @cindex --return-stack-size, command-line option
                    731: @cindex -r, command-line option
                    732: @item --return-stack-size @i{size}
                    733: @itemx -r @i{size}
                    734: Allocate @i{size} space for the return stack instead of using the
                    735: default specified in the image (typically 15K).
1.21      crook     736: 
1.29      crook     737: @cindex --fp-stack-size, command-line option
                    738: @cindex -f, command-line option
                    739: @item --fp-stack-size @i{size}
                    740: @itemx -f @i{size}
                    741: Allocate @i{size} space for the floating point stack instead of
                    742: using the default specified in the image (typically 15.5K). In this case
                    743: the unit specifier @code{e} refers to floating point numbers.
1.21      crook     744: 
1.48      anton     745: @cindex --locals-stack-size, command-line option
                    746: @cindex -l, command-line option
                    747: @item --locals-stack-size @i{size}
                    748: @itemx -l @i{size}
                    749: Allocate @i{size} space for the locals stack instead of using the
                    750: default specified in the image (typically 14.5K).
                    751: 
1.176     anton     752: @cindex --vm-commit, command-line option
                    753: @cindex overcommit memory for dictionary and stacks
                    754: @cindex memory overcommit for dictionary and stacks
                    755: @item --vm-commit
                    756: Normally, Gforth tries to start up even if there is not enough virtual
                    757: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
                    758: on OSs that support it); so you can ask for a really big dictionary
                    759: and/or stacks, and as long as you don't use more virtual memory than
                    760: is available, everything will be fine (but if you use more, processes
                    761: get killed).  With this option you just use the default allocation
                    762: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
                    763: means that you cannot and should not ask for as big dictionary and
                    764: stacks, but once Gforth successfully starts up, out-of-memory won't
                    765: kill it.
                    766: 
1.48      anton     767: @cindex -h, command-line option
                    768: @cindex --help, command-line option
                    769: @item --help
                    770: @itemx -h
                    771: Print a message about the command-line options
                    772: 
                    773: @cindex -v, command-line option
                    774: @cindex --version, command-line option
                    775: @item --version
                    776: @itemx -v
                    777: Print version and exit
                    778: 
                    779: @cindex --debug, command-line option
                    780: @item --debug
                    781: Print some information useful for debugging on startup.
                    782: 
                    783: @cindex --offset-image, command-line option
                    784: @item --offset-image
                    785: Start the dictionary at a slightly different position than would be used
                    786: otherwise (useful for creating data-relocatable images,
                    787: @pxref{Data-Relocatable Image Files}).
                    788: 
                    789: @cindex --no-offset-im, command-line option
                    790: @item --no-offset-im
                    791: Start the dictionary at the normal position.
                    792: 
                    793: @cindex --clear-dictionary, command-line option
                    794: @item --clear-dictionary
                    795: Initialize all bytes in the dictionary to 0 before loading the image
                    796: (@pxref{Data-Relocatable Image Files}).
                    797: 
                    798: @cindex --die-on-signal, command-line-option
                    799: @item --die-on-signal
                    800: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                    801: or the segmentation violation SIGSEGV) by translating it into a Forth
                    802: @code{THROW}. With this option, Gforth exits if it receives such a
                    803: signal. This option is useful when the engine and/or the image might be
                    804: severely broken (such that it causes another signal before recovering
                    805: from the first); this option avoids endless loops in such cases.
1.109     anton     806: 
1.119     anton     807: @cindex --no-dynamic, command-line option
                    808: @cindex --dynamic, command-line option
1.109     anton     809: @item --no-dynamic
                    810: @item --dynamic
                    811: Disable or enable dynamic superinstructions with replication
                    812: (@pxref{Dynamic Superinstructions}).
                    813: 
1.119     anton     814: @cindex --no-super, command-line option
1.109     anton     815: @item --no-super
1.110     anton     816: Disable dynamic superinstructions, use just dynamic replication; this is
                    817: useful if you want to patch threaded code (@pxref{Dynamic
                    818: Superinstructions}).
1.119     anton     819: 
                    820: @cindex --ss-number, command-line option
                    821: @item --ss-number=@var{N}
                    822: Use only the first @var{N} static superinstructions compiled into the
                    823: engine (default: use them all; note that only @code{gforth-fast} has
                    824: any).  This option is useful for measuring the performance impact of
                    825: static superinstructions.
                    826: 
                    827: @cindex --ss-min-..., command-line options
                    828: @item --ss-min-codesize
                    829: @item --ss-min-ls
                    830: @item --ss-min-lsu
                    831: @item --ss-min-nexts
                    832: Use specified metric for determining the cost of a primitive or static
                    833: superinstruction for static superinstruction selection.  @code{Codesize}
                    834: is the native code size of the primive or static superinstruction,
                    835: @code{ls} is the number of loads and stores, @code{lsu} is the number of
                    836: loads, stores, and updates, and @code{nexts} is the number of dispatches
                    837: (not taking dynamic superinstructions into account), i.e. every
                    838: primitive or static superinstruction has cost 1. Default:
                    839: @code{codesize} if you use dynamic code generation, otherwise
                    840: @code{nexts}.
                    841: 
                    842: @cindex --ss-greedy, command-line option
                    843: @item --ss-greedy
                    844: This option is useful for measuring the performance impact of static
                    845: superinstructions.  By default, an optimal shortest-path algorithm is
                    846: used for selecting static superinstructions.  With @option{--ss-greedy}
                    847: this algorithm is modified to assume that anything after the static
                    848: superinstruction currently under consideration is not combined into
                    849: static superinstructions.  With @option{--ss-min-nexts} this produces
                    850: the same result as a greedy algorithm that always selects the longest
                    851: superinstruction available at the moment.  E.g., if there are
                    852: superinstructions AB and BCD, then for the sequence A B C D the optimal
                    853: algorithm will select A BCD and the greedy algorithm will select AB C D.
                    854: 
                    855: @cindex --print-metrics, command-line option
                    856: @item --print-metrics
                    857: Prints some metrics used during static superinstruction selection:
                    858: @code{code size} is the actual size of the dynamically generated code.
                    859: @code{Metric codesize} is the sum of the codesize metrics as seen by
                    860: static superinstruction selection; there is a difference from @code{code
                    861: size}, because not all primitives and static superinstructions are
                    862: compiled into dynamically generated code, and because of markers.  The
                    863: other metrics correspond to the @option{ss-min-...} options.  This
                    864: option is useful for evaluating the effects of the @option{--ss-...}
                    865: options.
1.109     anton     866: 
1.48      anton     867: @end table
                    868: 
                    869: @cindex loading files at startup
                    870: @cindex executing code on startup
                    871: @cindex batch processing with Gforth
                    872: As explained above, the image-specific command-line arguments for the
                    873: default image @file{gforth.fi} consist of a sequence of filenames and
                    874: @code{-e @var{forth-code}} options that are interpreted in the sequence
                    875: in which they are given. The @code{-e @var{forth-code}} or
1.121     anton     876: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
                    877: option takes only one argument; if you want to evaluate more Forth
                    878: words, you have to quote them or use @code{-e} several times. To exit
1.48      anton     879: after processing the command line (instead of entering interactive mode)
1.121     anton     880: append @code{-e bye} to the command line.  You can also process the
                    881: command-line arguments with a Forth program (@pxref{OS command line
                    882: arguments}).
1.48      anton     883: 
                    884: @cindex versions, invoking other versions of Gforth
                    885: If you have several versions of Gforth installed, @code{gforth} will
                    886: invoke the version that was installed last. @code{gforth-@i{version}}
                    887: invokes a specific version. If your environment contains the variable
                    888: @code{GFORTHPATH}, you may want to override it by using the
                    889: @code{--path} option.
                    890: 
                    891: Not yet implemented:
                    892: On startup the system first executes the system initialization file
                    893: (unless the option @code{--no-init-file} is given; note that the system
                    894: resulting from using this option may not be ANS Forth conformant). Then
                    895: the user initialization file @file{.gforth.fs} is executed, unless the
1.62      crook     896: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48      anton     897: then in @file{~}, then in the normal path (see above).
                    898: 
                    899: 
                    900: 
                    901: @comment ----------------------------------------------
                    902: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                    903: @section Leaving Gforth
                    904: @cindex Gforth - leaving
                    905: @cindex leaving Gforth
                    906: 
                    907: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                    908: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                    909: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49      anton     910: data are discarded.  For ways of saving the state of the system before
                    911: leaving Gforth see @ref{Image Files}.
1.48      anton     912: 
                    913: doc-bye
                    914: 
                    915: 
                    916: @comment ----------------------------------------------
1.65      anton     917: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48      anton     918: @section Command-line editing
                    919: @cindex command-line editing
                    920: 
                    921: Gforth maintains a history file that records every line that you type to
                    922: the text interpreter. This file is preserved between sessions, and is
                    923: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
                    924: repeatedly you can recall successively older commands from this (or
                    925: previous) session(s). The full list of command-line editing facilities is:
                    926: 
                    927: @itemize @bullet
                    928: @item
                    929: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
                    930: commands from the history buffer.
                    931: @item
                    932: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
                    933: from the history buffer.
                    934: @item
                    935: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
                    936: @item
                    937: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
                    938: @item
                    939: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
                    940: closing up the line.
                    941: @item
                    942: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
                    943: @item
                    944: @kbd{Ctrl-a} to move the cursor to the start of the line.
                    945: @item
                    946: @kbd{Ctrl-e} to move the cursor to the end of the line.
                    947: @item
                    948: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
                    949: line.
                    950: @item
                    951: @key{TAB} to step through all possible full-word completions of the word
                    952: currently being typed.
                    953: @item
1.65      anton     954: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
                    955: using @code{bye}). 
                    956: @item
                    957: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
                    958: character under the cursor.
1.48      anton     959: @end itemize
                    960: 
                    961: When editing, displayable characters are inserted to the left of the
                    962: cursor position; the line is always in ``insert'' (as opposed to
                    963: ``overstrike'') mode.
                    964: 
                    965: @cindex history file
                    966: @cindex @file{.gforth-history}
                    967: On Unix systems, the history file is @file{~/.gforth-history} by
                    968: default@footnote{i.e. it is stored in the user's home directory.}. You
                    969: can find out the name and location of your history file using:
                    970: 
                    971: @example 
                    972: history-file type \ Unix-class systems
                    973: 
                    974: history-file type \ Other systems
                    975: history-dir  type
                    976: @end example
                    977: 
                    978: If you enter long definitions by hand, you can use a text editor to
                    979: paste them out of the history file into a Forth source file for reuse at
                    980: a later time.
                    981: 
                    982: Gforth never trims the size of the history file, so you should do this
                    983: periodically, if necessary.
                    984: 
                    985: @comment this is all defined in history.fs
                    986: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
                    987: @comment chosen?
                    988: 
                    989: 
                    990: @comment ----------------------------------------------
1.65      anton     991: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48      anton     992: @section Environment variables
                    993: @cindex environment variables
                    994: 
                    995: Gforth uses these environment variables:
                    996: 
                    997: @itemize @bullet
                    998: @item
                    999: @cindex @code{GFORTHHIST} -- environment variable
                   1000: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
                   1001: open/create the history file, @file{.gforth-history}. Default:
                   1002: @code{$HOME}.
                   1003: 
                   1004: @item
                   1005: @cindex @code{GFORTHPATH} -- environment variable
                   1006: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
                   1007: for Forth source-code files.
                   1008: 
                   1009: @item
1.147     anton    1010: @cindex @code{LANG} -- environment variable
                   1011: @code{LANG} -- see @code{LC_CTYPE}
                   1012: 
                   1013: @item
                   1014: @cindex @code{LC_ALL} -- environment variable
                   1015: @code{LC_ALL} -- see @code{LC_CTYPE}
                   1016: 
                   1017: @item
                   1018: @cindex @code{LC_CTYPE} -- environment variable
                   1019: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
                   1020: startup, Gforth uses the UTF-8 encoding for strings internally and
                   1021: expects its input and produces its output in UTF-8 encoding, otherwise
                   1022: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
                   1023: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
                   1024: that is unset, in @code{LANG}.
                   1025: 
                   1026: @item
1.129     anton    1027: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
                   1028: 
                   1029: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
                   1030: of @code{system} before passing it to C's @code{system()}.  Default:
1.130     anton    1031: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
1.129     anton    1032: and the command are directly concatenated, so if a space between them is
                   1033: necessary, append it to the prefix.
                   1034: 
                   1035: @item
1.48      anton    1036: @cindex @code{GFORTH} -- environment variable
1.49      anton    1037: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1038: 
                   1039: @item
                   1040: @cindex @code{GFORTHD} -- environment variable
1.62      crook    1041: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1042: 
                   1043: @item
                   1044: @cindex @code{TMP}, @code{TEMP} - environment variable
                   1045: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
                   1046: location for the history file.
                   1047: @end itemize
                   1048: 
                   1049: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1050: @comment mentioning these.
                   1051: 
                   1052: All the Gforth environment variables default to sensible values if they
                   1053: are not set.
                   1054: 
                   1055: 
                   1056: @comment ----------------------------------------------
1.112     anton    1057: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48      anton    1058: @section Gforth files
                   1059: @cindex Gforth files
                   1060: 
                   1061: When you install Gforth on a Unix system, it installs files in these
                   1062: locations by default:
                   1063: 
                   1064: @itemize @bullet
                   1065: @item
                   1066: @file{/usr/local/bin/gforth}
                   1067: @item
                   1068: @file{/usr/local/bin/gforthmi}
                   1069: @item
                   1070: @file{/usr/local/man/man1/gforth.1} - man page.
                   1071: @item
                   1072: @file{/usr/local/info} - the Info version of this manual.
                   1073: @item
                   1074: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
                   1075: @item
                   1076: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
                   1077: @item
                   1078: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
                   1079: @item
                   1080: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
                   1081: @end itemize
                   1082: 
                   1083: You can select different places for installation by using
                   1084: @code{configure} options (listed with @code{configure --help}).
                   1085: 
                   1086: @comment ----------------------------------------------
1.112     anton    1087: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
                   1088: @section Gforth in pipes
                   1089: @cindex pipes, Gforth as part of
                   1090: 
                   1091: Gforth can be used in pipes created elsewhere (described here).  It can
                   1092: also create pipes on its own (@pxref{Pipes}).
                   1093: 
                   1094: @cindex input from pipes
                   1095: If you pipe into Gforth, your program should read with @code{read-file}
                   1096: or @code{read-line} from @code{stdin} (@pxref{General files}).
                   1097: @code{Key} does not recognize the end of input.  Words like
                   1098: @code{accept} echo the input and are therefore usually not useful for
                   1099: reading from a pipe.  You have to invoke the Forth program with an OS
                   1100: command-line option, as you have no chance to use the Forth command line
                   1101: (the text interpreter would try to interpret the pipe input).
                   1102: 
                   1103: @cindex output in pipes
                   1104: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
                   1105: 
                   1106: @cindex silent exiting from Gforth
                   1107: When you write to a pipe that has been closed at the other end, Gforth
                   1108: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
                   1109: into the exception @code{broken-pipe-error}.  If your application does
                   1110: not catch that exception, the system catches it and exits, usually
                   1111: silently (unless you were working on the Forth command line; then it
                   1112: prints an error message and exits).  This is usually the desired
                   1113: behaviour.
                   1114: 
                   1115: If you do not like this behaviour, you have to catch the exception
                   1116: yourself, and react to it.
                   1117: 
                   1118: Here's an example of an invocation of Gforth that is usable in a pipe:
                   1119: 
                   1120: @example
                   1121: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
                   1122:  type repeat ; foo bye"
                   1123: @end example
                   1124: 
                   1125: This example just copies the input verbatim to the output.  A very
                   1126: simple pipe containing this example looks like this:
                   1127: 
                   1128: @example
                   1129: cat startup.fs |
                   1130: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
                   1131:  type repeat ; foo bye"|
                   1132: head
                   1133: @end example
                   1134: 
                   1135: @cindex stderr and pipes
                   1136: Pipes involving Gforth's @code{stderr} output do not work.
                   1137: 
                   1138: @comment ----------------------------------------------
                   1139: @node Startup speed,  , Gforth in pipes, Gforth Environment
1.48      anton    1140: @section Startup speed
                   1141: @cindex Startup speed
                   1142: @cindex speed, startup
                   1143: 
                   1144: If Gforth is used for CGI scripts or in shell scripts, its startup
1.204     anton    1145: speed may become a problem.  On a 3GHz Core 2 Duo E8400 under 64-bit
                   1146: Linux 2.6.27.8 with libc-2.7, @code{gforth-fast -e bye} takes 13.1ms
                   1147: user and 1.2ms system time (@code{gforth -e bye} is faster on startup
                   1148: with about 3.4ms user time and 1.2ms system time, because it subsumes
                   1149: some of the options discussed below).
1.48      anton    1150: 
                   1151: If startup speed is a problem, you may consider the following ways to
                   1152: improve it; or you may consider ways to reduce the number of startups
1.204     anton    1153: (for example, by using Fast-CGI).  Note that the first steps below
                   1154: improve the startup time at the cost of run-time (including
                   1155: compile-time), so whether they are profitable depends on the balance
                   1156: of these times in your application.
                   1157: 
                   1158: An easy step that influences Gforth startup speed is the use of a
                   1159: number of options that increase run-time, but decrease image-loading
                   1160: time.
                   1161: 
                   1162: The first of these that you should try is @code{--ss-number=0
                   1163: --ss-states=1} because this option buys relatively little run-time
                   1164: speedup and costs quite a bit of time at startup.  @code{gforth-fast
                   1165: --ss-number=0 --ss-states=1 -e bye} takes about 2.8ms user and 1.5ms
                   1166: system time.
1.48      anton    1167: 
1.204     anton    1168: The next option is @code{--no-dynamic} which has a substantial impact
                   1169: on run-time (about a factor of 2 on several platforms), but still
                   1170: makes startup speed a little faster: @code{gforth-fast --ss-number=0
                   1171: --ss-states=1 --no-dynamic -e bye} consumes about 2.6ms user and 1.2ms
                   1172: system time.
                   1173: 
                   1174: The next step to improve startup speed is to use a data-relocatable
                   1175: image (@pxref{Data-Relocatable Image Files}).  This avoids the
                   1176: relocation cost for the code in the image (but not for the data).
                   1177: Note that the image is then specific to the particular binary you are
                   1178: using (i.e., whether it is @code{gforth}, @code{gforth-fast}, and even
                   1179: the particular build).  You create the data-relocatable image that
                   1180: works with @code{./gforth-fast} with @code{GFORTHD="./gforth-fast
                   1181: --no-dynamic" gforthmi gforthdr.fi} (the @code{--no-dynamic} is
                   1182: required here or the image will not work).  And you run it with
                   1183: @code{gforth-fast -i gforthdr.fi ... -e bye} (the flags discussed
                   1184: above don't matter here, because they only come into play on
                   1185: relocatable code).  @code{gforth-fast -i gforthdr.fi -e bye} takes
                   1186: about 1.1ms user and 1.2ms system time.
                   1187: 
                   1188: One step further is to avoid all relocation cost and part of the
                   1189: copy-on-write cost through using a non-relocatable image
                   1190: (@pxref{Non-Relocatable Image Files}).  However, this has the
                   1191: disadvantage that it does not work on operating systems with address
                   1192: space randomization (the default in, e.g., Linux nowadays), or if the
                   1193: dictionary moves for any other reason (e.g., because of a change of
                   1194: the OS kernel or an updated library), so we cannot really recommend
                   1195: it.  You create a non-relocatable image with @code{gforth-fast
                   1196: --no-dynamic -e "savesystem gforthnr.fi bye"} (the @code{--no-dynamic}
                   1197: is required here, too).  And you run it with @code{gforth-fast -i
                   1198: gforthnr.fi ... -e bye} (again the flags discussed above don't
                   1199: matter).  @code{gforth-fast -i gforthdr.fi -e bye} takes
                   1200: about 0.9ms user and 0.9ms system time.
                   1201: 
                   1202: If the script you want to execute contains a significant amount of
                   1203: code, it may be profitable to compile it into the image to avoid the
                   1204: cost of compiling it at startup time.
1.48      anton    1205: 
                   1206: @c ******************************************************************
                   1207: @node Tutorial, Introduction, Gforth Environment, Top
                   1208: @chapter Forth Tutorial
                   1209: @cindex Tutorial
                   1210: @cindex Forth Tutorial
                   1211: 
1.67      anton    1212: @c Topics from nac's Introduction that could be mentioned:
                   1213: @c press <ret> after each line
                   1214: @c Prompt
                   1215: @c numbers vs. words in dictionary on text interpretation
                   1216: @c what happens on redefinition
                   1217: @c parsing words (in particular, defining words)
                   1218: 
1.83      anton    1219: The difference of this chapter from the Introduction
                   1220: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
                   1221: be used while sitting in front of a computer, and covers much more
                   1222: material, but does not explain how the Forth system works.
                   1223: 
1.62      crook    1224: This tutorial can be used with any ANS-compliant Forth; any
1.206     anton    1225: Gforth-specific features are marked as such and you can skip them if
                   1226: you work with another Forth.  This tutorial does not explain all
                   1227: features of Forth, just enough to get you started and give you some
                   1228: ideas about the facilities available in Forth.  Read the rest of the
                   1229: manual when you are through this.
1.48      anton    1230: 
                   1231: The intended way to use this tutorial is that you work through it while
                   1232: sitting in front of the console, take a look at the examples and predict
                   1233: what they will do, then try them out; if the outcome is not as expected,
                   1234: find out why (e.g., by trying out variations of the example), so you
                   1235: understand what's going on.  There are also some assignments that you
                   1236: should solve.
                   1237: 
                   1238: This tutorial assumes that you have programmed before and know what,
                   1239: e.g., a loop is.
                   1240: 
                   1241: @c !! explain compat library
                   1242: 
                   1243: @menu
                   1244: * Starting Gforth Tutorial::    
                   1245: * Syntax Tutorial::             
                   1246: * Crash Course Tutorial::       
                   1247: * Stack Tutorial::              
                   1248: * Arithmetics Tutorial::        
                   1249: * Stack Manipulation Tutorial::  
                   1250: * Using files for Forth code Tutorial::  
                   1251: * Comments Tutorial::           
                   1252: * Colon Definitions Tutorial::  
                   1253: * Decompilation Tutorial::      
                   1254: * Stack-Effect Comments Tutorial::  
                   1255: * Types Tutorial::              
                   1256: * Factoring Tutorial::          
                   1257: * Designing the stack effect Tutorial::  
                   1258: * Local Variables Tutorial::    
                   1259: * Conditional execution Tutorial::  
                   1260: * Flags and Comparisons Tutorial::  
                   1261: * General Loops Tutorial::      
                   1262: * Counted loops Tutorial::      
                   1263: * Recursion Tutorial::          
                   1264: * Leaving definitions or loops Tutorial::  
                   1265: * Return Stack Tutorial::       
                   1266: * Memory Tutorial::             
                   1267: * Characters and Strings Tutorial::  
                   1268: * Alignment Tutorial::          
1.190     anton    1269: * Floating Point Tutorial::     
1.87      anton    1270: * Files Tutorial::              
1.48      anton    1271: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1272: * Execution Tokens Tutorial::   
                   1273: * Exceptions Tutorial::         
                   1274: * Defining Words Tutorial::     
                   1275: * Arrays and Records Tutorial::  
                   1276: * POSTPONE Tutorial::           
                   1277: * Literal Tutorial::            
                   1278: * Advanced macros Tutorial::    
                   1279: * Compilation Tokens Tutorial::  
                   1280: * Wordlists and Search Order Tutorial::  
                   1281: @end menu
                   1282: 
                   1283: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1284: @section Starting Gforth
1.66      anton    1285: @cindex starting Gforth tutorial
1.48      anton    1286: You can start Gforth by typing its name:
                   1287: 
                   1288: @example
                   1289: gforth
                   1290: @end example
                   1291: 
                   1292: That puts you into interactive mode; you can leave Gforth by typing
                   1293: @code{bye}.  While in Gforth, you can edit the command line and access
                   1294: the command line history with cursor keys, similar to bash.
                   1295: 
                   1296: 
                   1297: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1298: @section Syntax
1.66      anton    1299: @cindex syntax tutorial
1.48      anton    1300: 
1.171     anton    1301: A @dfn{word} is a sequence of arbitrary characters (except white
1.48      anton    1302: space).  Words are separated by white space.  E.g., each of the
                   1303: following lines contains exactly one word:
                   1304: 
                   1305: @example
                   1306: word
                   1307: !@@#$%^&*()
                   1308: 1234567890
                   1309: 5!a
                   1310: @end example
                   1311: 
1.205     anton    1312: A frequent beginner's error is to leave out necessary white space,
1.48      anton    1313: resulting in an error like @samp{Undefined word}; so if you see such an
                   1314: error, check if you have put spaces wherever necessary.
                   1315: 
                   1316: @example
                   1317: ." hello, world" \ correct
                   1318: ."hello, world"  \ gives an "Undefined word" error
                   1319: @end example
                   1320: 
1.65      anton    1321: Gforth and most other Forth systems ignore differences in case (they are
1.48      anton    1322: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1323: your system is case-sensitive, you may have to type all the examples
                   1324: given here in upper case.
                   1325: 
                   1326: 
                   1327: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1328: @section Crash Course
                   1329: 
1.209     anton    1330: Forth does not prevent you from shooting yourself in the foot.  Let's
                   1331: try a few ways to crash Gforth:
1.48      anton    1332: 
                   1333: @example
                   1334: 0 0 !
                   1335: here execute
                   1336: ' catch >body 20 erase abort
                   1337: ' (quit) >body 20 erase
                   1338: @end example
                   1339: 
1.209     anton    1340: The last two examples are guaranteed to destroy important parts of
                   1341: Gforth (and most other systems), so you better leave Gforth afterwards
                   1342: (if it has not finished by itself).  On some systems you may have to
                   1343: kill gforth from outside (e.g., in Unix with @code{kill}).
                   1344: 
                   1345: You will find out later what these lines do and then you will get an
                   1346: idea why they produce crashes.
1.48      anton    1347: 
                   1348: Now that you know how to produce crashes (and that there's not much to
                   1349: them), let's learn how to produce meaningful programs.
                   1350: 
                   1351: 
                   1352: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1353: @section Stack
1.66      anton    1354: @cindex stack tutorial
1.48      anton    1355: 
                   1356: The most obvious feature of Forth is the stack.  When you type in a
1.205     anton    1357: number, it is pushed on the stack.  You can display the contents of the
1.48      anton    1358: stack with @code{.s}.
                   1359: 
                   1360: @example
                   1361: 1 2 .s
                   1362: 3 .s
                   1363: @end example
                   1364: 
                   1365: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1366: appear in @code{.s} output as they appeared in the input.
                   1367: 
1.205     anton    1368: You can print the top element of the stack with @code{.}.
1.48      anton    1369: 
                   1370: @example
                   1371: 1 2 3 . . .
                   1372: @end example
                   1373: 
                   1374: In general, words consume their stack arguments (@code{.s} is an
                   1375: exception).
                   1376: 
1.141     anton    1377: @quotation Assignment
1.48      anton    1378: What does the stack contain after @code{5 6 7 .}?
1.141     anton    1379: @end quotation
1.48      anton    1380: 
                   1381: 
                   1382: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1383: @section Arithmetics
1.66      anton    1384: @cindex arithmetics tutorial
1.48      anton    1385: 
                   1386: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1387: operate on the top two stack items:
                   1388: 
                   1389: @example
1.67      anton    1390: 2 2 .s
                   1391: + .s
                   1392: .
1.48      anton    1393: 2 1 - .
                   1394: 7 3 mod .
                   1395: @end example
                   1396: 
                   1397: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1398: as in the corresponding infix expression (this is generally the case in
                   1399: Forth).
                   1400: 
                   1401: Parentheses are superfluous (and not available), because the order of
                   1402: the words unambiguously determines the order of evaluation and the
                   1403: operands:
                   1404: 
                   1405: @example
                   1406: 3 4 + 5 * .
                   1407: 3 4 5 * + .
                   1408: @end example
                   1409: 
1.141     anton    1410: @quotation Assignment
1.48      anton    1411: What are the infix expressions corresponding to the Forth code above?
                   1412: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1413: known as Postfix or RPN (Reverse Polish Notation).}.
1.141     anton    1414: @end quotation
1.48      anton    1415: 
                   1416: To change the sign, use @code{negate}:
                   1417: 
                   1418: @example
                   1419: 2 negate .
                   1420: @end example
                   1421: 
1.141     anton    1422: @quotation Assignment
1.48      anton    1423: Convert -(-3)*4-5 to Forth.
1.141     anton    1424: @end quotation
1.48      anton    1425: 
                   1426: @code{/mod} performs both @code{/} and @code{mod}.
                   1427: 
                   1428: @example
                   1429: 7 3 /mod . .
                   1430: @end example
                   1431: 
1.66      anton    1432: Reference: @ref{Arithmetic}.
                   1433: 
                   1434: 
1.48      anton    1435: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1436: @section Stack Manipulation
1.66      anton    1437: @cindex stack manipulation tutorial
1.48      anton    1438: 
                   1439: Stack manipulation words rearrange the data on the stack.
                   1440: 
                   1441: @example
                   1442: 1 .s drop .s
                   1443: 1 .s dup .s drop drop .s
                   1444: 1 2 .s over .s drop drop drop
                   1445: 1 2 .s swap .s drop drop
                   1446: 1 2 3 .s rot .s drop drop drop
                   1447: @end example
                   1448: 
                   1449: These are the most important stack manipulation words.  There are also
                   1450: variants that manipulate twice as many stack items:
                   1451: 
                   1452: @example
                   1453: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1454: @end example
                   1455: 
                   1456: Two more stack manipulation words are:
                   1457: 
                   1458: @example
                   1459: 1 2 .s nip .s drop
                   1460: 1 2 .s tuck .s 2drop drop
                   1461: @end example
                   1462: 
1.141     anton    1463: @quotation Assignment
1.48      anton    1464: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1465: manipulation words.
                   1466: 
                   1467: @example
                   1468: Given:          How do you get:
                   1469: 1 2 3           3 2 1           
                   1470: 1 2 3           1 2 3 2                 
                   1471: 1 2 3           1 2 3 3                 
                   1472: 1 2 3           1 3 3           
                   1473: 1 2 3           2 1 3           
                   1474: 1 2 3 4         4 3 2 1         
                   1475: 1 2 3           1 2 3 1 2 3             
                   1476: 1 2 3 4         1 2 3 4 1 2             
                   1477: 1 2 3
                   1478: 1 2 3           1 2 3 4                 
                   1479: 1 2 3           1 3             
                   1480: @end example
1.141     anton    1481: @end quotation
1.48      anton    1482: 
                   1483: @example
                   1484: 5 dup * .
                   1485: @end example
                   1486: 
1.141     anton    1487: @quotation Assignment
1.48      anton    1488: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1489: Write a piece of Forth code that expects two numbers on the stack
                   1490: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1491: @code{(a-b)(a+1)}.
1.141     anton    1492: @end quotation
1.48      anton    1493: 
1.66      anton    1494: Reference: @ref{Stack Manipulation}.
                   1495: 
                   1496: 
1.48      anton    1497: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1498: @section Using files for Forth code
1.66      anton    1499: @cindex loading Forth code, tutorial
                   1500: @cindex files containing Forth code, tutorial
1.48      anton    1501: 
                   1502: While working at the Forth command line is convenient for one-line
                   1503: examples and short one-off code, you probably want to store your source
                   1504: code in files for convenient editing and persistence.  You can use your
                   1505: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102     anton    1506: Gforth}) to create @var{file.fs} and use
1.48      anton    1507: 
                   1508: @example
1.102     anton    1509: s" @var{file.fs}" included
1.48      anton    1510: @end example
                   1511: 
                   1512: to load it into your Forth system.  The file name extension I use for
                   1513: Forth files is @samp{.fs}.
                   1514: 
                   1515: You can easily start Gforth with some files loaded like this:
                   1516: 
                   1517: @example
1.102     anton    1518: gforth @var{file1.fs} @var{file2.fs}
1.48      anton    1519: @end example
                   1520: 
                   1521: If an error occurs during loading these files, Gforth terminates,
                   1522: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1523: a Gforth command line.  Starting the Forth system every time gives you a
                   1524: clean start every time, without interference from the results of earlier
                   1525: tries.
                   1526: 
                   1527: I often put all the tests in a file, then load the code and run the
                   1528: tests with
                   1529: 
                   1530: @example
1.102     anton    1531: gforth @var{code.fs} @var{tests.fs} -e bye
1.48      anton    1532: @end example
                   1533: 
                   1534: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1535: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1536: restart this command without ado.
                   1537: 
                   1538: The advantage of this approach is that the tests can be repeated easily
                   1539: every time the program ist changed, making it easy to catch bugs
                   1540: introduced by the change.
                   1541: 
1.66      anton    1542: Reference: @ref{Forth source files}.
                   1543: 
1.48      anton    1544: 
                   1545: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1546: @section Comments
1.66      anton    1547: @cindex comments tutorial
1.48      anton    1548: 
                   1549: @example
                   1550: \ That's a comment; it ends at the end of the line
                   1551: ( Another comment; it ends here: )  .s
                   1552: @end example
                   1553: 
                   1554: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1555: separated with white space from the following text.
                   1556: 
                   1557: @example
                   1558: \This gives an "Undefined word" error
                   1559: @end example
                   1560: 
                   1561: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1562: nest @code{(}-comments; and you cannot comment out text containing a
                   1563: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1564: avoid @code{)} in word names.}.
                   1565: 
                   1566: I use @code{\}-comments for descriptive text and for commenting out code
                   1567: of one or more line; I use @code{(}-comments for describing the stack
                   1568: effect, the stack contents, or for commenting out sub-line pieces of
                   1569: code.
                   1570: 
                   1571: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1572: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1573: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1574: with @kbd{M-q}.
                   1575: 
1.66      anton    1576: Reference: @ref{Comments}.
                   1577: 
1.48      anton    1578: 
                   1579: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1580: @section Colon Definitions
1.66      anton    1581: @cindex colon definitions, tutorial
                   1582: @cindex definitions, tutorial
                   1583: @cindex procedures, tutorial
                   1584: @cindex functions, tutorial
1.48      anton    1585: 
                   1586: are similar to procedures and functions in other programming languages.
                   1587: 
                   1588: @example
                   1589: : squared ( n -- n^2 )
                   1590:    dup * ;
                   1591: 5 squared .
                   1592: 7 squared .
                   1593: @end example
                   1594: 
                   1595: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1596: following comment describes its stack effect.  The words @code{dup *}
                   1597: are not executed, but compiled into the definition.  @code{;} ends the
                   1598: colon definition.
                   1599: 
                   1600: The newly-defined word can be used like any other word, including using
                   1601: it in other definitions:
                   1602: 
                   1603: @example
                   1604: : cubed ( n -- n^3 )
                   1605:    dup squared * ;
                   1606: -5 cubed .
                   1607: : fourth-power ( n -- n^4 )
                   1608:    squared squared ;
                   1609: 3 fourth-power .
                   1610: @end example
                   1611: 
1.141     anton    1612: @quotation Assignment
1.48      anton    1613: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1614: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1615: test your tests on the originals first).  Don't let the
                   1616: @samp{redefined}-Messages spook you, they are just warnings.
1.141     anton    1617: @end quotation
1.48      anton    1618: 
1.66      anton    1619: Reference: @ref{Colon Definitions}.
                   1620: 
1.48      anton    1621: 
                   1622: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1623: @section Decompilation
1.66      anton    1624: @cindex decompilation tutorial
                   1625: @cindex see tutorial
1.48      anton    1626: 
                   1627: You can decompile colon definitions with @code{see}:
                   1628: 
                   1629: @example
                   1630: see squared
                   1631: see cubed
                   1632: @end example
                   1633: 
                   1634: In Gforth @code{see} shows you a reconstruction of the source code from
                   1635: the executable code.  Informations that were present in the source, but
                   1636: not in the executable code, are lost (e.g., comments).
                   1637: 
1.65      anton    1638: You can also decompile the predefined words:
                   1639: 
                   1640: @example
                   1641: see .
                   1642: see +
                   1643: @end example
                   1644: 
                   1645: 
1.48      anton    1646: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1647: @section Stack-Effect Comments
1.66      anton    1648: @cindex stack-effect comments, tutorial
                   1649: @cindex --, tutorial
1.48      anton    1650: By convention the comment after the name of a definition describes the
1.171     anton    1651: stack effect: The part in front of the @samp{--} describes the state of
1.48      anton    1652: the stack before the execution of the definition, i.e., the parameters
                   1653: that are passed into the colon definition; the part behind the @samp{--}
                   1654: is the state of the stack after the execution of the definition, i.e.,
                   1655: the results of the definition.  The stack comment only shows the top
                   1656: stack items that the definition accesses and/or changes.
                   1657: 
                   1658: You should put a correct stack effect on every definition, even if it is
                   1659: just @code{( -- )}.  You should also add some descriptive comment to
                   1660: more complicated words (I usually do this in the lines following
                   1661: @code{:}).  If you don't do this, your code becomes unreadable (because
1.117     anton    1662: you have to work through every definition before you can understand
1.48      anton    1663: any).
                   1664: 
1.141     anton    1665: @quotation Assignment
1.48      anton    1666: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1667: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1668: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
1.65      anton    1669: are done, you can compare your stack effects to those in this manual
1.48      anton    1670: (@pxref{Word Index}).
1.141     anton    1671: @end quotation
1.48      anton    1672: 
                   1673: Sometimes programmers put comments at various places in colon
                   1674: definitions that describe the contents of the stack at that place (stack
                   1675: comments); i.e., they are like the first part of a stack-effect
                   1676: comment. E.g.,
                   1677: 
                   1678: @example
                   1679: : cubed ( n -- n^3 )
                   1680:    dup squared  ( n n^2 ) * ;
                   1681: @end example
                   1682: 
                   1683: In this case the stack comment is pretty superfluous, because the word
                   1684: is simple enough.  If you think it would be a good idea to add such a
                   1685: comment to increase readability, you should also consider factoring the
                   1686: word into several simpler words (@pxref{Factoring Tutorial,,
1.60      anton    1687: Factoring}), which typically eliminates the need for the stack comment;
1.48      anton    1688: however, if you decide not to refactor it, then having such a comment is
                   1689: better than not having it.
                   1690: 
                   1691: The names of the stack items in stack-effect and stack comments in the
                   1692: standard, in this manual, and in many programs specify the type through
                   1693: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1694: frequent prefixes are:
                   1695: 
                   1696: @table @code
                   1697: @item n
                   1698: signed integer
                   1699: @item u
                   1700: unsigned integer
                   1701: @item c
                   1702: character
                   1703: @item f
                   1704: Boolean flags, i.e. @code{false} or @code{true}.
                   1705: @item a-addr,a-
                   1706: Cell-aligned address
                   1707: @item c-addr,c-
                   1708: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1709: @item xt
                   1710: Execution token, same size as Cell
                   1711: @item w,x
                   1712: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1713: 16 bits (depending on your platform and Forth system). A cell is more
                   1714: commonly known as machine word, but the term @emph{word} already means
                   1715: something different in Forth.
                   1716: @item d
                   1717: signed double-cell integer
                   1718: @item ud
                   1719: unsigned double-cell integer
                   1720: @item r
                   1721: Float (on the FP stack)
                   1722: @end table
                   1723: 
                   1724: You can find a more complete list in @ref{Notation}.
                   1725: 
1.141     anton    1726: @quotation Assignment
1.48      anton    1727: Write stack-effect comments for all definitions you have written up to
                   1728: now.
1.141     anton    1729: @end quotation
1.48      anton    1730: 
                   1731: 
                   1732: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1733: @section Types
1.66      anton    1734: @cindex types tutorial
1.48      anton    1735: 
                   1736: In Forth the names of the operations are not overloaded; so similar
                   1737: operations on different types need different names; e.g., @code{+} adds
                   1738: integers, and you have to use @code{f+} to add floating-point numbers.
                   1739: The following prefixes are often used for related operations on
                   1740: different types:
                   1741: 
                   1742: @table @code
                   1743: @item (none)
                   1744: signed integer
                   1745: @item u
                   1746: unsigned integer
                   1747: @item c
                   1748: character
                   1749: @item d
                   1750: signed double-cell integer
                   1751: @item ud, du
                   1752: unsigned double-cell integer
                   1753: @item 2
                   1754: two cells (not-necessarily double-cell numbers)
                   1755: @item m, um
                   1756: mixed single-cell and double-cell operations
                   1757: @item f
                   1758: floating-point (note that in stack comments @samp{f} represents flags,
1.210     anton    1759: and @samp{r} represents FP numbers; also, you need to include the
                   1760: exponent part in literal FP numbers, @pxref{Floating Point Tutorial}).
1.48      anton    1761: @end table
                   1762: 
                   1763: If there are no differences between the signed and the unsigned variant
                   1764: (e.g., for @code{+}), there is only the prefix-less variant.
                   1765: 
                   1766: Forth does not perform type checking, neither at compile time, nor at
1.210     anton    1767: run time.  If you use the wrong operation, the data are interpreted
1.48      anton    1768: incorrectly:
                   1769: 
                   1770: @example
                   1771: -1 u.
                   1772: @end example
                   1773: 
                   1774: If you have only experience with type-checked languages until now, and
                   1775: have heard how important type-checking is, don't panic!  In my
                   1776: experience (and that of other Forthers), type errors in Forth code are
                   1777: usually easy to find (once you get used to it), the increased vigilance
                   1778: of the programmer tends to catch some harder errors in addition to most
                   1779: type errors, and you never have to work around the type system, so in
                   1780: most situations the lack of type-checking seems to be a win (projects to
                   1781: add type checking to Forth have not caught on).
                   1782: 
                   1783: 
                   1784: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   1785: @section Factoring
1.66      anton    1786: @cindex factoring tutorial
1.48      anton    1787: 
                   1788: If you try to write longer definitions, you will soon find it hard to
                   1789: keep track of the stack contents.  Therefore, good Forth programmers
                   1790: tend to write only short definitions (e.g., three lines).  The art of
                   1791: finding meaningful short definitions is known as factoring (as in
                   1792: factoring polynomials).
                   1793: 
                   1794: Well-factored programs offer additional advantages: smaller, more
                   1795: general words, are easier to test and debug and can be reused more and
                   1796: better than larger, specialized words.
                   1797: 
                   1798: So, if you run into difficulties with stack management, when writing
                   1799: code, try to define meaningful factors for the word, and define the word
                   1800: in terms of those.  Even if a factor contains only two words, it is
                   1801: often helpful.
                   1802: 
1.65      anton    1803: Good factoring is not easy, and it takes some practice to get the knack
                   1804: for it; but even experienced Forth programmers often don't find the
                   1805: right solution right away, but only when rewriting the program.  So, if
                   1806: you don't come up with a good solution immediately, keep trying, don't
                   1807: despair.
1.48      anton    1808: 
                   1809: @c example !!
                   1810: 
                   1811: 
                   1812: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   1813: @section Designing the stack effect
1.66      anton    1814: @cindex Stack effect design, tutorial
                   1815: @cindex design of stack effects, tutorial
1.48      anton    1816: 
                   1817: In other languages you can use an arbitrary order of parameters for a
1.65      anton    1818: function; and since there is only one result, you don't have to deal with
1.48      anton    1819: the order of results, either.
                   1820: 
1.117     anton    1821: In Forth (and other stack-based languages, e.g., PostScript) the
1.48      anton    1822: parameter and result order of a definition is important and should be
                   1823: designed well.  The general guideline is to design the stack effect such
                   1824: that the word is simple to use in most cases, even if that complicates
                   1825: the implementation of the word.  Some concrete rules are:
                   1826: 
                   1827: @itemize @bullet
                   1828: 
                   1829: @item
                   1830: Words consume all of their parameters (e.g., @code{.}).
                   1831: 
                   1832: @item
                   1833: If there is a convention on the order of parameters (e.g., from
                   1834: mathematics or another programming language), stick with it (e.g.,
                   1835: @code{-}).
                   1836: 
                   1837: @item
                   1838: If one parameter usually requires only a short computation (e.g., it is
                   1839: a constant), pass it on the top of the stack.  Conversely, parameters
                   1840: that usually require a long sequence of code to compute should be passed
                   1841: as the bottom (i.e., first) parameter.  This makes the code easier to
1.171     anton    1842: read, because the reader does not need to keep track of the bottom item
1.48      anton    1843: through a long sequence of code (or, alternatively, through stack
1.49      anton    1844: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    1845: address on top of the stack because it is usually simpler to compute
                   1846: than the stored value (often the address is just a variable).
                   1847: 
                   1848: @item
                   1849: Similarly, results that are usually consumed quickly should be returned
                   1850: on the top of stack, whereas a result that is often used in long
                   1851: computations should be passed as bottom result.  E.g., the file words
                   1852: like @code{open-file} return the error code on the top of stack, because
                   1853: it is usually consumed quickly by @code{throw}; moreover, the error code
                   1854: has to be checked before doing anything with the other results.
                   1855: 
                   1856: @end itemize
                   1857: 
                   1858: These rules are just general guidelines, don't lose sight of the overall
                   1859: goal to make the words easy to use.  E.g., if the convention rule
                   1860: conflicts with the computation-length rule, you might decide in favour
                   1861: of the convention if the word will be used rarely, and in favour of the
                   1862: computation-length rule if the word will be used frequently (because
                   1863: with frequent use the cost of breaking the computation-length rule would
                   1864: be quite high, and frequent use makes it easier to remember an
                   1865: unconventional order).
                   1866: 
                   1867: @c example !! structure package
                   1868: 
1.65      anton    1869: 
1.48      anton    1870: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   1871: @section Local Variables
1.66      anton    1872: @cindex local variables, tutorial
1.48      anton    1873: 
                   1874: You can define local variables (@emph{locals}) in a colon definition:
                   1875: 
                   1876: @example
                   1877: : swap @{ a b -- b a @}
                   1878:   b a ;
                   1879: 1 2 swap .s 2drop
                   1880: @end example
                   1881: 
                   1882: (If your Forth system does not support this syntax, include
1.187     anton    1883: @file{compat/anslocal.fs} first).
1.48      anton    1884: 
                   1885: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   1886: takes two cells from the stack, puts the top of stack in @code{b} and
                   1887: the next stack element in @code{a}.  @code{--} starts a comment ending
                   1888: with @code{@}}.  After the locals definition, using the name of the
                   1889: local will push its value on the stack.  You can leave the comment
                   1890: part (@code{-- b a}) away:
                   1891: 
                   1892: @example
                   1893: : swap ( x1 x2 -- x2 x1 )
                   1894:   @{ a b @} b a ;
                   1895: @end example
                   1896: 
                   1897: In Gforth you can have several locals definitions, anywhere in a colon
                   1898: definition; in contrast, in a standard program you can have only one
                   1899: locals definition per colon definition, and that locals definition must
1.163     anton    1900: be outside any control structure.
1.48      anton    1901: 
                   1902: With locals you can write slightly longer definitions without running
                   1903: into stack trouble.  However, I recommend trying to write colon
                   1904: definitions without locals for exercise purposes to help you gain the
                   1905: essential factoring skills.
                   1906: 
1.141     anton    1907: @quotation Assignment
1.48      anton    1908: Rewrite your definitions until now with locals
1.141     anton    1909: @end quotation
1.48      anton    1910: 
1.66      anton    1911: Reference: @ref{Locals}.
                   1912: 
1.48      anton    1913: 
                   1914: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   1915: @section Conditional execution
1.66      anton    1916: @cindex conditionals, tutorial
                   1917: @cindex if, tutorial
1.48      anton    1918: 
                   1919: In Forth you can use control structures only inside colon definitions.
                   1920: An @code{if}-structure looks like this:
                   1921: 
                   1922: @example
                   1923: : abs ( n1 -- +n2 )
                   1924:     dup 0 < if
                   1925:         negate
                   1926:     endif ;
                   1927: 5 abs .
                   1928: -5 abs .
                   1929: @end example
                   1930: 
                   1931: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   1932: the following code is performed, otherwise execution continues after the
1.51      pazsan   1933: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.171     anton    1934: elements and produces a flag:
1.48      anton    1935: 
                   1936: @example
                   1937: 1 2 < .
                   1938: 2 1 < .
                   1939: 1 1 < .
                   1940: @end example
                   1941: 
                   1942: Actually the standard name for @code{endif} is @code{then}.  This
                   1943: tutorial presents the examples using @code{endif}, because this is often
                   1944: less confusing for people familiar with other programming languages
                   1945: where @code{then} has a different meaning.  If your system does not have
                   1946: @code{endif}, define it with
                   1947: 
                   1948: @example
                   1949: : endif postpone then ; immediate
                   1950: @end example
                   1951: 
                   1952: You can optionally use an @code{else}-part:
                   1953: 
                   1954: @example
                   1955: : min ( n1 n2 -- n )
                   1956:   2dup < if
                   1957:     drop
                   1958:   else
                   1959:     nip
                   1960:   endif ;
                   1961: 2 3 min .
                   1962: 3 2 min .
                   1963: @end example
                   1964: 
1.141     anton    1965: @quotation Assignment
1.48      anton    1966: Write @code{min} without @code{else}-part (hint: what's the definition
                   1967: of @code{nip}?).
1.141     anton    1968: @end quotation
1.48      anton    1969: 
1.66      anton    1970: Reference: @ref{Selection}.
                   1971: 
1.48      anton    1972: 
                   1973: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   1974: @section Flags and Comparisons
1.66      anton    1975: @cindex flags tutorial
                   1976: @cindex comparison tutorial
1.48      anton    1977: 
                   1978: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   1979: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   1980: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   1981: treated as true flag.
                   1982: 
                   1983: @example
                   1984: false .
                   1985: true .
                   1986: true hex u. decimal
                   1987: @end example
                   1988: 
                   1989: Comparison words produce canonical flags:
                   1990: 
                   1991: @example
                   1992: 1 1 = .
                   1993: 1 0= .
                   1994: 0 1 < .
                   1995: 0 0 < .
                   1996: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   1997: -1 1 < .
                   1998: @end example
                   1999: 
1.66      anton    2000: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
                   2001: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
                   2002: these combinations are standard (for details see the standard,
                   2003: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48      anton    2004: 
1.171     anton    2005: You can use @code{and or xor invert} as operations on canonical flags.
                   2006: Actually they are bitwise operations:
1.48      anton    2007: 
                   2008: @example
                   2009: 1 2 and .
                   2010: 1 2 or .
                   2011: 1 3 xor .
                   2012: 1 invert .
                   2013: @end example
                   2014: 
                   2015: You can convert a zero/non-zero flag into a canonical flag with
                   2016: @code{0<>} (and complement it on the way with @code{0=}).
                   2017: 
                   2018: @example
                   2019: 1 0= .
                   2020: 1 0<> .
                   2021: @end example
                   2022: 
1.65      anton    2023: You can use the all-bits-set feature of canonical flags and the bitwise
1.48      anton    2024: operation of the Boolean operations to avoid @code{if}s:
                   2025: 
                   2026: @example
                   2027: : foo ( n1 -- n2 )
                   2028:   0= if
                   2029:     14
                   2030:   else
                   2031:     0
                   2032:   endif ;
                   2033: 0 foo .
                   2034: 1 foo .
                   2035: 
                   2036: : foo ( n1 -- n2 )
                   2037:   0= 14 and ;
                   2038: 0 foo .
                   2039: 1 foo .
                   2040: @end example
                   2041: 
1.141     anton    2042: @quotation Assignment
1.48      anton    2043: Write @code{min} without @code{if}.
1.141     anton    2044: @end quotation
1.48      anton    2045: 
1.66      anton    2046: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
                   2047: @ref{Bitwise operations}.
                   2048: 
1.48      anton    2049: 
                   2050: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   2051: @section General Loops
1.66      anton    2052: @cindex loops, indefinite, tutorial
1.48      anton    2053: 
                   2054: The endless loop is the most simple one:
                   2055: 
                   2056: @example
                   2057: : endless ( -- )
                   2058:   0 begin
                   2059:     dup . 1+
                   2060:   again ;
                   2061: endless
                   2062: @end example
                   2063: 
                   2064: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   2065: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   2066: 
                   2067: A loop with one exit at any place looks like this:
                   2068: 
                   2069: @example
                   2070: : log2 ( +n1 -- n2 )
                   2071: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2072:   assert( dup 0> )
                   2073:   2/ 0 begin
                   2074:     over 0> while
                   2075:       1+ swap 2/ swap
                   2076:   repeat
                   2077:   nip ;
                   2078: 7 log2 .
                   2079: 8 log2 .
                   2080: @end example
                   2081: 
                   2082: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   2083: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    2084: continues behind the @code{while}.  @code{Repeat} jumps back to
                   2085: @code{begin}, just like @code{again}.
                   2086: 
1.211     anton    2087: In Forth there are a number of combinations/abbreviations, like
                   2088: @code{1+}.  However, @code{2/} is not one of them; it shifts its
                   2089: argument right by one bit (arithmetic shift right), and viewed as
                   2090: division that always rounds towards negative infinity (floored
                   2091: division).  In contrast, @code{/} rounds towards zero on some systems
                   2092: (not on default installations of gforth (>=0.7.0), however).
1.48      anton    2093: 
                   2094: @example
1.211     anton    2095: -5 2 / . \ -2 or -3
                   2096: -5 2/ .  \ -3
1.48      anton    2097: @end example
                   2098: 
                   2099: @code{assert(} is no standard word, but you can get it on systems other
1.198     anton    2100: than Gforth by including @file{compat/assert.fs}.  You can see what it
1.48      anton    2101: does by trying
                   2102: 
                   2103: @example
                   2104: 0 log2 .
                   2105: @end example
                   2106: 
                   2107: Here's a loop with an exit at the end:
                   2108: 
                   2109: @example
                   2110: : log2 ( +n1 -- n2 )
                   2111: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2112:   assert( dup 0 > )
                   2113:   -1 begin
                   2114:     1+ swap 2/ swap
                   2115:     over 0 <=
                   2116:   until
                   2117:   nip ;
                   2118: @end example
                   2119: 
1.235     anton    2120: @code{Until} consumes a flag; if it is zero, execution continues at
1.48      anton    2121: the @code{begin}, otherwise after the @code{until}.
                   2122: 
1.141     anton    2123: @quotation Assignment
1.48      anton    2124: Write a definition for computing the greatest common divisor.
1.141     anton    2125: @end quotation
1.48      anton    2126: 
1.66      anton    2127: Reference: @ref{Simple Loops}.
                   2128: 
1.48      anton    2129: 
                   2130: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   2131: @section Counted loops
1.66      anton    2132: @cindex loops, counted, tutorial
1.48      anton    2133: 
                   2134: @example
                   2135: : ^ ( n1 u -- n )
1.171     anton    2136: \ n = the uth power of n1
1.48      anton    2137:   1 swap 0 u+do
                   2138:     over *
                   2139:   loop
                   2140:   nip ;
                   2141: 3 2 ^ .
                   2142: 4 3 ^ .
                   2143: @end example
                   2144: 
                   2145: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   2146: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   2147: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2148: times (or not at all, if @code{u3-u4<0}).
                   2149: 
                   2150: You can see the stack effect design rules at work in the stack effect of
                   2151: the loop start words: Since the start value of the loop is more
                   2152: frequently constant than the end value, the start value is passed on
                   2153: the top-of-stack.
                   2154: 
                   2155: You can access the counter of a counted loop with @code{i}:
                   2156: 
                   2157: @example
                   2158: : fac ( u -- u! )
                   2159:   1 swap 1+ 1 u+do
                   2160:     i *
                   2161:   loop ;
                   2162: 5 fac .
                   2163: 7 fac .
                   2164: @end example
                   2165: 
                   2166: There is also @code{+do}, which expects signed numbers (important for
                   2167: deciding whether to enter the loop).
                   2168: 
1.141     anton    2169: @quotation Assignment
1.48      anton    2170: Write a definition for computing the nth Fibonacci number.
1.141     anton    2171: @end quotation
1.48      anton    2172: 
1.65      anton    2173: You can also use increments other than 1:
                   2174: 
                   2175: @example
                   2176: : up2 ( n1 n2 -- )
                   2177:   +do
                   2178:     i .
                   2179:   2 +loop ;
                   2180: 10 0 up2
                   2181: 
                   2182: : down2 ( n1 n2 -- )
                   2183:   -do
                   2184:     i .
                   2185:   2 -loop ;
                   2186: 0 10 down2
                   2187: @end example
1.48      anton    2188: 
1.66      anton    2189: Reference: @ref{Counted Loops}.
                   2190: 
1.48      anton    2191: 
                   2192: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2193: @section Recursion
1.66      anton    2194: @cindex recursion tutorial
1.48      anton    2195: 
                   2196: Usually the name of a definition is not visible in the definition; but
                   2197: earlier definitions are usually visible:
                   2198: 
                   2199: @example
1.166     anton    2200: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48      anton    2201: : / ( n1 n2 -- n )
                   2202:   dup 0= if
                   2203:     -10 throw \ report division by zero
                   2204:   endif
                   2205:   /           \ old version
                   2206: ;
                   2207: 1 0 /
                   2208: @end example
                   2209: 
                   2210: For recursive definitions you can use @code{recursive} (non-standard) or
                   2211: @code{recurse}:
                   2212: 
                   2213: @example
                   2214: : fac1 ( n -- n! ) recursive
                   2215:  dup 0> if
                   2216:    dup 1- fac1 *
                   2217:  else
                   2218:    drop 1
                   2219:  endif ;
                   2220: 7 fac1 .
                   2221: 
                   2222: : fac2 ( n -- n! )
                   2223:  dup 0> if
                   2224:    dup 1- recurse *
                   2225:  else
                   2226:    drop 1
                   2227:  endif ;
                   2228: 8 fac2 .
                   2229: @end example
                   2230: 
1.141     anton    2231: @quotation Assignment
1.48      anton    2232: Write a recursive definition for computing the nth Fibonacci number.
1.141     anton    2233: @end quotation
1.48      anton    2234: 
1.66      anton    2235: Reference (including indirect recursion): @xref{Calls and returns}.
                   2236: 
1.48      anton    2237: 
                   2238: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2239: @section Leaving definitions or loops
1.66      anton    2240: @cindex leaving definitions, tutorial
                   2241: @cindex leaving loops, tutorial
1.48      anton    2242: 
                   2243: @code{EXIT} exits the current definition right away.  For every counted
                   2244: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2245: before the @code{EXIT}:
                   2246: 
                   2247: @c !! real examples
                   2248: @example
                   2249: : ...
                   2250:  ... u+do
                   2251:    ... if
                   2252:      ... unloop exit
                   2253:    endif
                   2254:    ...
                   2255:  loop
                   2256:  ... ;
                   2257: @end example
                   2258: 
                   2259: @code{LEAVE} leaves the innermost counted loop right away:
                   2260: 
                   2261: @example
                   2262: : ...
                   2263:  ... u+do
                   2264:    ... if
                   2265:      ... leave
                   2266:    endif
                   2267:    ...
                   2268:  loop
                   2269:  ... ;
                   2270: @end example
                   2271: 
1.65      anton    2272: @c !! example
1.48      anton    2273: 
1.66      anton    2274: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
                   2275: 
                   2276: 
1.48      anton    2277: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2278: @section Return Stack
1.66      anton    2279: @cindex return stack tutorial
1.48      anton    2280: 
                   2281: In addition to the data stack Forth also has a second stack, the return
                   2282: stack; most Forth systems store the return addresses of procedure calls
                   2283: there (thus its name).  Programmers can also use this stack:
                   2284: 
                   2285: @example
                   2286: : foo ( n1 n2 -- )
                   2287:  .s
                   2288:  >r .s
1.50      anton    2289:  r@@ .
1.48      anton    2290:  >r .s
1.50      anton    2291:  r@@ .
1.48      anton    2292:  r> .
1.50      anton    2293:  r@@ .
1.48      anton    2294:  r> . ;
                   2295: 1 2 foo
                   2296: @end example
                   2297: 
                   2298: @code{>r} takes an element from the data stack and pushes it onto the
                   2299: return stack; conversely, @code{r>} moves an elementm from the return to
                   2300: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148     anton    2301: on the data stack.
1.48      anton    2302: 
                   2303: Forth programmers usually use the return stack for storing data
                   2304: temporarily, if using the data stack alone would be too complex, and
                   2305: factoring and locals are not an option:
                   2306: 
                   2307: @example
                   2308: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2309:  rot >r rot r> ;
                   2310: @end example
                   2311: 
                   2312: The return address of the definition and the loop control parameters of
                   2313: counted loops usually reside on the return stack, so you have to take
                   2314: all items, that you have pushed on the return stack in a colon
                   2315: definition or counted loop, from the return stack before the definition
                   2316: or loop ends.  You cannot access items that you pushed on the return
                   2317: stack outside some definition or loop within the definition of loop.
                   2318: 
                   2319: If you miscount the return stack items, this usually ends in a crash:
                   2320: 
                   2321: @example
                   2322: : crash ( n -- )
                   2323:   >r ;
                   2324: 5 crash
                   2325: @end example
                   2326: 
                   2327: You cannot mix using locals and using the return stack (according to the
                   2328: standard; Gforth has no problem).  However, they solve the same
                   2329: problems, so this shouldn't be an issue.
                   2330: 
1.141     anton    2331: @quotation Assignment
1.48      anton    2332: Can you rewrite any of the definitions you wrote until now in a better
                   2333: way using the return stack?
1.141     anton    2334: @end quotation
1.48      anton    2335: 
1.66      anton    2336: Reference: @ref{Return stack}.
                   2337: 
1.48      anton    2338: 
                   2339: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2340: @section Memory
1.66      anton    2341: @cindex memory access/allocation tutorial
1.48      anton    2342: 
                   2343: You can create a global variable @code{v} with
                   2344: 
                   2345: @example
                   2346: variable v ( -- addr )
                   2347: @end example
                   2348: 
                   2349: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2350: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2351: values into this cell and @code{@@} (fetch) to load the value from the
                   2352: stack into memory:
                   2353: 
                   2354: @example
                   2355: v .
                   2356: 5 v ! .s
1.50      anton    2357: v @@ .
1.48      anton    2358: @end example
                   2359: 
1.65      anton    2360: You can see a raw dump of memory with @code{dump}:
                   2361: 
                   2362: @example
                   2363: v 1 cells .s dump
                   2364: @end example
                   2365: 
                   2366: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
                   2367: generally, address units (aus)) that @code{n1 cells} occupy.  You can
                   2368: also reserve more memory:
1.48      anton    2369: 
                   2370: @example
                   2371: create v2 20 cells allot
1.65      anton    2372: v2 20 cells dump
1.48      anton    2373: @end example
                   2374: 
1.212     anton    2375: creates a variable-like word @code{v2} and reserves 20 uninitialized
                   2376: cells; the address pushed by @code{v2} points to the start of these 20
                   2377: cells (@pxref{CREATE}).  You can use address arithmetic to access
                   2378: these cells:
1.48      anton    2379: 
                   2380: @example
                   2381: 3 v2 5 cells + !
1.65      anton    2382: v2 20 cells dump
1.48      anton    2383: @end example
                   2384: 
                   2385: You can reserve and initialize memory with @code{,}:
                   2386: 
                   2387: @example
                   2388: create v3
                   2389:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2390: v3 @@ .
                   2391: v3 cell+ @@ .
                   2392: v3 2 cells + @@ .
1.65      anton    2393: v3 5 cells dump
1.48      anton    2394: @end example
                   2395: 
1.141     anton    2396: @quotation Assignment
1.48      anton    2397: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2398: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2399: one at @code{addr cell+} etc.
1.141     anton    2400: @end quotation
1.48      anton    2401: 
1.214     anton    2402: The difference between @code{variable} and @code{create} is that
                   2403: @code{variable} allots a cell, and that you cannot allot additional
                   2404: memory to a variable in standard Forth.
                   2405: 
1.48      anton    2406: You can also reserve memory without creating a new word:
                   2407: 
                   2408: @example
1.60      anton    2409: here 10 cells allot .
                   2410: here .
1.48      anton    2411: @end example
                   2412: 
1.211     anton    2413: The first @code{here} pushes the start address of the memory area, the
                   2414: second @code{here} the address after the dictionary area.  You should
                   2415: store the start address somewhere, or you will have a hard time
                   2416: finding the memory area again.
1.48      anton    2417: 
                   2418: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2419: the system's data structures for words etc. on Gforth and most other
                   2420: Forth systems.  It is managed like a stack: You can free the memory that
                   2421: you have just @code{allot}ed with
                   2422: 
                   2423: @example
                   2424: -10 cells allot
1.60      anton    2425: here .
1.48      anton    2426: @end example
                   2427: 
                   2428: Note that you cannot do this if you have created a new word in the
                   2429: meantime (because then your @code{allot}ed memory is no longer on the
                   2430: top of the dictionary ``stack'').
                   2431: 
                   2432: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2433: freeing memory in any order:
                   2434: 
                   2435: @example
                   2436: 10 cells allocate throw .s
                   2437: 20 cells allocate throw .s
                   2438: swap
                   2439: free throw
                   2440: free throw
                   2441: @end example
                   2442: 
                   2443: The @code{throw}s deal with errors (e.g., out of memory).
                   2444: 
1.65      anton    2445: And there is also a
                   2446: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   2447: garbage collector}, which eliminates the need to @code{free} memory
                   2448: explicitly.
1.48      anton    2449: 
1.66      anton    2450: Reference: @ref{Memory}.
                   2451: 
1.48      anton    2452: 
                   2453: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2454: @section Characters and Strings
1.66      anton    2455: @cindex strings tutorial
                   2456: @cindex characters tutorial
1.48      anton    2457: 
                   2458: On the stack characters take up a cell, like numbers.  In memory they
                   2459: have their own size (one 8-bit byte on most systems), and therefore
                   2460: require their own words for memory access:
                   2461: 
                   2462: @example
                   2463: create v4 
                   2464:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2465: v4 4 chars + c@@ .
1.65      anton    2466: v4 5 chars dump
1.48      anton    2467: @end example
                   2468: 
                   2469: The preferred representation of strings on the stack is @code{addr
                   2470: u-count}, where @code{addr} is the address of the first character and
                   2471: @code{u-count} is the number of characters in the string.
                   2472: 
                   2473: @example
                   2474: v4 5 type
                   2475: @end example
                   2476: 
                   2477: You get a string constant with
                   2478: 
                   2479: @example
                   2480: s" hello, world" .s
                   2481: type
                   2482: @end example
                   2483: 
                   2484: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2485: is a normal Forth word and must be delimited with white space (try what
                   2486: happens when you remove the space).
                   2487: 
                   2488: However, this interpretive use of @code{s"} is quite restricted: the
                   2489: string exists only until the next call of @code{s"} (some Forth systems
                   2490: keep more than one of these strings, but usually they still have a
1.62      crook    2491: limited lifetime).
1.48      anton    2492: 
                   2493: @example
                   2494: s" hello," s" world" .s
                   2495: type
                   2496: type
                   2497: @end example
                   2498: 
1.62      crook    2499: You can also use @code{s"} in a definition, and the resulting
                   2500: strings then live forever (well, for as long as the definition):
1.48      anton    2501: 
                   2502: @example
                   2503: : foo s" hello," s" world" ;
                   2504: foo .s
                   2505: type
                   2506: type
                   2507: @end example
                   2508: 
1.141     anton    2509: @quotation Assignment
1.48      anton    2510: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2511: Implement @code{type ( addr u -- )}.
1.141     anton    2512: @end quotation
1.48      anton    2513: 
1.66      anton    2514: Reference: @ref{Memory Blocks}.
                   2515: 
                   2516: 
1.190     anton    2517: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
1.48      anton    2518: @section Alignment
1.66      anton    2519: @cindex alignment tutorial
                   2520: @cindex memory alignment tutorial
1.48      anton    2521: 
                   2522: On many processors cells have to be aligned in memory, if you want to
                   2523: access them with @code{@@} and @code{!} (and even if the processor does
1.62      crook    2524: not require alignment, access to aligned cells is faster).
1.48      anton    2525: 
                   2526: @code{Create} aligns @code{here} (i.e., the place where the next
                   2527: allocation will occur, and that the @code{create}d word points to).
                   2528: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2529: address.  Adding a number of @code{cells} to an aligned address produces
                   2530: another aligned address.
                   2531: 
                   2532: However, address arithmetic involving @code{char+} and @code{chars} can
                   2533: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2534: a-addr )} produces the next aligned address:
                   2535: 
                   2536: @example
1.50      anton    2537: v3 char+ aligned .s @@ .
                   2538: v3 char+ .s @@ .
1.48      anton    2539: @end example
                   2540: 
                   2541: Similarly, @code{align} advances @code{here} to the next aligned
                   2542: address:
                   2543: 
                   2544: @example
                   2545: create v5 97 c,
                   2546: here .
                   2547: align here .
                   2548: 1000 ,
                   2549: @end example
                   2550: 
                   2551: Note that you should use aligned addresses even if your processor does
                   2552: not require them, if you want your program to be portable.
                   2553: 
1.66      anton    2554: Reference: @ref{Address arithmetic}.
                   2555: 
1.190     anton    2556: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
                   2557: @section Floating Point
                   2558: @cindex floating point tutorial
                   2559: @cindex FP tutorial
                   2560: 
                   2561: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
                   2562: might expect, but there are a few things worth noting:
                   2563: 
                   2564: The first point is not specific to Forth, but so important and yet not
                   2565: universally known that I mention it here: FP numbers are not reals.
                   2566: Many properties (e.g., arithmetic laws) that reals have and that one
                   2567: expects of all kinds of numbers do not hold for FP numbers.  If you
                   2568: want to use FP computations, you should learn about their problems and
                   2569: how to avoid them; a good starting point is @cite{David Goldberg,
                   2570: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
                   2571: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
                   2572: Computing Surveys 23(1):5@minus{}48, March 1991}.
                   2573: 
                   2574: In Forth source code literal FP numbers need an exponent, e.g.,
1.210     anton    2575: @code{1e0}; this can also be written shorter as @code{1e}, longer as
                   2576: @code{+1.0e+0}, and many variations in between.  The reason for this is
                   2577: that, for historical reasons, Forth interprets a decimal point alone
                   2578: (e.g., @code{1.}) as indicating a double-cell integer.  Examples:
                   2579: 
                   2580: @example
                   2581: 2e 2e f+ f.
                   2582: @end example
                   2583: 
                   2584: Another requirement for literal FP numbers is that the current base is
1.190     anton    2585: decimal; with a hex base @code{1e} is interpreted as an integer.
                   2586: 
                   2587: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
                   2588: ANS Forth system may implement the FP stack on the data stack, but
                   2589: virtually all systems implement a separate FP stack; and programming
                   2590: in a way that accommodates all models is so cumbersome that nobody
                   2591: does it.}  One advantage of this model is that cells are not in the
                   2592: way when accessing FP values, and vice versa.  Forth has a set of
                   2593: words for manipulating the FP stack: @code{fdup fswap fdrop fover
                   2594: frot} and (non-standard) @code{fnip ftuck fpick}.
                   2595: 
                   2596: FP arithmetic words are prefixed with @code{F}.  There is the usual
                   2597: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
                   2598: other functions, e.g., @code{fsqrt fsin fln fmin}.  One word that you
                   2599: might expect is @code{f=}; but @code{f=} is non-standard, because FP
                   2600: computation results are usually inaccurate, so exact comparison is
                   2601: usually a mistake, and one should use approximate comparison.
                   2602: Unfortunately, @code{f~}, the standard word for that purpose, is not
                   2603: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
                   2604: well.
                   2605: 
                   2606: And of course there are words for accessing FP numbers in memory
                   2607: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
                   2608: faligned}).  There are also variants of these words with an @code{sf}
                   2609: and @code{df} prefix for accessing IEEE format single-precision and
                   2610: double-precision numbers in memory; their main purpose is for
                   2611: accessing external FP data (e.g., that has been read from or will be
                   2612: written to a file).
                   2613: 
                   2614: Here is an example of a dot-product word and its use:
                   2615: 
                   2616: @example
                   2617: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   2618:   >r swap 2swap swap 0e r> 0 ?DO
                   2619:     dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
                   2620:   LOOP
                   2621:   2drop 2drop ;
1.48      anton    2622: 
1.190     anton    2623: create v 1.23e f, 4.56e f, 7.89e f,
                   2624: 
                   2625: v 1 floats  v 1 floats  3  v* f.
                   2626: @end example
                   2627: 
                   2628: @quotation Assignment
                   2629: Write a program to solve a quadratic equation.  Then read @cite{Henry
                   2630: G. Baker,
                   2631: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
                   2632: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
                   2633: 33(1):30@minus{}39, January 1998}, and see if you can improve your
                   2634: program.  Finally, find a test case where the original and the
                   2635: improved version produce different results.
                   2636: @end quotation
                   2637: 
                   2638: Reference: @ref{Floating Point}; @ref{Floating point stack};
                   2639: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
                   2640: arithmetic}.
                   2641: 
                   2642: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
1.84      pazsan   2643: @section Files
                   2644: @cindex files tutorial
                   2645: 
                   2646: This section gives a short introduction into how to use files inside
                   2647: Forth. It's broken up into five easy steps:
                   2648: 
                   2649: @enumerate 1
                   2650: @item Opened an ASCII text file for input
                   2651: @item Opened a file for output
                   2652: @item Read input file until string matched (or some other condition matched)
                   2653: @item Wrote some lines from input ( modified or not) to output
                   2654: @item Closed the files.
                   2655: @end enumerate
                   2656: 
1.153     anton    2657: Reference: @ref{General files}.
                   2658: 
1.84      pazsan   2659: @subsection Open file for input
                   2660: 
                   2661: @example
                   2662: s" foo.in"  r/o open-file throw Value fd-in
                   2663: @end example
                   2664: 
                   2665: @subsection Create file for output
                   2666: 
                   2667: @example
                   2668: s" foo.out" w/o create-file throw Value fd-out
                   2669: @end example
                   2670: 
                   2671: The available file modes are r/o for read-only access, r/w for
                   2672: read-write access, and w/o for write-only access. You could open both
                   2673: files with r/w, too, if you like. All file words return error codes; for
                   2674: most applications, it's best to pass there error codes with @code{throw}
                   2675: to the outer error handler.
                   2676: 
                   2677: If you want words for opening and assigning, define them as follows:
                   2678: 
                   2679: @example
                   2680: 0 Value fd-in
                   2681: 0 Value fd-out
                   2682: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
                   2683: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
                   2684: @end example
                   2685: 
                   2686: Usage example:
                   2687: 
                   2688: @example
                   2689: s" foo.in" open-input
                   2690: s" foo.out" open-output
                   2691: @end example
                   2692: 
                   2693: @subsection Scan file for a particular line
                   2694: 
                   2695: @example
                   2696: 256 Constant max-line
                   2697: Create line-buffer  max-line 2 + allot
                   2698: 
                   2699: : scan-file ( addr u -- )
                   2700:   begin
                   2701:       line-buffer max-line fd-in read-line throw
                   2702:   while
                   2703:          >r 2dup line-buffer r> compare 0=
                   2704:      until
                   2705:   else
                   2706:      drop
                   2707:   then
                   2708:   2drop ;
                   2709: @end example
                   2710: 
                   2711: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94      anton    2712: the buffer at addr, and returns the number of bytes read, a flag that is
                   2713: false when the end of file is reached, and an error code.
1.84      pazsan   2714: 
                   2715: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
                   2716: returns zero if both strings are equal. It returns a positive number if
                   2717: the first string is lexically greater, a negative if the second string
                   2718: is lexically greater.
                   2719: 
                   2720: We haven't seen this loop here; it has two exits. Since the @code{while}
                   2721: exits with the number of bytes read on the stack, we have to clean up
                   2722: that separately; that's after the @code{else}.
                   2723: 
                   2724: Usage example:
                   2725: 
                   2726: @example
                   2727: s" The text I search is here" scan-file
                   2728: @end example
                   2729: 
                   2730: @subsection Copy input to output
                   2731: 
                   2732: @example
                   2733: : copy-file ( -- )
                   2734:   begin
                   2735:       line-buffer max-line fd-in read-line throw
                   2736:   while
1.194     anton    2737:       line-buffer swap fd-out write-line throw
1.229     anton    2738:   repeat 
                   2739:   drop ;
1.84      pazsan   2740: @end example
1.194     anton    2741: @c !! does not handle long lines, no newline at end of file
1.84      pazsan   2742: 
                   2743: @subsection Close files
                   2744: 
                   2745: @example
                   2746: fd-in close-file throw
                   2747: fd-out close-file throw
                   2748: @end example
                   2749: 
                   2750: Likewise, you can put that into definitions, too:
                   2751: 
                   2752: @example
                   2753: : close-input ( -- )  fd-in close-file throw ;
                   2754: : close-output ( -- )  fd-out close-file throw ;
                   2755: @end example
                   2756: 
1.141     anton    2757: @quotation Assignment
1.84      pazsan   2758: How could you modify @code{copy-file} so that it copies until a second line is
                   2759: matched? Can you write a program that extracts a section of a text file,
                   2760: given the line that starts and the line that terminates that section?
1.141     anton    2761: @end quotation
1.84      pazsan   2762: 
                   2763: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48      anton    2764: @section Interpretation and Compilation Semantics and Immediacy
1.66      anton    2765: @cindex semantics tutorial
                   2766: @cindex interpretation semantics tutorial
                   2767: @cindex compilation semantics tutorial
                   2768: @cindex immediate, tutorial
1.48      anton    2769: 
                   2770: When a word is compiled, it behaves differently from being interpreted.
                   2771: E.g., consider @code{+}:
                   2772: 
                   2773: @example
                   2774: 1 2 + .
                   2775: : foo + ;
                   2776: @end example
                   2777: 
                   2778: These two behaviours are known as compilation and interpretation
                   2779: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2780: is to append the interpretation semantics to the currently defined word
                   2781: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2782: later, the interpretation semantics of @code{+} (i.e., adding two
                   2783: numbers) will be performed.
                   2784: 
                   2785: However, there are words with non-default compilation semantics, e.g.,
                   2786: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2787: change the compilation semantics of the last defined word to be equal to
                   2788: the interpretation semantics:
                   2789: 
                   2790: @example
                   2791: : [FOO] ( -- )
                   2792:  5 . ; immediate
                   2793: 
                   2794: [FOO]
                   2795: : bar ( -- )
                   2796:   [FOO] ;
                   2797: bar
                   2798: see bar
                   2799: @end example
                   2800: 
1.198     anton    2801: Two conventions to mark words with non-default compilation semantics are
1.48      anton    2802: names with brackets (more frequently used) and to write them all in
                   2803: upper case (less frequently used).
                   2804: 
                   2805: In Gforth (and many other systems) you can also remove the
                   2806: interpretation semantics with @code{compile-only} (the compilation
                   2807: semantics is derived from the original interpretation semantics):
                   2808: 
                   2809: @example
                   2810: : flip ( -- )
                   2811:  6 . ; compile-only \ but not immediate
                   2812: flip
                   2813: 
                   2814: : flop ( -- )
                   2815:  flip ;
                   2816: flop
                   2817: @end example
                   2818: 
                   2819: In this example the interpretation semantics of @code{flop} is equal to
                   2820: the original interpretation semantics of @code{flip}.
                   2821: 
                   2822: The text interpreter has two states: in interpret state, it performs the
                   2823: interpretation semantics of words it encounters; in compile state, it
                   2824: performs the compilation semantics of these words.
                   2825: 
                   2826: Among other things, @code{:} switches into compile state, and @code{;}
                   2827: switches back to interpret state.  They contain the factors @code{]}
                   2828: (switch to compile state) and @code{[} (switch to interpret state), that
                   2829: do nothing but switch the state.
                   2830: 
                   2831: @example
                   2832: : xxx ( -- )
                   2833:   [ 5 . ]
                   2834: ;
                   2835: 
                   2836: xxx
                   2837: see xxx
                   2838: @end example
                   2839: 
                   2840: These brackets are also the source of the naming convention mentioned
                   2841: above.
                   2842: 
1.66      anton    2843: Reference: @ref{Interpretation and Compilation Semantics}.
                   2844: 
1.48      anton    2845: 
                   2846: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2847: @section Execution Tokens
1.66      anton    2848: @cindex execution tokens tutorial
                   2849: @cindex XT tutorial
1.48      anton    2850: 
                   2851: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2852: cell representing the interpretation semantics of a word.  You can
                   2853: execute this semantics with @code{execute}:
                   2854: 
                   2855: @example
                   2856: ' + .s
                   2857: 1 2 rot execute .
                   2858: @end example
                   2859: 
                   2860: The XT is similar to a function pointer in C.  However, parameter
                   2861: passing through the stack makes it a little more flexible:
                   2862: 
                   2863: @example
                   2864: : map-array ( ... addr u xt -- ... )
1.50      anton    2865: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2866: \ at addr and containing u elements
1.48      anton    2867:   @{ xt @}
                   2868:   cells over + swap ?do
1.50      anton    2869:     i @@ xt execute
1.48      anton    2870:   1 cells +loop ;
                   2871: 
                   2872: create a 3 , 4 , 2 , -1 , 4 ,
                   2873: a 5 ' . map-array .s
                   2874: 0 a 5 ' + map-array .
                   2875: s" max-n" environment? drop .s
                   2876: a 5 ' min map-array .
                   2877: @end example
                   2878: 
                   2879: You can use map-array with the XTs of words that consume one element
                   2880: more than they produce.  In theory you can also use it with other XTs,
                   2881: but the stack effect then depends on the size of the array, which is
                   2882: hard to understand.
                   2883: 
1.51      pazsan   2884: Since XTs are cell-sized, you can store them in memory and manipulate
                   2885: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2886: word with @code{compile,}:
                   2887: 
                   2888: @example
                   2889: : foo1 ( n1 n2 -- n )
                   2890:    [ ' + compile, ] ;
1.229     anton    2891: see foo1
1.48      anton    2892: @end example
                   2893: 
                   2894: This is non-standard, because @code{compile,} has no compilation
                   2895: semantics in the standard, but it works in good Forth systems.  For the
                   2896: broken ones, use
                   2897: 
                   2898: @example
                   2899: : [compile,] compile, ; immediate
                   2900: 
                   2901: : foo1 ( n1 n2 -- n )
                   2902:    [ ' + ] [compile,] ;
                   2903: see foo
                   2904: @end example
                   2905: 
                   2906: @code{'} is a word with default compilation semantics; it parses the
                   2907: next word when its interpretation semantics are executed, not during
                   2908: compilation:
                   2909: 
                   2910: @example
                   2911: : foo ( -- xt )
                   2912:   ' ;
                   2913: see foo
                   2914: : bar ( ... "word" -- ... )
                   2915:   ' execute ;
                   2916: see bar
1.60      anton    2917: 1 2 bar + .
1.48      anton    2918: @end example
                   2919: 
                   2920: You often want to parse a word during compilation and compile its XT so
                   2921: it will be pushed on the stack at run-time.  @code{[']} does this:
                   2922: 
                   2923: @example
                   2924: : xt-+ ( -- xt )
                   2925:   ['] + ;
                   2926: see xt-+
                   2927: 1 2 xt-+ execute .
                   2928: @end example
                   2929: 
                   2930: Many programmers tend to see @code{'} and the word it parses as one
                   2931: unit, and expect it to behave like @code{[']} when compiled, and are
                   2932: confused by the actual behaviour.  If you are, just remember that the
                   2933: Forth system just takes @code{'} as one unit and has no idea that it is
                   2934: a parsing word (attempts to convenience programmers in this issue have
                   2935: usually resulted in even worse pitfalls, see
1.66      anton    2936: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
                   2937: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48      anton    2938: 
                   2939: Note that the state of the interpreter does not come into play when
1.51      pazsan   2940: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    2941: compile state, it still gives you the interpretation semantics.  And
                   2942: whatever that state is, @code{execute} performs the semantics
1.66      anton    2943: represented by the XT (i.e., for XTs produced with @code{'} the
                   2944: interpretation semantics).
                   2945: 
                   2946: Reference: @ref{Tokens for Words}.
1.48      anton    2947: 
                   2948: 
                   2949: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   2950: @section Exceptions
1.66      anton    2951: @cindex exceptions tutorial
1.48      anton    2952: 
                   2953: @code{throw ( n -- )} causes an exception unless n is zero.
                   2954: 
                   2955: @example
                   2956: 100 throw .s
                   2957: 0 throw .s
                   2958: @end example
                   2959: 
                   2960: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   2961: it catches exceptions and pushes the number of the exception on the
                   2962: stack (or 0, if the xt executed without exception).  If there was an
                   2963: exception, the stacks have the same depth as when entering @code{catch}:
                   2964: 
                   2965: @example
                   2966: .s
                   2967: 3 0 ' / catch .s
                   2968: 3 2 ' / catch .s
                   2969: @end example
                   2970: 
1.141     anton    2971: @quotation Assignment
1.48      anton    2972: Try the same with @code{execute} instead of @code{catch}.
1.141     anton    2973: @end quotation
1.48      anton    2974: 
                   2975: @code{Throw} always jumps to the dynamically next enclosing
                   2976: @code{catch}, even if it has to leave several call levels to achieve
                   2977: this:
                   2978: 
                   2979: @example
                   2980: : foo 100 throw ;
                   2981: : foo1 foo ." after foo" ;
1.51      pazsan   2982: : bar ['] foo1 catch ;
1.60      anton    2983: bar .
1.48      anton    2984: @end example
                   2985: 
                   2986: It is often important to restore a value upon leaving a definition, even
                   2987: if the definition is left through an exception.  You can ensure this
                   2988: like this:
                   2989: 
                   2990: @example
                   2991: : ...
                   2992:    save-x
1.51      pazsan   2993:    ['] word-changing-x catch ( ... n )
1.48      anton    2994:    restore-x
                   2995:    ( ... n ) throw ;
                   2996: @end example
                   2997: 
1.172     anton    2998: However, this is still not safe against, e.g., the user pressing
                   2999: @kbd{Ctrl-C} when execution is between the @code{catch} and
                   3000: @code{restore-x}.
                   3001: 
                   3002: Gforth provides an alternative exception handling syntax that is safe
                   3003: against such cases: @code{try ... restore ... endtry}.  If the code
                   3004: between @code{try} and @code{endtry} has an exception, the stack
                   3005: depths are restored, the exception number is pushed on the stack, and
                   3006: the execution continues right after @code{restore}.
1.48      anton    3007: 
1.172     anton    3008: The safer equivalent to the restoration code above is
1.48      anton    3009: 
                   3010: @example
                   3011: : ...
                   3012:   save-x
                   3013:   try
1.92      anton    3014:     word-changing-x 0
1.172     anton    3015:   restore
                   3016:     restore-x
                   3017:   endtry
1.48      anton    3018:   throw ;
                   3019: @end example
                   3020: 
1.66      anton    3021: Reference: @ref{Exception Handling}.
                   3022: 
1.48      anton    3023: 
                   3024: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   3025: @section Defining Words
1.66      anton    3026: @cindex defining words tutorial
                   3027: @cindex does> tutorial
                   3028: @cindex create...does> tutorial
                   3029: 
                   3030: @c before semantics?
1.48      anton    3031: 
                   3032: @code{:}, @code{create}, and @code{variable} are definition words: They
                   3033: define other words.  @code{Constant} is another definition word:
                   3034: 
                   3035: @example
                   3036: 5 constant foo
                   3037: foo .
                   3038: @end example
                   3039: 
                   3040: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   3041: (floating point) with @code{variable} and @code{constant}.
                   3042: 
                   3043: You can also define your own defining words.  E.g.:
                   3044: 
                   3045: @example
                   3046: : variable ( "name" -- )
                   3047:   create 0 , ;
                   3048: @end example
                   3049: 
                   3050: You can also define defining words that create words that do something
                   3051: other than just producing their address:
                   3052: 
                   3053: @example
                   3054: : constant ( n "name" -- )
                   3055:   create ,
                   3056: does> ( -- n )
1.50      anton    3057:   ( addr ) @@ ;
1.48      anton    3058: 
                   3059: 5 constant foo
                   3060: foo .
                   3061: @end example
                   3062: 
                   3063: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   3064: @code{does>} replaces @code{;}, but it also does something else: It
                   3065: changes the last defined word such that it pushes the address of the
                   3066: body of the word and then performs the code after the @code{does>}
                   3067: whenever it is called.
                   3068: 
                   3069: In the example above, @code{constant} uses @code{,} to store 5 into the
                   3070: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   3071: the body onto the stack, then (in the code after the @code{does>})
                   3072: fetches the 5 from there.
                   3073: 
                   3074: The stack comment near the @code{does>} reflects the stack effect of the
                   3075: defined word, not the stack effect of the code after the @code{does>}
                   3076: (the difference is that the code expects the address of the body that
                   3077: the stack comment does not show).
                   3078: 
                   3079: You can use these definition words to do factoring in cases that involve
                   3080: (other) definition words.  E.g., a field offset is always added to an
                   3081: address.  Instead of defining
                   3082: 
                   3083: @example
                   3084: 2 cells constant offset-field1
                   3085: @end example
                   3086: 
                   3087: and using this like
                   3088: 
                   3089: @example
                   3090: ( addr ) offset-field1 +
                   3091: @end example
                   3092: 
                   3093: you can define a definition word
                   3094: 
                   3095: @example
                   3096: : simple-field ( n "name" -- )
                   3097:   create ,
                   3098: does> ( n1 -- n1+n )
1.50      anton    3099:   ( addr ) @@ + ;
1.48      anton    3100: @end example
1.21      crook    3101: 
1.48      anton    3102: Definition and use of field offsets now look like this:
1.21      crook    3103: 
1.48      anton    3104: @example
                   3105: 2 cells simple-field field1
1.60      anton    3106: create mystruct 4 cells allot
                   3107: mystruct .s field1 .s drop
1.48      anton    3108: @end example
1.21      crook    3109: 
1.48      anton    3110: If you want to do something with the word without performing the code
                   3111: after the @code{does>}, you can access the body of a @code{create}d word
                   3112: with @code{>body ( xt -- addr )}:
1.21      crook    3113: 
1.48      anton    3114: @example
                   3115: : value ( n "name" -- )
                   3116:   create ,
                   3117: does> ( -- n1 )
1.50      anton    3118:   @@ ;
1.48      anton    3119: : to ( n "name" -- )
                   3120:   ' >body ! ;
1.21      crook    3121: 
1.48      anton    3122: 5 value foo
                   3123: foo .
                   3124: 7 to foo
                   3125: foo .
                   3126: @end example
1.21      crook    3127: 
1.141     anton    3128: @quotation Assignment
1.48      anton    3129: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   3130: XT (at the start the XT of @code{abort}), and upon execution
                   3131: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   3132: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   3133: recursion is one application of @code{defer}.
1.141     anton    3134: @end quotation
1.29      crook    3135: 
1.66      anton    3136: Reference: @ref{User-defined Defining Words}.
                   3137: 
                   3138: 
1.48      anton    3139: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   3140: @section Arrays and Records
1.66      anton    3141: @cindex arrays tutorial
                   3142: @cindex records tutorial
                   3143: @cindex structs tutorial
1.29      crook    3144: 
1.48      anton    3145: Forth has no standard words for defining data structures such as arrays
                   3146: and records (structs in C terminology), but you can build them yourself
                   3147: based on address arithmetic.  You can also define words for defining
                   3148: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    3149: 
1.48      anton    3150: One of the first projects a Forth newcomer sets out upon when learning
                   3151: about defining words is an array defining word (possibly for
                   3152: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   3153: learn something from it.  However, don't be disappointed when you later
                   3154: learn that you have little use for these words (inappropriate use would
1.198     anton    3155: be even worse).  I have not found a set of useful array words yet;
1.48      anton    3156: the needs are just too diverse, and named, global arrays (the result of
                   3157: naive use of defining words) are often not flexible enough (e.g.,
1.66      anton    3158: consider how to pass them as parameters).  Another such project is a set
                   3159: of words to help dealing with strings.
1.29      crook    3160: 
1.48      anton    3161: On the other hand, there is a useful set of record words, and it has
                   3162: been defined in @file{compat/struct.fs}; these words are predefined in
                   3163: Gforth.  They are explained in depth elsewhere in this manual (see
                   3164: @pxref{Structures}).  The @code{simple-field} example above is
                   3165: simplified variant of fields in this package.
1.21      crook    3166: 
                   3167: 
1.48      anton    3168: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   3169: @section @code{POSTPONE}
1.66      anton    3170: @cindex postpone tutorial
1.21      crook    3171: 
1.48      anton    3172: You can compile the compilation semantics (instead of compiling the
                   3173: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    3174: 
1.48      anton    3175: @example
                   3176: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   3177:  POSTPONE + ; immediate
1.48      anton    3178: : foo ( n1 n2 -- n )
                   3179:  MY-+ ;
                   3180: 1 2 foo .
                   3181: see foo
                   3182: @end example
1.21      crook    3183: 
1.48      anton    3184: During the definition of @code{foo} the text interpreter performs the
                   3185: compilation semantics of @code{MY-+}, which performs the compilation
                   3186: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   3187: 
                   3188: This example also displays separate stack comments for the compilation
                   3189: semantics and for the stack effect of the compiled code.  For words with
                   3190: default compilation semantics these stack effects are usually not
                   3191: displayed; the stack effect of the compilation semantics is always
                   3192: @code{( -- )} for these words, the stack effect for the compiled code is
                   3193: the stack effect of the interpretation semantics.
                   3194: 
                   3195: Note that the state of the interpreter does not come into play when
                   3196: performing the compilation semantics in this way.  You can also perform
                   3197: it interpretively, e.g.:
                   3198: 
                   3199: @example
                   3200: : foo2 ( n1 n2 -- n )
                   3201:  [ MY-+ ] ;
                   3202: 1 2 foo .
                   3203: see foo
                   3204: @end example
1.21      crook    3205: 
1.48      anton    3206: However, there are some broken Forth systems where this does not always
1.62      crook    3207: work, and therefore this practice was been declared non-standard in
1.48      anton    3208: 1999.
                   3209: @c !! repair.fs
                   3210: 
                   3211: Here is another example for using @code{POSTPONE}:
1.44      crook    3212: 
1.48      anton    3213: @example
                   3214: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   3215:  POSTPONE negate POSTPONE + ; immediate compile-only
                   3216: : bar ( n1 n2 -- n )
                   3217:   MY-- ;
                   3218: 2 1 bar .
                   3219: see bar
                   3220: @end example
1.21      crook    3221: 
1.48      anton    3222: You can define @code{ENDIF} in this way:
1.21      crook    3223: 
1.48      anton    3224: @example
                   3225: : ENDIF ( Compilation: orig -- )
                   3226:   POSTPONE then ; immediate
                   3227: @end example
1.21      crook    3228: 
1.141     anton    3229: @quotation Assignment
1.48      anton    3230: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   3231: @code{2dup}, but compiles @code{over over}.
1.141     anton    3232: @end quotation
1.29      crook    3233: 
1.66      anton    3234: @c !! @xref{Macros} for reference
                   3235: 
                   3236: 
1.48      anton    3237: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3238: @section @code{Literal}
1.66      anton    3239: @cindex literal tutorial
1.29      crook    3240: 
1.48      anton    3241: You cannot @code{POSTPONE} numbers:
1.21      crook    3242: 
1.48      anton    3243: @example
                   3244: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3245: @end example
                   3246: 
1.48      anton    3247: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3248: 
1.48      anton    3249: @example
                   3250: : [FOO] ( compilation: --; run-time: -- n )
                   3251:   500 POSTPONE literal ; immediate
1.29      crook    3252: 
1.60      anton    3253: : flip [FOO] ;
1.48      anton    3254: flip .
                   3255: see flip
                   3256: @end example
1.29      crook    3257: 
1.48      anton    3258: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3259: semantics are executed) and pushes it at run-time (when the code it
                   3260: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3261: number computed at compile time into the current word:
1.29      crook    3262: 
1.48      anton    3263: @example
                   3264: : bar ( -- n )
                   3265:   [ 2 2 + ] literal ;
                   3266: see bar
                   3267: @end example
1.29      crook    3268: 
1.141     anton    3269: @quotation Assignment
1.48      anton    3270: Write @code{]L} which allows writing the example above as @code{: bar (
                   3271: -- n ) [ 2 2 + ]L ;}
1.141     anton    3272: @end quotation
1.48      anton    3273: 
1.66      anton    3274: @c !! @xref{Macros} for reference
                   3275: 
1.48      anton    3276: 
                   3277: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3278: @section Advanced macros
1.66      anton    3279: @cindex macros, advanced tutorial
                   3280: @cindex run-time code generation, tutorial
1.48      anton    3281: 
1.66      anton    3282: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
                   3283: Execution Tokens}.  It frequently performs @code{execute}, a relatively
                   3284: expensive operation in some Forth implementations.  You can use
1.48      anton    3285: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3286: and produce a word that contains the word to be performed directly:
                   3287: 
                   3288: @c use ]] ... [[
                   3289: @example
                   3290: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3291: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3292: \ array beginning at addr and containing u elements
                   3293:   @{ xt @}
                   3294:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3295:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3296:   1 cells POSTPONE literal POSTPONE +loop ;
                   3297: 
                   3298: : sum-array ( addr u -- n )
                   3299:  0 rot rot [ ' + compile-map-array ] ;
                   3300: see sum-array
                   3301: a 5 sum-array .
                   3302: @end example
                   3303: 
                   3304: You can use the full power of Forth for generating the code; here's an
                   3305: example where the code is generated in a loop:
                   3306: 
                   3307: @example
                   3308: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3309: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3310:   POSTPONE tuck POSTPONE @@
1.48      anton    3311:   POSTPONE literal POSTPONE * POSTPONE +
                   3312:   POSTPONE swap POSTPONE cell+ ;
                   3313: 
                   3314: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3315: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3316:   0 postpone literal postpone swap
                   3317:   [ ' compile-vmul-step compile-map-array ]
                   3318:   postpone drop ;
                   3319: see compile-vmul
                   3320: 
                   3321: : a-vmul ( addr -- n )
1.51      pazsan   3322: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3323:  [ a 5 compile-vmul ] ;
                   3324: see a-vmul
                   3325: a a-vmul .
                   3326: @end example
                   3327: 
                   3328: This example uses @code{compile-map-array} to show off, but you could
1.66      anton    3329: also use @code{map-array} instead (try it now!).
1.48      anton    3330: 
                   3331: You can use this technique for efficient multiplication of large
                   3332: matrices.  In matrix multiplication, you multiply every line of one
                   3333: matrix with every column of the other matrix.  You can generate the code
                   3334: for one line once, and use it for every column.  The only downside of
                   3335: this technique is that it is cumbersome to recover the memory consumed
                   3336: by the generated code when you are done (and in more complicated cases
                   3337: it is not possible portably).
                   3338: 
1.66      anton    3339: @c !! @xref{Macros} for reference
                   3340: 
                   3341: 
1.48      anton    3342: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3343: @section Compilation Tokens
1.66      anton    3344: @cindex compilation tokens, tutorial
                   3345: @cindex CT, tutorial
1.48      anton    3346: 
                   3347: This section is Gforth-specific.  You can skip it.
                   3348: 
                   3349: @code{' word compile,} compiles the interpretation semantics.  For words
                   3350: with default compilation semantics this is the same as performing the
                   3351: compilation semantics.  To represent the compilation semantics of other
                   3352: words (e.g., words like @code{if} that have no interpretation
                   3353: semantics), Gforth has the concept of a compilation token (CT,
                   3354: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3355: You can perform the compilation semantics represented by a CT with
                   3356: @code{execute}:
1.29      crook    3357: 
1.48      anton    3358: @example
                   3359: : foo2 ( n1 n2 -- n )
                   3360:    [ comp' + execute ] ;
                   3361: see foo
                   3362: @end example
1.29      crook    3363: 
1.48      anton    3364: You can compile the compilation semantics represented by a CT with
                   3365: @code{postpone,}:
1.30      anton    3366: 
1.48      anton    3367: @example
                   3368: : foo3 ( -- )
                   3369:   [ comp' + postpone, ] ;
                   3370: see foo3
                   3371: @end example
1.30      anton    3372: 
1.51      pazsan   3373: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3374: @code{comp'} is particularly useful for words that have no
                   3375: interpretation semantics:
1.29      crook    3376: 
1.30      anton    3377: @example
1.48      anton    3378: ' if
1.60      anton    3379: comp' if .s 2drop
1.30      anton    3380: @end example
                   3381: 
1.66      anton    3382: Reference: @ref{Tokens for Words}.
                   3383: 
1.29      crook    3384: 
1.48      anton    3385: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3386: @section Wordlists and Search Order
1.66      anton    3387: @cindex wordlists tutorial
                   3388: @cindex search order, tutorial
1.48      anton    3389: 
                   3390: The dictionary is not just a memory area that allows you to allocate
                   3391: memory with @code{allot}, it also contains the Forth words, arranged in
                   3392: several wordlists.  When searching for a word in a wordlist,
                   3393: conceptually you start searching at the youngest and proceed towards
                   3394: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3395: you define a word with the same name as an older word, the new word
                   3396: shadows the older word.
                   3397: 
                   3398: Which wordlists are searched in which order is determined by the search
                   3399: order.  You can display the search order with @code{order}.  It displays
                   3400: first the search order, starting with the wordlist searched first, then
                   3401: it displays the wordlist that will contain newly defined words.
1.21      crook    3402: 
1.48      anton    3403: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3404: 
1.48      anton    3405: @example
                   3406: wordlist constant mywords
                   3407: @end example
1.21      crook    3408: 
1.48      anton    3409: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3410: defined words (the @emph{current} wordlist):
1.21      crook    3411: 
1.48      anton    3412: @example
                   3413: mywords set-current
                   3414: order
                   3415: @end example
1.26      crook    3416: 
1.48      anton    3417: Gforth does not display a name for the wordlist in @code{mywords}
                   3418: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3419: 
1.48      anton    3420: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3421: you want to put something into a specific wordlist without overall
                   3422: effect on the current wordlist, this typically looks like this:
1.21      crook    3423: 
1.48      anton    3424: @example
                   3425: get-current mywords set-current ( wid )
                   3426: create someword
                   3427: ( wid ) set-current
                   3428: @end example
1.21      crook    3429: 
1.48      anton    3430: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3431: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3432: searched wordlist is topmost.
1.21      crook    3433: 
1.48      anton    3434: @example
                   3435: get-order mywords swap 1+ set-order
                   3436: order
                   3437: @end example
1.21      crook    3438: 
1.48      anton    3439: Yes, the order of wordlists in the output of @code{order} is reversed
                   3440: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3441: 
1.141     anton    3442: @quotation Assignment
1.48      anton    3443: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3444: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3445: removes the first searched wordlist from the search order.  Experiment
                   3446: with boundary conditions (you will see some crashes or situations that
                   3447: are hard or impossible to leave).
1.141     anton    3448: @end quotation
1.21      crook    3449: 
1.48      anton    3450: The search order is a powerful foundation for providing features similar
                   3451: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3452: programs in this way has disadvantages for debugging and reuse/factoring
                   3453: that overcome the advantages in my experience (I don't do huge projects,
1.55      anton    3454: though).  These disadvantages are not so clear in other
1.82      anton    3455: languages/programming environments, because these languages are not so
1.48      anton    3456: strong in debugging and reuse.
1.21      crook    3457: 
1.66      anton    3458: @c !! example
                   3459: 
                   3460: Reference: @ref{Word Lists}.
1.21      crook    3461: 
1.29      crook    3462: @c ******************************************************************
1.48      anton    3463: @node Introduction, Words, Tutorial, Top
1.29      crook    3464: @comment node-name,     next,           previous, up
                   3465: @chapter An Introduction to ANS Forth
                   3466: @cindex Forth - an introduction
1.21      crook    3467: 
1.83      anton    3468: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
                   3469: that it is slower-paced in its examples, but uses them to dive deep into
                   3470: explaining Forth internals (not covered by the Tutorial).  Apart from
                   3471: that, this chapter covers far less material.  It is suitable for reading
                   3472: without using a computer.
                   3473: 
1.29      crook    3474: The primary purpose of this manual is to document Gforth. However, since
                   3475: Forth is not a widely-known language and there is a lack of up-to-date
                   3476: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3477: material.  For other sources of Forth-related
                   3478: information, see @ref{Forth-related information}.
1.21      crook    3479: 
1.29      crook    3480: The examples in this section should work on any ANS Forth; the
                   3481: output shown was produced using Gforth. Each example attempts to
                   3482: reproduce the exact output that Gforth produces. If you try out the
                   3483: examples (and you should), what you should type is shown @kbd{like this}
                   3484: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3485: that, where the example shows @key{RET} it means that you should
1.29      crook    3486: press the ``carriage return'' key. Unfortunately, some output formats for
                   3487: this manual cannot show the difference between @kbd{this} and
                   3488: @code{this} which will make trying out the examples harder (but not
                   3489: impossible).
1.21      crook    3490: 
1.29      crook    3491: Forth is an unusual language. It provides an interactive development
                   3492: environment which includes both an interpreter and compiler. Forth
                   3493: programming style encourages you to break a problem down into many
                   3494: @cindex factoring
                   3495: small fragments (@dfn{factoring}), and then to develop and test each
                   3496: fragment interactively. Forth advocates assert that breaking the
                   3497: edit-compile-test cycle used by conventional programming languages can
                   3498: lead to great productivity improvements.
1.21      crook    3499: 
1.29      crook    3500: @menu
1.67      anton    3501: * Introducing the Text Interpreter::  
                   3502: * Stacks and Postfix notation::  
                   3503: * Your first definition::       
                   3504: * How does that work?::         
                   3505: * Forth is written in Forth::   
                   3506: * Review - elements of a Forth system::  
                   3507: * Where to go next::            
                   3508: * Exercises::                   
1.29      crook    3509: @end menu
1.21      crook    3510: 
1.29      crook    3511: @comment ----------------------------------------------
                   3512: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3513: @section Introducing the Text Interpreter
                   3514: @cindex text interpreter
                   3515: @cindex outer interpreter
1.21      crook    3516: 
1.30      anton    3517: @c IMO this is too detailed and the pace is too slow for
                   3518: @c an introduction.  If you know German, take a look at
                   3519: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3520: @c to see how I do it - anton 
                   3521: 
1.44      crook    3522: @c nac-> Where I have accepted your comments 100% and modified the text
                   3523: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3524: @c response like this to attempt to rationalise what I have done. Of
                   3525: @c course, this is a very clumsy mechanism for something that would be
                   3526: @c done far more efficiently over a beer. Please delete any dialogue
                   3527: @c you consider closed.
                   3528: 
1.29      crook    3529: When you invoke the Forth image, you will see a startup banner printed
                   3530: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3531: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3532: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3533: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3534: about the text interpreter as you read through this chapter, for more
                   3535: detail @pxref{The Text Interpreter}).
1.21      crook    3536: 
1.29      crook    3537: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3538: input. Type a number and press the @key{RET} key:
1.21      crook    3539: 
1.26      crook    3540: @example
1.30      anton    3541: @kbd{45@key{RET}}  ok
1.26      crook    3542: @end example
1.21      crook    3543: 
1.29      crook    3544: Rather than give you a prompt to invite you to input something, the text
                   3545: interpreter prints a status message @i{after} it has processed a line
                   3546: of input. The status message in this case (``@code{ ok}'' followed by
                   3547: carriage-return) indicates that the text interpreter was able to process
                   3548: all of your input successfully. Now type something illegal:
                   3549: 
                   3550: @example
1.30      anton    3551: @kbd{qwer341@key{RET}}
1.134     anton    3552: *the terminal*:2: Undefined word
                   3553: >>>qwer341<<<
                   3554: Backtrace:
                   3555: $2A95B42A20 throw 
                   3556: $2A95B57FB8 no.extensions 
1.29      crook    3557: @end example
1.23      crook    3558: 
1.134     anton    3559: The exact text, other than the ``Undefined word'' may differ slightly
                   3560: on your system, but the effect is the same; when the text interpreter
1.29      crook    3561: detects an error, it discards any remaining text on a line, resets
1.134     anton    3562: certain internal state and prints an error message. For a detailed
                   3563: description of error messages see @ref{Error messages}.
1.23      crook    3564: 
1.29      crook    3565: The text interpreter waits for you to press carriage-return, and then
                   3566: processes your input line. Starting at the beginning of the line, it
                   3567: breaks the line into groups of characters separated by spaces. For each
                   3568: group of characters in turn, it makes two attempts to do something:
1.23      crook    3569: 
1.29      crook    3570: @itemize @bullet
                   3571: @item
1.44      crook    3572: @cindex name dictionary
1.29      crook    3573: It tries to treat it as a command. It does this by searching a @dfn{name
                   3574: dictionary}. If the group of characters matches an entry in the name
                   3575: dictionary, the name dictionary provides the text interpreter with
                   3576: information that allows the text interpreter perform some actions. In
                   3577: Forth jargon, we say that the group
                   3578: @cindex word
                   3579: @cindex definition
                   3580: @cindex execution token
                   3581: @cindex xt
                   3582: of characters names a @dfn{word}, that the dictionary search returns an
                   3583: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3584: word, and that the text interpreter executes the xt. Often, the terms
                   3585: @dfn{word} and @dfn{definition} are used interchangeably.
                   3586: @item
                   3587: If the text interpreter fails to find a match in the name dictionary, it
                   3588: tries to treat the group of characters as a number in the current number
                   3589: base (when you start up Forth, the current number base is base 10). If
                   3590: the group of characters legitimately represents a number, the text
                   3591: interpreter pushes the number onto a stack (we'll learn more about that
                   3592: in the next section).
                   3593: @end itemize
1.23      crook    3594: 
1.29      crook    3595: If the text interpreter is unable to do either of these things with any
                   3596: group of characters, it discards the group of characters and the rest of
                   3597: the line, then prints an error message. If the text interpreter reaches
                   3598: the end of the line without error, it prints the status message ``@code{ ok}''
                   3599: followed by carriage-return.
1.21      crook    3600: 
1.29      crook    3601: This is the simplest command we can give to the text interpreter:
1.23      crook    3602: 
                   3603: @example
1.30      anton    3604: @key{RET}  ok
1.23      crook    3605: @end example
1.21      crook    3606: 
1.29      crook    3607: The text interpreter did everything we asked it to do (nothing) without
                   3608: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3609: command:
1.21      crook    3610: 
1.23      crook    3611: @example
1.30      anton    3612: @kbd{12 dup fred dup@key{RET}}
1.134     anton    3613: *the terminal*:3: Undefined word
                   3614: 12 dup >>>fred<<< dup
                   3615: Backtrace:
                   3616: $2A95B42A20 throw 
                   3617: $2A95B57FB8 no.extensions 
1.23      crook    3618: @end example
1.21      crook    3619: 
1.29      crook    3620: When you press the carriage-return key, the text interpreter starts to
                   3621: work its way along the line:
1.21      crook    3622: 
1.29      crook    3623: @itemize @bullet
                   3624: @item
                   3625: When it gets to the space after the @code{2}, it takes the group of
                   3626: characters @code{12} and looks them up in the name
                   3627: dictionary@footnote{We can't tell if it found them or not, but assume
                   3628: for now that it did not}. There is no match for this group of characters
                   3629: in the name dictionary, so it tries to treat them as a number. It is
                   3630: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3631: (whatever that means).
                   3632: @item
                   3633: The text interpreter resumes scanning the line and gets the next group
                   3634: of characters, @code{dup}. It looks it up in the name dictionary and
                   3635: (you'll have to take my word for this) finds it, and executes the word
                   3636: @code{dup} (whatever that means).
                   3637: @item
                   3638: Once again, the text interpreter resumes scanning the line and gets the
                   3639: group of characters @code{fred}. It looks them up in the name
                   3640: dictionary, but can't find them. It tries to treat them as a number, but
                   3641: they don't represent any legal number.
                   3642: @end itemize
1.21      crook    3643: 
1.29      crook    3644: At this point, the text interpreter gives up and prints an error
                   3645: message. The error message shows exactly how far the text interpreter
                   3646: got in processing the line. In particular, it shows that the text
                   3647: interpreter made no attempt to do anything with the final character
                   3648: group, @code{dup}, even though we have good reason to believe that the
                   3649: text interpreter would have no problem looking that word up and
                   3650: executing it a second time.
1.21      crook    3651: 
                   3652: 
1.29      crook    3653: @comment ----------------------------------------------
                   3654: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3655: @section Stacks, postfix notation and parameter passing
                   3656: @cindex text interpreter
                   3657: @cindex outer interpreter
1.21      crook    3658: 
1.29      crook    3659: In procedural programming languages (like C and Pascal), the
                   3660: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3661: functions or procedures are called with @dfn{explicit parameters}. For
                   3662: example, in C we might write:
1.21      crook    3663: 
1.23      crook    3664: @example
1.29      crook    3665: total = total + new_volume(length,height,depth);
1.23      crook    3666: @end example
1.21      crook    3667: 
1.23      crook    3668: @noindent
1.29      crook    3669: where new_volume is a function-call to another piece of code, and total,
                   3670: length, height and depth are all variables. length, height and depth are
                   3671: parameters to the function-call.
1.21      crook    3672: 
1.29      crook    3673: In Forth, the equivalent of the function or procedure is the
                   3674: @dfn{definition} and parameters are implicitly passed between
                   3675: definitions using a shared stack that is visible to the
                   3676: programmer. Although Forth does support variables, the existence of the
                   3677: stack means that they are used far less often than in most other
                   3678: programming languages. When the text interpreter encounters a number, it
                   3679: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3680: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3681: used for any operation is implied unambiguously by the operation being
                   3682: performed. The stack used for all integer operations is called the @dfn{data
                   3683: stack} and, since this is the stack used most commonly, references to
                   3684: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3685: 
1.29      crook    3686: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3687: 
1.23      crook    3688: @example
1.30      anton    3689: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3690: @end example
1.21      crook    3691: 
1.29      crook    3692: Then this instructs the text interpreter to placed three numbers on the
                   3693: (data) stack. An analogy for the behaviour of the stack is to take a
                   3694: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3695: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3696: you take a card off the pile then, unless you're prepared to fiddle a
                   3697: bit, the card that you take off will be the 3 (``first-out''). The
                   3698: number that will be first-out of the stack is called the @dfn{top of
                   3699: stack}, which
                   3700: @cindex TOS definition
                   3701: is often abbreviated to @dfn{TOS}.
1.21      crook    3702: 
1.29      crook    3703: To understand how parameters are passed in Forth, consider the
                   3704: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3705: be surprised to learn that this definition performs addition. More
                   3706: precisely, it adds two number together and produces a result. Where does
                   3707: it get the two numbers from? It takes the top two numbers off the
                   3708: stack. Where does it place the result? On the stack. You can act-out the
                   3709: behaviour of @code{+} with your playing cards like this:
1.21      crook    3710: 
                   3711: @itemize @bullet
                   3712: @item
1.29      crook    3713: Pick up two cards from the stack on the table
1.21      crook    3714: @item
1.29      crook    3715: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3716: numbers''
1.21      crook    3717: @item
1.29      crook    3718: Decide that the answer is 5
1.21      crook    3719: @item
1.29      crook    3720: Shuffle the two cards back into the pack and find a 5
1.21      crook    3721: @item
1.29      crook    3722: Put a 5 on the remaining ace that's on the table.
1.21      crook    3723: @end itemize
                   3724: 
1.29      crook    3725: If you don't have a pack of cards handy but you do have Forth running,
                   3726: you can use the definition @code{.s} to show the current state of the stack,
                   3727: without affecting the stack. Type:
1.21      crook    3728: 
                   3729: @example
1.124     anton    3730: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30      anton    3731: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3732: @end example
                   3733: 
1.124     anton    3734: The text interpreter looks up the word @code{clearstacks} and executes
                   3735: it; it tidies up the stacks and removes any entries that may have been
1.29      crook    3736: left on it by earlier examples. The text interpreter pushes each of the
                   3737: three numbers in turn onto the stack. Finally, the text interpreter
                   3738: looks up the word @code{.s} and executes it. The effect of executing
                   3739: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3740: followed by a list of all the items on the stack; the item on the far
                   3741: right-hand side is the TOS.
1.21      crook    3742: 
1.29      crook    3743: You can now type:
1.21      crook    3744: 
1.29      crook    3745: @example
1.30      anton    3746: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3747: @end example
1.21      crook    3748: 
1.29      crook    3749: @noindent
                   3750: which is correct; there are now 2 items on the stack and the result of
                   3751: the addition is 5.
1.23      crook    3752: 
1.29      crook    3753: If you're playing with cards, try doing a second addition: pick up the
                   3754: two cards, work out that their sum is 6, shuffle them into the pack,
                   3755: look for a 6 and place that on the table. You now have just one item on
                   3756: the stack. What happens if you try to do a third addition? Pick up the
                   3757: first card, pick up the second card -- ah! There is no second card. This
                   3758: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95      anton    3759: do the same thing with Forth it often reports an error (probably a Stack
1.29      crook    3760: Underflow or an Invalid Memory Address error).
1.23      crook    3761: 
1.29      crook    3762: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3763: which simply accepts that there is a finite amount of storage space
                   3764: reserved for the stack. To stretch the playing card analogy, if you had
                   3765: enough packs of cards and you piled the cards up on the table, you would
                   3766: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3767: allows you to set the maximum size of the stacks. In general, the only
                   3768: time that you will get a stack overflow is because a definition has a
                   3769: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3770: 
1.29      crook    3771: There's one final use for the playing card analogy. If you model your
                   3772: stack using a pack of playing cards, the maximum number of items on
                   3773: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3774: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3775: possible numbers are positive integer numbers 1 through 13; you can't
                   3776: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3777: think about some of the cards, you can accommodate different
                   3778: numbers. For example, you could think of the Jack as representing 0,
                   3779: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3780: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3781: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3782: 
1.29      crook    3783: In that analogy, the limit was the amount of information that a single
                   3784: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3785: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3786: implementation dependent and affects the maximum value that a stack
                   3787: entry can hold. A Standard Forth provides a cell size of at least
                   3788: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3789: 
1.29      crook    3790: Forth does not do any type checking for you, so you are free to
                   3791: manipulate and combine stack items in any way you wish. A convenient way
                   3792: of treating stack items is as 2's complement signed integers, and that
                   3793: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3794: 
1.29      crook    3795: @example
1.30      anton    3796: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3797: @end example
1.21      crook    3798: 
1.29      crook    3799: If you use numbers and definitions like @code{+} in order to turn Forth
                   3800: into a great big pocket calculator, you will realise that it's rather
                   3801: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3802: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3803: result). The terminology used to describe this difference is to say that
                   3804: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3805: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3806: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3807: 
1.29      crook    3808: Whilst postfix notation might look confusing to begin with, it has
                   3809: several important advantages:
1.21      crook    3810: 
1.23      crook    3811: @itemize @bullet
                   3812: @item
1.29      crook    3813: it is unambiguous
1.23      crook    3814: @item
1.29      crook    3815: it is more concise
1.23      crook    3816: @item
1.29      crook    3817: it fits naturally with a stack-based system
1.23      crook    3818: @end itemize
1.21      crook    3819: 
1.29      crook    3820: To examine these claims in more detail, consider these sums:
1.21      crook    3821: 
1.29      crook    3822: @example
                   3823: 6 + 5 * 4 =
                   3824: 4 * 5 + 6 =
                   3825: @end example
1.21      crook    3826: 
1.29      crook    3827: If you're just learning maths or your maths is very rusty, you will
                   3828: probably come up with the answer 44 for the first and 26 for the
                   3829: second. If you are a bit of a whizz at maths you will remember the
                   3830: @i{convention} that multiplication takes precendence over addition, and
                   3831: you'd come up with the answer 26 both times. To explain the answer 26
                   3832: to someone who got the answer 44, you'd probably rewrite the first sum
                   3833: like this:
1.21      crook    3834: 
1.29      crook    3835: @example
                   3836: 6 + (5 * 4) =
                   3837: @end example
1.21      crook    3838: 
1.29      crook    3839: If what you really wanted was to perform the addition before the
                   3840: multiplication, you would have to use parentheses to force it.
1.21      crook    3841: 
1.29      crook    3842: If you did the first two sums on a pocket calculator you would probably
                   3843: get the right answers, unless you were very cautious and entered them using
                   3844: these keystroke sequences:
1.21      crook    3845: 
1.29      crook    3846: 6 + 5 = * 4 =
                   3847: 4 * 5 = + 6 =
1.21      crook    3848: 
1.29      crook    3849: Postfix notation is unambiguous because the order that the operators
                   3850: are applied is always explicit; that also means that parentheses are
                   3851: never required. The operators are @i{active} (the act of quoting the
                   3852: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3853: 
1.29      crook    3854: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3855: equivalent ways:
1.26      crook    3856: 
                   3857: @example
1.29      crook    3858: 6 5 4 * +      or:
                   3859: 5 4 * 6 +
1.26      crook    3860: @end example
1.23      crook    3861: 
1.29      crook    3862: An important thing that you should notice about this notation is that
                   3863: the @i{order} of the numbers does not change; if you want to subtract
                   3864: 2 from 10 you type @code{10 2 -}.
1.1       anton    3865: 
1.29      crook    3866: The reason that Forth uses postfix notation is very simple to explain: it
                   3867: makes the implementation extremely simple, and it follows naturally from
                   3868: using the stack as a mechanism for passing parameters. Another way of
                   3869: thinking about this is to realise that all Forth definitions are
                   3870: @i{active}; they execute as they are encountered by the text
                   3871: interpreter. The result of this is that the syntax of Forth is trivially
                   3872: simple.
1.1       anton    3873: 
                   3874: 
                   3875: 
1.29      crook    3876: @comment ----------------------------------------------
                   3877: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3878: @section Your first Forth definition
                   3879: @cindex first definition
1.1       anton    3880: 
1.29      crook    3881: Until now, the examples we've seen have been trivial; we've just been
                   3882: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3883: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3884: again@footnote{That's not quite true. If you press the up-arrow key on
                   3885: your keyboard you should be able to scroll back to any earlier command,
                   3886: edit it and re-enter it.} In this section we'll see how to add new
                   3887: words to Forth's vocabulary.
1.1       anton    3888: 
1.29      crook    3889: The easiest way to create a new word is to use a @dfn{colon
                   3890: definition}. We'll define a few and try them out before worrying too
                   3891: much about how they work. Try typing in these examples; be careful to
                   3892: copy the spaces accurately:
1.1       anton    3893: 
1.29      crook    3894: @example
                   3895: : add-two 2 + . ;
                   3896: : greet ." Hello and welcome" ;
                   3897: : demo 5 add-two ;
                   3898: @end example
1.1       anton    3899: 
1.29      crook    3900: @noindent
                   3901: Now try them out:
1.1       anton    3902: 
1.29      crook    3903: @example
1.30      anton    3904: @kbd{greet@key{RET}} Hello and welcome  ok
                   3905: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3906: @kbd{4 add-two@key{RET}} 6  ok
                   3907: @kbd{demo@key{RET}} 7  ok
                   3908: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3909: @end example
1.1       anton    3910: 
1.29      crook    3911: The first new thing that we've introduced here is the pair of words
                   3912: @code{:} and @code{;}. These are used to start and terminate a new
                   3913: definition, respectively. The first word after the @code{:} is the name
                   3914: for the new definition.
1.1       anton    3915: 
1.29      crook    3916: As you can see from the examples, a definition is built up of words that
                   3917: have already been defined; Forth makes no distinction between
                   3918: definitions that existed when you started the system up, and those that
                   3919: you define yourself.
1.1       anton    3920: 
1.29      crook    3921: The examples also introduce the words @code{.} (dot), @code{."}
                   3922: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3923: the stack and displays it. It's like @code{.s} except that it only
                   3924: displays the top item of the stack and it is destructive; after it has
                   3925: executed, the number is no longer on the stack. There is always one
                   3926: space printed after the number, and no spaces before it. Dot-quote
                   3927: defines a string (a sequence of characters) that will be printed when
                   3928: the word is executed. The string can contain any printable characters
                   3929: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3930: word but it acts as a delimiter (the way that delimiters work is
                   3931: described in the next section). Finally, @code{dup} duplicates the value
                   3932: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3933: 
1.29      crook    3934: We already know that the text interpreter searches through the
                   3935: dictionary to locate names. If you've followed the examples earlier, you
                   3936: will already have a definition called @code{add-two}. Lets try modifying
                   3937: it by typing in a new definition:
1.1       anton    3938: 
1.29      crook    3939: @example
1.30      anton    3940: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3941: @end example
1.5       anton    3942: 
1.29      crook    3943: Forth recognised that we were defining a word that already exists, and
                   3944: printed a message to warn us of that fact. Let's try out the new
                   3945: definition:
1.5       anton    3946: 
1.29      crook    3947: @example
1.30      anton    3948: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3949: @end example
1.1       anton    3950: 
1.29      crook    3951: @noindent
                   3952: All that we've actually done here, though, is to create a new
                   3953: definition, with a particular name. The fact that there was already a
                   3954: definition with the same name did not make any difference to the way
                   3955: that the new definition was created (except that Forth printed a warning
                   3956: message). The old definition of add-two still exists (try @code{demo}
                   3957: again to see that this is true). Any new definition will use the new
                   3958: definition of @code{add-two}, but old definitions continue to use the
                   3959: version that already existed at the time that they were @code{compiled}.
1.1       anton    3960: 
1.29      crook    3961: Before you go on to the next section, try defining and redefining some
                   3962: words of your own.
1.1       anton    3963: 
1.29      crook    3964: @comment ----------------------------------------------
                   3965: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3966: @section How does that work?
                   3967: @cindex parsing words
1.1       anton    3968: 
1.30      anton    3969: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3970: 
                   3971: @c Is it a good idea to talk about the interpretation semantics of a
                   3972: @c number? We don't have an xt to go along with it. - anton
                   3973: 
                   3974: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3975: @c be better to keep them (or add run-time semantics), to make it easier to
                   3976: @c explain what compilation semantics usually does. - anton
                   3977: 
1.44      crook    3978: @c nac-> I removed the term ``default compilation sematics'' from the
                   3979: @c introductory chapter. Removing ``execution semantics'' was making
                   3980: @c everything simpler to explain, then I think the use of this term made
                   3981: @c everything more complex again. I replaced it with ``default
                   3982: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3983: @c ``a definition that has neither the immediate nor the compile-only
1.83      anton    3984: @c flag set''.
                   3985: 
                   3986: @c anton: I have eliminated default semantics (except in one place where it
                   3987: @c means "default interpretation and compilation semantics"), because it
                   3988: @c makes no sense in the presence of combined words.  I reverted to
                   3989: @c "execution semantics" where necessary.
                   3990: 
                   3991: @c nac-> I reworded big chunks of the ``how does that work''
1.44      crook    3992: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3993: @c what you think -- I know I have not addressed your primary concern
                   3994: @c that it is too heavy-going for an introduction. From what I understood
                   3995: @c of your course notes it looks as though they might be a good framework. 
                   3996: @c Things that I've tried to capture here are some things that came as a
                   3997: @c great revelation here when I first understood them. Also, I like the
                   3998: @c fact that a very simple code example shows up almost all of the issues
                   3999: @c that you need to understand to see how Forth works. That's unique and
                   4000: @c worthwhile to emphasise.
                   4001: 
1.83      anton    4002: @c anton: I think it's a good idea to present the details, especially those
                   4003: @c that you found to be a revelation, and probably the tutorial tries to be
                   4004: @c too superficial and does not get some of the things across that make
                   4005: @c Forth special.  I do believe that most of the time these things should
                   4006: @c be discussed at the end of a section or in separate sections instead of
                   4007: @c in the middle of a section (e.g., the stuff you added in "User-defined
                   4008: @c defining words" leads in a completely different direction from the rest
                   4009: @c of the section).
                   4010: 
1.29      crook    4011: Now we're going to take another look at the definition of @code{add-two}
                   4012: from the previous section. From our knowledge of the way that the text
                   4013: interpreter works, we would have expected this result when we tried to
                   4014: define @code{add-two}:
1.21      crook    4015: 
1.29      crook    4016: @example
1.44      crook    4017: @kbd{: add-two 2 + . ;@key{RET}}
1.134     anton    4018: *the terminal*:4: Undefined word
                   4019: : >>>add-two<<< 2 + . ;
1.29      crook    4020: @end example
1.28      crook    4021: 
1.29      crook    4022: The reason that this didn't happen is bound up in the way that @code{:}
                   4023: works. The word @code{:} does two special things. The first special
                   4024: thing that it does prevents the text interpreter from ever seeing the
                   4025: characters @code{add-two}. The text interpreter uses a variable called
                   4026: @cindex modifying >IN
1.44      crook    4027: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    4028: input line. When it encounters the word @code{:} it behaves in exactly
                   4029: the same way as it does for any other word; it looks it up in the name
                   4030: dictionary, finds its xt and executes it. When @code{:} executes, it
                   4031: looks at the input buffer, finds the word @code{add-two} and advances the
                   4032: value of @code{>IN} to point past it. It then does some other stuff
                   4033: associated with creating the new definition (including creating an entry
                   4034: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   4035: completes, control returns to the text interpreter, which is oblivious
                   4036: to the fact that it has been tricked into ignoring part of the input
                   4037: line.
1.21      crook    4038: 
1.29      crook    4039: @cindex parsing words
                   4040: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   4041: prevent the text interpreter from acting on the whole of the input line
                   4042: -- are called @dfn{parsing words}.
1.21      crook    4043: 
1.29      crook    4044: @cindex @code{state} - effect on the text interpreter
                   4045: @cindex text interpreter - effect of state
                   4046: The second special thing that @code{:} does is change the value of a
                   4047: variable called @code{state}, which affects the way that the text
                   4048: interpreter behaves. When Gforth starts up, @code{state} has the value
                   4049: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   4050: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    4051: the text interpreter is said to be @dfn{compiling}.
                   4052: 
                   4053: In this example, the text interpreter is compiling when it processes the
                   4054: string ``@code{2 + . ;}''. It still breaks the string down into
                   4055: character sequences in the same way. However, instead of pushing the
                   4056: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   4057: into the definition of @code{add-two} that will make the number @code{2} get
                   4058: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   4059: the behaviours of @code{+} and @code{.} are also compiled into the
                   4060: definition.
                   4061: 
                   4062: One category of words don't get compiled. These so-called @dfn{immediate
                   4063: words} get executed (performed @i{now}) regardless of whether the text
                   4064: interpreter is interpreting or compiling. The word @code{;} is an
                   4065: immediate word. Rather than being compiled into the definition, it
                   4066: executes. Its effect is to terminate the current definition, which
                   4067: includes changing the value of @code{state} back to 0.
                   4068: 
                   4069: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   4070: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   4071: definition.
1.28      crook    4072: 
1.30      anton    4073: In Forth, every word or number can be described in terms of two
1.29      crook    4074: properties:
1.28      crook    4075: 
                   4076: @itemize @bullet
                   4077: @item
1.29      crook    4078: @cindex interpretation semantics
1.44      crook    4079: Its @dfn{interpretation semantics} describe how it will behave when the
                   4080: text interpreter encounters it in @dfn{interpret} state. The
                   4081: interpretation semantics of a word are represented by an @dfn{execution
                   4082: token}.
1.28      crook    4083: @item
1.29      crook    4084: @cindex compilation semantics
1.44      crook    4085: Its @dfn{compilation semantics} describe how it will behave when the
                   4086: text interpreter encounters it in @dfn{compile} state. The compilation
                   4087: semantics of a word are represented in an implementation-dependent way;
                   4088: Gforth uses a @dfn{compilation token}.
1.29      crook    4089: @end itemize
                   4090: 
                   4091: @noindent
                   4092: Numbers are always treated in a fixed way:
                   4093: 
                   4094: @itemize @bullet
1.28      crook    4095: @item
1.44      crook    4096: When the number is @dfn{interpreted}, its behaviour is to push the
                   4097: number onto the stack.
1.28      crook    4098: @item
1.30      anton    4099: When the number is @dfn{compiled}, a piece of code is appended to the
                   4100: current definition that pushes the number when it runs. (In other words,
                   4101: the compilation semantics of a number are to postpone its interpretation
                   4102: semantics until the run-time of the definition that it is being compiled
                   4103: into.)
1.29      crook    4104: @end itemize
                   4105: 
1.44      crook    4106: Words don't behave in such a regular way, but most have @i{default
                   4107: semantics} which means that they behave like this:
1.29      crook    4108: 
                   4109: @itemize @bullet
1.28      crook    4110: @item
1.30      anton    4111: The @dfn{interpretation semantics} of the word are to do something useful.
                   4112: @item
1.29      crook    4113: The @dfn{compilation semantics} of the word are to append its
1.30      anton    4114: @dfn{interpretation semantics} to the current definition (so that its
                   4115: run-time behaviour is to do something useful).
1.28      crook    4116: @end itemize
                   4117: 
1.30      anton    4118: @cindex immediate words
1.44      crook    4119: The actual behaviour of any particular word can be controlled by using
                   4120: the words @code{immediate} and @code{compile-only} when the word is
                   4121: defined. These words set flags in the name dictionary entry of the most
                   4122: recently defined word, and these flags are retrieved by the text
                   4123: interpreter when it finds the word in the name dictionary.
                   4124: 
                   4125: A word that is marked as @dfn{immediate} has compilation semantics that
                   4126: are identical to its interpretation semantics. In other words, it
                   4127: behaves like this:
1.29      crook    4128: 
                   4129: @itemize @bullet
                   4130: @item
1.30      anton    4131: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    4132: @item
1.30      anton    4133: The @dfn{compilation semantics} of the word are to do something useful
                   4134: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    4135: @end itemize
1.28      crook    4136: 
1.44      crook    4137: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   4138: performing the interpretation semantics of the word directly; an attempt
                   4139: to do so will generate an error. It is never necessary to use
                   4140: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   4141: provided by many implementations) but it is good etiquette to apply it
                   4142: to a word that will not behave correctly (and might have unexpected
                   4143: side-effects) in interpret state. For example, it is only legal to use
                   4144: the conditional word @code{IF} within a definition. If you forget this
                   4145: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   4146: @code{compile-only} allows the text interpreter to generate a helpful
                   4147: error message rather than subjecting you to the consequences of your
                   4148: folly.
                   4149: 
1.29      crook    4150: This example shows the difference between an immediate and a
                   4151: non-immediate word:
1.28      crook    4152: 
1.29      crook    4153: @example
                   4154: : show-state state @@ . ;
                   4155: : show-state-now show-state ; immediate
                   4156: : word1 show-state ;
                   4157: : word2 show-state-now ;
1.28      crook    4158: @end example
1.23      crook    4159: 
1.29      crook    4160: The word @code{immediate} after the definition of @code{show-state-now}
                   4161: makes that word an immediate word. These definitions introduce a new
                   4162: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   4163: variable, and leaves it on the stack. Therefore, the behaviour of
                   4164: @code{show-state} is to print a number that represents the current value
                   4165: of @code{state}.
1.28      crook    4166: 
1.29      crook    4167: When you execute @code{word1}, it prints the number 0, indicating that
                   4168: the system is interpreting. When the text interpreter compiled the
                   4169: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    4170: compilation semantics are to append its interpretation semantics to the
1.29      crook    4171: current definition. When you execute @code{word1}, it performs the
1.30      anton    4172: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    4173: (and therefore @code{show-state}) are executed, the system is
                   4174: interpreting.
1.28      crook    4175: 
1.30      anton    4176: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    4177: you should have seen the number -1 printed, followed by ``@code{
                   4178: ok}''. When the text interpreter compiled the definition of
                   4179: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    4180: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4181: semantics. It is executed straight away (even before the text
                   4182: interpreter has moved on to process another group of characters; the
                   4183: @code{;} in this example). The effect of executing it are to display the
                   4184: value of @code{state} @i{at the time that the definition of}
                   4185: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4186: system is compiling at this time. If you execute @code{word2} it does
                   4187: nothing at all.
1.28      crook    4188: 
1.29      crook    4189: @cindex @code{."}, how it works
                   4190: Before leaving the subject of immediate words, consider the behaviour of
                   4191: @code{."} in the definition of @code{greet}, in the previous
                   4192: section. This word is both a parsing word and an immediate word. Notice
                   4193: that there is a space between @code{."} and the start of the text
                   4194: @code{Hello and welcome}, but that there is no space between the last
                   4195: letter of @code{welcome} and the @code{"} character. The reason for this
                   4196: is that @code{."} is a Forth word; it must have a space after it so that
                   4197: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4198: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4199: is displayed, there is neither a space before the @code{H} nor after the
                   4200: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4201: that @code{greet} is defined. When it executes, its behaviour is to
                   4202: search forward in the input line looking for the delimiter. When it
                   4203: finds the delimiter, it updates @code{>IN} to point past the
                   4204: delimiter. It also compiles some magic code into the definition of
                   4205: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4206: compiles the string @code{Hello and welcome} into memory so that it is
                   4207: available to be printed later. When the text interpreter gains control,
                   4208: the next word it finds in the input stream is @code{;} and so it
                   4209: terminates the definition of @code{greet}.
1.28      crook    4210: 
                   4211: 
                   4212: @comment ----------------------------------------------
1.29      crook    4213: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4214: @section Forth is written in Forth
                   4215: @cindex structure of Forth programs
                   4216: 
                   4217: When you start up a Forth compiler, a large number of definitions
                   4218: already exist. In Forth, you develop a new application using bottom-up
                   4219: programming techniques to create new definitions that are defined in
                   4220: terms of existing definitions. As you create each definition you can
                   4221: test and debug it interactively.
                   4222: 
                   4223: If you have tried out the examples in this section, you will probably
                   4224: have typed them in by hand; when you leave Gforth, your definitions will
                   4225: be lost. You can avoid this by using a text editor to enter Forth source
                   4226: code into a file, and then loading code from the file using
1.49      anton    4227: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    4228: processed by the text interpreter, just as though you had typed it in by
                   4229: hand@footnote{Actually, there are some subtle differences -- see
                   4230: @ref{The Text Interpreter}.}.
                   4231: 
                   4232: Gforth also supports the traditional Forth alternative to using text
1.49      anton    4233: files for program entry (@pxref{Blocks}).
1.28      crook    4234: 
1.29      crook    4235: In common with many, if not most, Forth compilers, most of Gforth is
                   4236: actually written in Forth. All of the @file{.fs} files in the
                   4237: installation directory@footnote{For example,
1.30      anton    4238: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4239: study to see examples of Forth programming.
1.28      crook    4240: 
1.29      crook    4241: Gforth maintains a history file that records every line that you type to
                   4242: the text interpreter. This file is preserved between sessions, and is
                   4243: used to provide a command-line recall facility. If you enter long
                   4244: definitions by hand, you can use a text editor to paste them out of the
                   4245: history file into a Forth source file for reuse at a later time
1.49      anton    4246: (for more information @pxref{Command-line editing}).
1.28      crook    4247: 
                   4248: 
                   4249: @comment ----------------------------------------------
1.29      crook    4250: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4251: @section Review - elements of a Forth system
                   4252: @cindex elements of a Forth system
1.28      crook    4253: 
1.29      crook    4254: To summarise this chapter:
1.28      crook    4255: 
                   4256: @itemize @bullet
                   4257: @item
1.29      crook    4258: Forth programs use @dfn{factoring} to break a problem down into small
                   4259: fragments called @dfn{words} or @dfn{definitions}.
                   4260: @item
                   4261: Forth program development is an interactive process.
                   4262: @item
                   4263: The main command loop that accepts input, and controls both
                   4264: interpretation and compilation, is called the @dfn{text interpreter}
                   4265: (also known as the @dfn{outer interpreter}).
                   4266: @item
                   4267: Forth has a very simple syntax, consisting of words and numbers
                   4268: separated by spaces or carriage-return characters. Any additional syntax
                   4269: is imposed by @dfn{parsing words}.
                   4270: @item
                   4271: Forth uses a stack to pass parameters between words. As a result, it
                   4272: uses postfix notation.
                   4273: @item
                   4274: To use a word that has previously been defined, the text interpreter
                   4275: searches for the word in the @dfn{name dictionary}.
                   4276: @item
1.30      anton    4277: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4278: @item
1.29      crook    4279: The text interpreter uses the value of @code{state} to select between
                   4280: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4281: semantics} of a word that it encounters.
1.28      crook    4282: @item
1.30      anton    4283: The relationship between the @dfn{interpretation semantics} and
                   4284: @dfn{compilation semantics} for a word
1.29      crook    4285: depend upon the way in which the word was defined (for example, whether
                   4286: it is an @dfn{immediate} word).
1.28      crook    4287: @item
1.29      crook    4288: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4289: definitions}) or in some other way (usually a lower-level language and
                   4290: as a result often called @dfn{low-level definitions}, @dfn{code
                   4291: definitions} or @dfn{primitives}).
1.28      crook    4292: @item
1.29      crook    4293: Many Forth systems are implemented mainly in Forth.
1.28      crook    4294: @end itemize
                   4295: 
                   4296: 
1.29      crook    4297: @comment ----------------------------------------------
1.48      anton    4298: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4299: @section Where To Go Next
                   4300: @cindex where to go next
1.28      crook    4301: 
1.29      crook    4302: Amazing as it may seem, if you have read (and understood) this far, you
                   4303: know almost all the fundamentals about the inner workings of a Forth
                   4304: system. You certainly know enough to be able to read and understand the
                   4305: rest of this manual and the ANS Forth document, to learn more about the
                   4306: facilities that Forth in general and Gforth in particular provide. Even
                   4307: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4308: However, that's not a good idea just yet... better to try writing some
1.29      crook    4309: programs in Gforth.
1.28      crook    4310: 
1.29      crook    4311: Forth has such a rich vocabulary that it can be hard to know where to
                   4312: start in learning it. This section suggests a few sets of words that are
                   4313: enough to write small but useful programs. Use the word index in this
                   4314: document to learn more about each word, then try it out and try to write
                   4315: small definitions using it. Start by experimenting with these words:
1.28      crook    4316: 
                   4317: @itemize @bullet
                   4318: @item
1.29      crook    4319: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4320: @item
                   4321: Comparison: @code{MIN MAX =}
                   4322: @item
                   4323: Logic: @code{AND OR XOR NOT}
                   4324: @item
                   4325: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4326: @item
1.29      crook    4327: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4328: @item
1.29      crook    4329: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4330: @item
1.29      crook    4331: Defining words: @code{: ; CREATE}
1.28      crook    4332: @item
1.29      crook    4333: Memory allocation words: @code{ALLOT ,}
1.28      crook    4334: @item
1.29      crook    4335: Tools: @code{SEE WORDS .S MARKER}
                   4336: @end itemize
                   4337: 
                   4338: When you have mastered those, go on to:
                   4339: 
                   4340: @itemize @bullet
1.28      crook    4341: @item
1.29      crook    4342: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4343: @item
1.29      crook    4344: Memory access: @code{@@ !}
1.28      crook    4345: @end itemize
1.23      crook    4346: 
1.29      crook    4347: When you have mastered these, there's nothing for it but to read through
                   4348: the whole of this manual and find out what you've missed.
                   4349: 
                   4350: @comment ----------------------------------------------
1.48      anton    4351: @node Exercises,  , Where to go next, Introduction
1.29      crook    4352: @section Exercises
                   4353: @cindex exercises
                   4354: 
                   4355: TODO: provide a set of programming excercises linked into the stuff done
                   4356: already and into other sections of the manual. Provide solutions to all
                   4357: the exercises in a .fs file in the distribution.
                   4358: 
                   4359: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4360: 
                   4361: @c excercises:
                   4362: @c 1. take inches and convert to feet and inches.
                   4363: @c 2. take temperature and convert from fahrenheight to celcius;
                   4364: @c    may need to care about symmetric vs floored??
                   4365: @c 3. take input line and do character substitution
                   4366: @c    to encipher or decipher
                   4367: @c 4. as above but work on a file for in and out
                   4368: @c 5. take input line and convert to pig-latin 
                   4369: @c
                   4370: @c thing of sets of things to exercise then come up with
                   4371: @c problems that need those things.
                   4372: 
                   4373: 
1.26      crook    4374: @c ******************************************************************
1.29      crook    4375: @node Words, Error messages, Introduction, Top
1.1       anton    4376: @chapter Forth Words
1.26      crook    4377: @cindex words
1.1       anton    4378: 
                   4379: @menu
                   4380: * Notation::                    
1.65      anton    4381: * Case insensitivity::          
                   4382: * Comments::                    
                   4383: * Boolean Flags::               
1.1       anton    4384: * Arithmetic::                  
                   4385: * Stack Manipulation::          
1.5       anton    4386: * Memory::                      
1.1       anton    4387: * Control Structures::          
                   4388: * Defining Words::              
1.65      anton    4389: * Interpretation and Compilation Semantics::  
1.47      crook    4390: * Tokens for Words::            
1.81      anton    4391: * Compiling words::             
1.65      anton    4392: * The Text Interpreter::        
1.111     anton    4393: * The Input Stream::            
1.65      anton    4394: * Word Lists::                  
                   4395: * Environmental Queries::       
1.12      anton    4396: * Files::                       
                   4397: * Blocks::                      
                   4398: * Other I/O::                   
1.121     anton    4399: * OS command line arguments::   
1.78      anton    4400: * Locals::                      
                   4401: * Structures::                  
                   4402: * Object-oriented Forth::       
1.12      anton    4403: * Programming Tools::           
1.150     anton    4404: * C Interface::                 
1.12      anton    4405: * Assembler and Code Words::    
                   4406: * Threading Words::             
1.65      anton    4407: * Passing Commands to the OS::  
                   4408: * Keeping track of Time::       
                   4409: * Miscellaneous Words::         
1.1       anton    4410: @end menu
                   4411: 
1.65      anton    4412: @node Notation, Case insensitivity, Words, Words
1.1       anton    4413: @section Notation
                   4414: @cindex notation of glossary entries
                   4415: @cindex format of glossary entries
                   4416: @cindex glossary notation format
                   4417: @cindex word glossary entry format
                   4418: 
                   4419: The Forth words are described in this section in the glossary notation
1.67      anton    4420: that has become a de-facto standard for Forth texts:
1.1       anton    4421: 
                   4422: @format
1.29      crook    4423: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4424: @end format
1.29      crook    4425: @i{Description}
1.1       anton    4426: 
                   4427: @table @var
                   4428: @item word
1.28      crook    4429: The name of the word.
1.1       anton    4430: 
                   4431: @item Stack effect
                   4432: @cindex stack effect
1.29      crook    4433: The stack effect is written in the notation @code{@i{before} --
                   4434: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4435: stack entries before and after the execution of the word. The rest of
                   4436: the stack is not touched by the word. The top of stack is rightmost,
                   4437: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4438: uses a separate floating point stack, but a unified stack
1.29      crook    4439: notation. Also, return stack effects are not shown in @i{stack
                   4440: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4441: the type and/or the function of the item. See below for a discussion of
                   4442: the types.
                   4443: 
                   4444: All words have two stack effects: A compile-time stack effect and a
                   4445: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4446: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4447: this standard behaviour, or the word does other unusual things at
                   4448: compile time, both stack effects are shown; otherwise only the run-time
                   4449: stack effect is shown.
                   4450: 
1.211     anton    4451: Also note that in code templates or examples there can be comments in
                   4452: parentheses that display the stack picture at this point; there is no
                   4453: @code{--} in these places, because there is no before-after situation.
                   4454: 
1.1       anton    4455: @cindex pronounciation of words
                   4456: @item pronunciation
                   4457: How the word is pronounced.
                   4458: 
                   4459: @cindex wordset
1.67      anton    4460: @cindex environment wordset
1.1       anton    4461: @item wordset
1.21      crook    4462: The ANS Forth standard is divided into several word sets. A standard
                   4463: system need not support all of them. Therefore, in theory, the fewer
                   4464: word sets your program uses the more portable it will be. However, we
                   4465: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4466: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4467: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4468: describes words that will work in future releases of Gforth;
                   4469: @code{gforth-internal} words are more volatile. Environmental query
                   4470: strings are also displayed like words; you can recognize them by the
1.21      crook    4471: @code{environment} in the word set field.
1.1       anton    4472: 
                   4473: @item Description
                   4474: A description of the behaviour of the word.
                   4475: @end table
                   4476: 
                   4477: @cindex types of stack items
                   4478: @cindex stack item types
                   4479: The type of a stack item is specified by the character(s) the name
                   4480: starts with:
                   4481: 
                   4482: @table @code
                   4483: @item f
                   4484: @cindex @code{f}, stack item type
                   4485: Boolean flags, i.e. @code{false} or @code{true}.
                   4486: @item c
                   4487: @cindex @code{c}, stack item type
                   4488: Char
                   4489: @item w
                   4490: @cindex @code{w}, stack item type
                   4491: Cell, can contain an integer or an address
                   4492: @item n
                   4493: @cindex @code{n}, stack item type
                   4494: signed integer
                   4495: @item u
                   4496: @cindex @code{u}, stack item type
                   4497: unsigned integer
                   4498: @item d
                   4499: @cindex @code{d}, stack item type
                   4500: double sized signed integer
                   4501: @item ud
                   4502: @cindex @code{ud}, stack item type
                   4503: double sized unsigned integer
                   4504: @item r
                   4505: @cindex @code{r}, stack item type
                   4506: Float (on the FP stack)
1.21      crook    4507: @item a-
1.1       anton    4508: @cindex @code{a_}, stack item type
                   4509: Cell-aligned address
1.21      crook    4510: @item c-
1.1       anton    4511: @cindex @code{c_}, stack item type
                   4512: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4513: @item f-
1.1       anton    4514: @cindex @code{f_}, stack item type
                   4515: Float-aligned address
1.21      crook    4516: @item df-
1.1       anton    4517: @cindex @code{df_}, stack item type
                   4518: Address aligned for IEEE double precision float
1.21      crook    4519: @item sf-
1.1       anton    4520: @cindex @code{sf_}, stack item type
                   4521: Address aligned for IEEE single precision float
                   4522: @item xt
                   4523: @cindex @code{xt}, stack item type
                   4524: Execution token, same size as Cell
                   4525: @item wid
                   4526: @cindex @code{wid}, stack item type
1.21      crook    4527: Word list ID, same size as Cell
1.68      anton    4528: @item ior, wior
                   4529: @cindex ior type description
                   4530: @cindex wior type description
                   4531: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
1.1       anton    4532: @item f83name
                   4533: @cindex @code{f83name}, stack item type
                   4534: Pointer to a name structure
                   4535: @item "
                   4536: @cindex @code{"}, stack item type
1.12      anton    4537: string in the input stream (not on the stack). The terminating character
                   4538: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4539: quotes.
                   4540: @end table
                   4541: 
1.65      anton    4542: @comment ----------------------------------------------
                   4543: @node Case insensitivity, Comments, Notation, Words
                   4544: @section Case insensitivity
                   4545: @cindex case sensitivity
                   4546: @cindex upper and lower case
                   4547: 
                   4548: Gforth is case-insensitive; you can enter definitions and invoke
                   4549: Standard words using upper, lower or mixed case (however,
                   4550: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   4551: options}).
                   4552: 
                   4553: ANS Forth only @i{requires} implementations to recognise Standard words
                   4554: when they are typed entirely in upper case. Therefore, a Standard
                   4555: program must use upper case for all Standard words. You can use whatever
                   4556: case you like for words that you define, but in a Standard program you
                   4557: have to use the words in the same case that you defined them.
                   4558: 
                   4559: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   4560: wordlists, @pxref{Word Lists}).
                   4561: 
                   4562: Two people have asked how to convert Gforth to be case-sensitive; while
                   4563: we think this is a bad idea, you can change all wordlists into tables
                   4564: like this:
                   4565: 
                   4566: @example
                   4567: ' table-find forth-wordlist wordlist-map @ !
                   4568: @end example
                   4569: 
                   4570: Note that you now have to type the predefined words in the same case
                   4571: that we defined them, which are varying.  You may want to convert them
                   4572: to your favourite case before doing this operation (I won't explain how,
                   4573: because if you are even contemplating doing this, you'd better have
                   4574: enough knowledge of Forth systems to know this already).
                   4575: 
                   4576: @node Comments, Boolean Flags, Case insensitivity, Words
1.21      crook    4577: @section Comments
1.26      crook    4578: @cindex comments
1.21      crook    4579: 
1.29      crook    4580: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4581: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4582: 
1.44      crook    4583: 
1.23      crook    4584: doc-(
1.21      crook    4585: doc-\
1.23      crook    4586: doc-\G
1.21      crook    4587: 
1.44      crook    4588: 
1.21      crook    4589: @node Boolean Flags, Arithmetic, Comments, Words
                   4590: @section Boolean Flags
1.26      crook    4591: @cindex Boolean flags
1.21      crook    4592: 
                   4593: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4594: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4595: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4596: a cell that has @i{any} bit set as @code{true}.
1.67      anton    4597: @c on and off to Memory? 
                   4598: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44      crook    4599: 
1.21      crook    4600: doc-true
                   4601: doc-false
1.29      crook    4602: doc-on
                   4603: doc-off
1.21      crook    4604: 
1.44      crook    4605: 
1.21      crook    4606: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4607: @section Arithmetic
                   4608: @cindex arithmetic words
                   4609: 
                   4610: @cindex division with potentially negative operands
                   4611: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4612: overflow on addition or multiplication, you may hear about division by
                   4613: zero if you are lucky. The operator is written after the operands, but
                   4614: the operands are still in the original order. I.e., the infix @code{2-1}
                   4615: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4616: operators. If you perform division with potentially negative operands,
                   4617: you do not want to use @code{/} or @code{/mod} with its undefined
                   4618: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4619: former, @pxref{Mixed precision}).
1.26      crook    4620: @comment TODO discuss the different division forms and the std approach
1.1       anton    4621: 
                   4622: @menu
                   4623: * Single precision::            
1.67      anton    4624: * Double precision::            Double-cell integer arithmetic
1.1       anton    4625: * Bitwise operations::          
1.67      anton    4626: * Numeric comparison::          
1.29      crook    4627: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4628: * Floating Point::              
                   4629: @end menu
                   4630: 
1.67      anton    4631: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1       anton    4632: @subsection Single precision
                   4633: @cindex single precision arithmetic words
                   4634: 
1.67      anton    4635: @c !! cell undefined
                   4636: 
                   4637: By default, numbers in Forth are single-precision integers that are one
1.26      crook    4638: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4639: treat them. For the rules used by the text interpreter for recognising
                   4640: single-precision integers see @ref{Number Conversion}.
1.21      crook    4641: 
1.67      anton    4642: These words are all defined for signed operands, but some of them also
                   4643: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
                   4644: @code{*}.
1.44      crook    4645: 
1.1       anton    4646: doc-+
1.21      crook    4647: doc-1+
1.128     anton    4648: doc-under+
1.1       anton    4649: doc--
1.21      crook    4650: doc-1-
1.1       anton    4651: doc-*
                   4652: doc-/
                   4653: doc-mod
                   4654: doc-/mod
                   4655: doc-negate
                   4656: doc-abs
                   4657: doc-min
                   4658: doc-max
1.27      crook    4659: doc-floored
1.1       anton    4660: 
1.44      crook    4661: 
1.67      anton    4662: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21      crook    4663: @subsection Double precision
                   4664: @cindex double precision arithmetic words
                   4665: 
1.49      anton    4666: For the rules used by the text interpreter for
                   4667: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4668: 
                   4669: A double precision number is represented by a cell pair, with the most
1.67      anton    4670: significant cell at the TOS. It is trivial to convert an unsigned single
                   4671: to a double: simply push a @code{0} onto the TOS. Since numbers are
                   4672: represented by Gforth using 2's complement arithmetic, converting a
                   4673: signed single to a (signed) double requires sign-extension across the
                   4674: most significant cell. This can be achieved using @code{s>d}. The moral
                   4675: of the story is that you cannot convert a number without knowing whether
                   4676: it represents an unsigned or a signed number.
1.21      crook    4677: 
1.67      anton    4678: These words are all defined for signed operands, but some of them also
                   4679: work for unsigned numbers: @code{d+}, @code{d-}.
1.44      crook    4680: 
1.21      crook    4681: doc-s>d
1.67      anton    4682: doc-d>s
1.21      crook    4683: doc-d+
                   4684: doc-d-
                   4685: doc-dnegate
                   4686: doc-dabs
                   4687: doc-dmin
                   4688: doc-dmax
                   4689: 
1.44      crook    4690: 
1.67      anton    4691: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
                   4692: @subsection Bitwise operations
                   4693: @cindex bitwise operation words
                   4694: 
                   4695: 
                   4696: doc-and
                   4697: doc-or
                   4698: doc-xor
                   4699: doc-invert
                   4700: doc-lshift
                   4701: doc-rshift
                   4702: doc-2*
                   4703: doc-d2*
                   4704: doc-2/
                   4705: doc-d2/
                   4706: 
                   4707: 
                   4708: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21      crook    4709: @subsection Numeric comparison
                   4710: @cindex numeric comparison words
                   4711: 
1.67      anton    4712: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
                   4713: d0= d0<>}) work for for both signed and unsigned numbers.
1.44      crook    4714: 
1.28      crook    4715: doc-<
                   4716: doc-<=
                   4717: doc-<>
                   4718: doc-=
                   4719: doc->
                   4720: doc->=
                   4721: 
1.21      crook    4722: doc-0<
1.23      crook    4723: doc-0<=
1.21      crook    4724: doc-0<>
                   4725: doc-0=
1.23      crook    4726: doc-0>
                   4727: doc-0>=
1.28      crook    4728: 
                   4729: doc-u<
                   4730: doc-u<=
1.44      crook    4731: @c u<> and u= exist but are the same as <> and =
1.31      anton    4732: @c doc-u<>
                   4733: @c doc-u=
1.28      crook    4734: doc-u>
                   4735: doc-u>=
                   4736: 
                   4737: doc-within
                   4738: 
                   4739: doc-d<
                   4740: doc-d<=
                   4741: doc-d<>
                   4742: doc-d=
                   4743: doc-d>
                   4744: doc-d>=
1.23      crook    4745: 
1.21      crook    4746: doc-d0<
1.23      crook    4747: doc-d0<=
                   4748: doc-d0<>
1.21      crook    4749: doc-d0=
1.23      crook    4750: doc-d0>
                   4751: doc-d0>=
                   4752: 
1.21      crook    4753: doc-du<
1.28      crook    4754: doc-du<=
1.44      crook    4755: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4756: @c doc-du<>
                   4757: @c doc-du=
1.28      crook    4758: doc-du>
                   4759: doc-du>=
1.1       anton    4760: 
1.44      crook    4761: 
1.21      crook    4762: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4763: @subsection Mixed precision
                   4764: @cindex mixed precision arithmetic words
                   4765: 
1.44      crook    4766: 
1.1       anton    4767: doc-m+
                   4768: doc-*/
                   4769: doc-*/mod
                   4770: doc-m*
                   4771: doc-um*
                   4772: doc-m*/
                   4773: doc-um/mod
                   4774: doc-fm/mod
                   4775: doc-sm/rem
                   4776: 
1.44      crook    4777: 
1.21      crook    4778: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4779: @subsection Floating Point
                   4780: @cindex floating point arithmetic words
                   4781: 
1.49      anton    4782: For the rules used by the text interpreter for
                   4783: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4784: 
1.67      anton    4785: Gforth has a separate floating point stack, but the documentation uses
                   4786: the unified notation.@footnote{It's easy to generate the separate
                   4787: notation from that by just separating the floating-point numbers out:
                   4788: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
                   4789: r3 )}.}
1.1       anton    4790: 
                   4791: @cindex floating-point arithmetic, pitfalls
                   4792: Floating point numbers have a number of unpleasant surprises for the
1.190     anton    4793: unwary (e.g., floating point addition is not associative) and even a
                   4794: few for the wary. You should not use them unless you know what you are
                   4795: doing or you don't care that the results you get are totally bogus. If
                   4796: you want to learn about the problems of floating point numbers (and
                   4797: how to avoid them), you might start with @cite{David Goldberg,
                   4798: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
                   4799: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
                   4800: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1       anton    4801: 
1.44      crook    4802: 
1.21      crook    4803: doc-d>f
                   4804: doc-f>d
1.1       anton    4805: doc-f+
                   4806: doc-f-
                   4807: doc-f*
                   4808: doc-f/
                   4809: doc-fnegate
                   4810: doc-fabs
                   4811: doc-fmax
                   4812: doc-fmin
                   4813: doc-floor
                   4814: doc-fround
                   4815: doc-f**
                   4816: doc-fsqrt
                   4817: doc-fexp
                   4818: doc-fexpm1
                   4819: doc-fln
                   4820: doc-flnp1
                   4821: doc-flog
                   4822: doc-falog
1.32      anton    4823: doc-f2*
                   4824: doc-f2/
                   4825: doc-1/f
                   4826: doc-precision
                   4827: doc-set-precision
                   4828: 
                   4829: @cindex angles in trigonometric operations
                   4830: @cindex trigonometric operations
                   4831: Angles in floating point operations are given in radians (a full circle
                   4832: has 2 pi radians).
                   4833: 
1.1       anton    4834: doc-fsin
                   4835: doc-fcos
                   4836: doc-fsincos
                   4837: doc-ftan
                   4838: doc-fasin
                   4839: doc-facos
                   4840: doc-fatan
                   4841: doc-fatan2
                   4842: doc-fsinh
                   4843: doc-fcosh
                   4844: doc-ftanh
                   4845: doc-fasinh
                   4846: doc-facosh
                   4847: doc-fatanh
1.21      crook    4848: doc-pi
1.28      crook    4849: 
1.32      anton    4850: @cindex equality of floats
                   4851: @cindex floating-point comparisons
1.31      anton    4852: One particular problem with floating-point arithmetic is that comparison
                   4853: for equality often fails when you would expect it to succeed.  For this
                   4854: reason approximate equality is often preferred (but you still have to
1.67      anton    4855: know what you are doing).  Also note that IEEE NaNs may compare
1.68      anton    4856: differently from what you might expect.  The comparison words are:
1.31      anton    4857: 
                   4858: doc-f~rel
                   4859: doc-f~abs
1.68      anton    4860: doc-f~
1.31      anton    4861: doc-f=
                   4862: doc-f<>
                   4863: 
                   4864: doc-f<
                   4865: doc-f<=
                   4866: doc-f>
                   4867: doc-f>=
                   4868: 
1.21      crook    4869: doc-f0<
1.28      crook    4870: doc-f0<=
                   4871: doc-f0<>
1.21      crook    4872: doc-f0=
1.28      crook    4873: doc-f0>
                   4874: doc-f0>=
                   4875: 
1.1       anton    4876: 
                   4877: @node Stack Manipulation, Memory, Arithmetic, Words
                   4878: @section Stack Manipulation
                   4879: @cindex stack manipulation words
                   4880: 
                   4881: @cindex floating-point stack in the standard
1.21      crook    4882: Gforth maintains a number of separate stacks:
                   4883: 
1.29      crook    4884: @cindex data stack
                   4885: @cindex parameter stack
1.21      crook    4886: @itemize @bullet
                   4887: @item
1.29      crook    4888: A data stack (also known as the @dfn{parameter stack}) -- for
                   4889: characters, cells, addresses, and double cells.
1.21      crook    4890: 
1.29      crook    4891: @cindex floating-point stack
1.21      crook    4892: @item
1.44      crook    4893: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4894: 
1.29      crook    4895: @cindex return stack
1.21      crook    4896: @item
1.44      crook    4897: A return stack -- for holding the return addresses of colon
1.32      anton    4898: definitions and other (non-FP) data.
1.21      crook    4899: 
1.29      crook    4900: @cindex locals stack
1.21      crook    4901: @item
1.44      crook    4902: A locals stack -- for holding local variables.
1.21      crook    4903: @end itemize
                   4904: 
1.1       anton    4905: @menu
                   4906: * Data stack::                  
                   4907: * Floating point stack::        
                   4908: * Return stack::                
                   4909: * Locals stack::                
                   4910: * Stack pointer manipulation::  
                   4911: @end menu
                   4912: 
                   4913: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4914: @subsection Data stack
                   4915: @cindex data stack manipulation words
                   4916: @cindex stack manipulations words, data stack
                   4917: 
1.44      crook    4918: 
1.1       anton    4919: doc-drop
                   4920: doc-nip
                   4921: doc-dup
                   4922: doc-over
                   4923: doc-tuck
                   4924: doc-swap
1.21      crook    4925: doc-pick
1.1       anton    4926: doc-rot
                   4927: doc--rot
                   4928: doc-?dup
                   4929: doc-roll
                   4930: doc-2drop
                   4931: doc-2nip
                   4932: doc-2dup
                   4933: doc-2over
                   4934: doc-2tuck
                   4935: doc-2swap
                   4936: doc-2rot
                   4937: 
1.44      crook    4938: 
1.1       anton    4939: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4940: @subsection Floating point stack
                   4941: @cindex floating-point stack manipulation words
                   4942: @cindex stack manipulation words, floating-point stack
                   4943: 
1.32      anton    4944: Whilst every sane Forth has a separate floating-point stack, it is not
                   4945: strictly required; an ANS Forth system could theoretically keep
                   4946: floating-point numbers on the data stack. As an additional difficulty,
                   4947: you don't know how many cells a floating-point number takes. It is
                   4948: reportedly possible to write words in a way that they work also for a
                   4949: unified stack model, but we do not recommend trying it. Instead, just
                   4950: say that your program has an environmental dependency on a separate
                   4951: floating-point stack.
                   4952: 
                   4953: doc-floating-stack
                   4954: 
1.1       anton    4955: doc-fdrop
                   4956: doc-fnip
                   4957: doc-fdup
                   4958: doc-fover
                   4959: doc-ftuck
                   4960: doc-fswap
1.21      crook    4961: doc-fpick
1.1       anton    4962: doc-frot
                   4963: 
1.44      crook    4964: 
1.1       anton    4965: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4966: @subsection Return stack
                   4967: @cindex return stack manipulation words
                   4968: @cindex stack manipulation words, return stack
                   4969: 
1.32      anton    4970: @cindex return stack and locals
                   4971: @cindex locals and return stack
                   4972: A Forth system is allowed to keep local variables on the
                   4973: return stack. This is reasonable, as local variables usually eliminate
                   4974: the need to use the return stack explicitly. So, if you want to produce
                   4975: a standard compliant program and you are using local variables in a
                   4976: word, forget about return stack manipulations in that word (refer to the
                   4977: standard document for the exact rules).
                   4978: 
1.1       anton    4979: doc->r
                   4980: doc-r>
                   4981: doc-r@
                   4982: doc-rdrop
                   4983: doc-2>r
                   4984: doc-2r>
                   4985: doc-2r@
                   4986: doc-2rdrop
                   4987: 
1.44      crook    4988: 
1.1       anton    4989: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4990: @subsection Locals stack
                   4991: 
1.78      anton    4992: Gforth uses an extra locals stack.  It is described, along with the
                   4993: reasons for its existence, in @ref{Locals implementation}.
1.21      crook    4994: 
1.1       anton    4995: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4996: @subsection Stack pointer manipulation
                   4997: @cindex stack pointer manipulation words
                   4998: 
1.44      crook    4999: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    5000: doc-sp0
1.1       anton    5001: doc-sp@
                   5002: doc-sp!
1.21      crook    5003: doc-fp0
1.1       anton    5004: doc-fp@
                   5005: doc-fp!
1.21      crook    5006: doc-rp0
1.1       anton    5007: doc-rp@
                   5008: doc-rp!
1.21      crook    5009: doc-lp0
1.1       anton    5010: doc-lp@
                   5011: doc-lp!
                   5012: 
1.44      crook    5013: 
1.1       anton    5014: @node Memory, Control Structures, Stack Manipulation, Words
                   5015: @section Memory
1.26      crook    5016: @cindex memory words
1.1       anton    5017: 
1.32      anton    5018: @menu
                   5019: * Memory model::                
                   5020: * Dictionary allocation::       
                   5021: * Heap Allocation::             
                   5022: * Memory Access::               
                   5023: * Address arithmetic::          
                   5024: * Memory Blocks::               
                   5025: @end menu
                   5026: 
1.67      anton    5027: In addition to the standard Forth memory allocation words, there is also
                   5028: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   5029: garbage collector}.
                   5030: 
1.32      anton    5031: @node Memory model, Dictionary allocation, Memory, Memory
                   5032: @subsection ANS Forth and Gforth memory models
                   5033: 
                   5034: @c The ANS Forth description is a mess (e.g., is the heap part of
                   5035: @c the dictionary?), so let's not stick to closely with it.
                   5036: 
1.67      anton    5037: ANS Forth considers a Forth system as consisting of several address
                   5038: spaces, of which only @dfn{data space} is managed and accessible with
                   5039: the memory words.  Memory not necessarily in data space includes the
                   5040: stacks, the code (called code space) and the headers (called name
                   5041: space). In Gforth everything is in data space, but the code for the
                   5042: primitives is usually read-only.
1.32      anton    5043: 
                   5044: Data space is divided into a number of areas: The (data space portion of
                   5045: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   5046: refer to the search data structure embodied in word lists and headers,
                   5047: because it is used for looking up names, just as you would in a
                   5048: conventional dictionary.}, the heap, and a number of system-allocated
                   5049: buffers.
                   5050: 
1.68      anton    5051: @cindex address arithmetic restrictions, ANS vs. Gforth
                   5052: @cindex contiguous regions, ANS vs. Gforth
1.32      anton    5053: In ANS Forth data space is also divided into contiguous regions.  You
                   5054: can only use address arithmetic within a contiguous region, not between
                   5055: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    5056: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    5057: allocation}).
                   5058: 
                   5059: Gforth provides one big address space, and address arithmetic can be
                   5060: performed between any addresses. However, in the dictionary headers or
                   5061: code are interleaved with data, so almost the only contiguous data space
                   5062: regions there are those described by ANS Forth as contiguous; but you
                   5063: can be sure that the dictionary is allocated towards increasing
                   5064: addresses even between contiguous regions.  The memory order of
                   5065: allocations in the heap is platform-dependent (and possibly different
                   5066: from one run to the next).
                   5067: 
1.27      crook    5068: 
1.32      anton    5069: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   5070: @subsection Dictionary allocation
1.27      crook    5071: @cindex reserving data space
                   5072: @cindex data space - reserving some
                   5073: 
1.32      anton    5074: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   5075: you want to deallocate X, you also deallocate everything
                   5076: allocated after X.
                   5077: 
1.68      anton    5078: @cindex contiguous regions in dictionary allocation
1.32      anton    5079: The allocations using the words below are contiguous and grow the region
                   5080: towards increasing addresses.  Other words that allocate dictionary
                   5081: memory of any kind (i.e., defining words including @code{:noname}) end
                   5082: the contiguous region and start a new one.
                   5083: 
                   5084: In ANS Forth only @code{create}d words are guaranteed to produce an
                   5085: address that is the start of the following contiguous region.  In
                   5086: particular, the cell allocated by @code{variable} is not guaranteed to
                   5087: be contiguous with following @code{allot}ed memory.
                   5088: 
                   5089: You can deallocate memory by using @code{allot} with a negative argument
                   5090: (with some restrictions, see @code{allot}). For larger deallocations use
                   5091: @code{marker}.
1.27      crook    5092: 
1.29      crook    5093: 
1.27      crook    5094: doc-here
                   5095: doc-unused
                   5096: doc-allot
                   5097: doc-c,
1.29      crook    5098: doc-f,
1.27      crook    5099: doc-,
                   5100: doc-2,
                   5101: 
1.32      anton    5102: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   5103: course you should allocate memory in an aligned way, too. I.e., before
                   5104: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   5105: The words below align @code{here} if it is not already.  Basically it is
                   5106: only already aligned for a type, if the last allocation was a multiple
                   5107: of the size of this type and if @code{here} was aligned for this type
                   5108: before.
                   5109: 
                   5110: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   5111: ANS Forth (@code{maxalign}ed in Gforth).
                   5112: 
                   5113: doc-align
                   5114: doc-falign
                   5115: doc-sfalign
                   5116: doc-dfalign
                   5117: doc-maxalign
                   5118: doc-cfalign
                   5119: 
                   5120: 
                   5121: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   5122: @subsection Heap allocation
                   5123: @cindex heap allocation
                   5124: @cindex dynamic allocation of memory
                   5125: @cindex memory-allocation word set
                   5126: 
1.68      anton    5127: @cindex contiguous regions and heap allocation
1.32      anton    5128: Heap allocation supports deallocation of allocated memory in any
                   5129: order. Dictionary allocation is not affected by it (i.e., it does not
                   5130: end a contiguous region). In Gforth, these words are implemented using
                   5131: the standard C library calls malloc(), free() and resize().
                   5132: 
1.68      anton    5133: The memory region produced by one invocation of @code{allocate} or
                   5134: @code{resize} is internally contiguous.  There is no contiguity between
                   5135: such a region and any other region (including others allocated from the
                   5136: heap).
                   5137: 
1.32      anton    5138: doc-allocate
                   5139: doc-free
                   5140: doc-resize
                   5141: 
1.27      crook    5142: 
1.32      anton    5143: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    5144: @subsection Memory Access
                   5145: @cindex memory access words
                   5146: 
                   5147: doc-@
                   5148: doc-!
                   5149: doc-+!
                   5150: doc-c@
                   5151: doc-c!
                   5152: doc-2@
                   5153: doc-2!
                   5154: doc-f@
                   5155: doc-f!
                   5156: doc-sf@
                   5157: doc-sf!
                   5158: doc-df@
                   5159: doc-df!
1.144     anton    5160: doc-sw@
                   5161: doc-uw@
                   5162: doc-w!
                   5163: doc-sl@
                   5164: doc-ul@
                   5165: doc-l!
1.68      anton    5166: 
1.32      anton    5167: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   5168: @subsection Address arithmetic
1.1       anton    5169: @cindex address arithmetic words
                   5170: 
1.67      anton    5171: Address arithmetic is the foundation on which you can build data
                   5172: structures like arrays, records (@pxref{Structures}) and objects
                   5173: (@pxref{Object-oriented Forth}).
1.32      anton    5174: 
1.68      anton    5175: @cindex address unit
                   5176: @cindex au (address unit)
1.1       anton    5177: ANS Forth does not specify the sizes of the data types. Instead, it
                   5178: offers a number of words for computing sizes and doing address
1.29      crook    5179: arithmetic. Address arithmetic is performed in terms of address units
                   5180: (aus); on most systems the address unit is one byte. Note that a
                   5181: character may have more than one au, so @code{chars} is no noop (on
1.68      anton    5182: platforms where it is a noop, it compiles to nothing).
1.1       anton    5183: 
1.67      anton    5184: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
                   5185: you have the address of a cell, perform @code{1 cells +}, and you will
                   5186: have the address of the next cell.
                   5187: 
1.68      anton    5188: @cindex contiguous regions and address arithmetic
1.67      anton    5189: In ANS Forth you can perform address arithmetic only within a contiguous
                   5190: region, i.e., if you have an address into one region, you can only add
                   5191: and subtract such that the result is still within the region; you can
                   5192: only subtract or compare addresses from within the same contiguous
                   5193: region.  Reasons: several contiguous regions can be arranged in memory
                   5194: in any way; on segmented systems addresses may have unusual
                   5195: representations, such that address arithmetic only works within a
                   5196: region.  Gforth provides a few more guarantees (linear address space,
                   5197: dictionary grows upwards), but in general I have found it easy to stay
                   5198: within contiguous regions (exception: computing and comparing to the
                   5199: address just beyond the end of an array).
                   5200: 
1.1       anton    5201: @cindex alignment of addresses for types
                   5202: ANS Forth also defines words for aligning addresses for specific
                   5203: types. Many computers require that accesses to specific data types
                   5204: must only occur at specific addresses; e.g., that cells may only be
                   5205: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5206: accesses, it can usually perform aligned accesses faster. 
                   5207: 
                   5208: For the performance-conscious: alignment operations are usually only
                   5209: necessary during the definition of a data structure, not during the
                   5210: (more frequent) accesses to it.
                   5211: 
                   5212: ANS Forth defines no words for character-aligning addresses. This is not
                   5213: an oversight, but reflects the fact that addresses that are not
                   5214: char-aligned have no use in the standard and therefore will not be
                   5215: created.
                   5216: 
                   5217: @cindex @code{CREATE} and alignment
1.29      crook    5218: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5219: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5220: are aligned for all purposes.
                   5221: 
1.26      crook    5222: Note that the ANS Forth word @code{char} has nothing to do with address
                   5223: arithmetic.
1.1       anton    5224: 
1.44      crook    5225: 
1.1       anton    5226: doc-chars
                   5227: doc-char+
                   5228: doc-cells
                   5229: doc-cell+
                   5230: doc-cell
                   5231: doc-aligned
                   5232: doc-floats
                   5233: doc-float+
                   5234: doc-float
                   5235: doc-faligned
                   5236: doc-sfloats
                   5237: doc-sfloat+
                   5238: doc-sfaligned
                   5239: doc-dfloats
                   5240: doc-dfloat+
                   5241: doc-dfaligned
                   5242: doc-maxaligned
                   5243: doc-cfaligned
                   5244: doc-address-unit-bits
1.145     anton    5245: doc-/w
                   5246: doc-/l
1.44      crook    5247: 
1.32      anton    5248: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5249: @subsection Memory Blocks
                   5250: @cindex memory block words
1.27      crook    5251: @cindex character strings - moving and copying
                   5252: 
1.49      anton    5253: Memory blocks often represent character strings; For ways of storing
                   5254: character strings in memory see @ref{String Formats}.  For other
                   5255: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5256: 
1.67      anton    5257: A few of these words work on address unit blocks.  In that case, you
                   5258: usually have to insert @code{CHARS} before the word when working on
                   5259: character strings.  Most words work on character blocks, and expect a
                   5260: char-aligned address.
                   5261: 
                   5262: When copying characters between overlapping memory regions, use
                   5263: @code{chars move} or choose carefully between @code{cmove} and
                   5264: @code{cmove>}.
1.44      crook    5265: 
1.1       anton    5266: doc-move
                   5267: doc-erase
                   5268: doc-cmove
                   5269: doc-cmove>
                   5270: doc-fill
                   5271: doc-blank
1.21      crook    5272: doc-compare
1.111     anton    5273: doc-str=
                   5274: doc-str<
                   5275: doc-string-prefix?
1.21      crook    5276: doc-search
1.27      crook    5277: doc--trailing
                   5278: doc-/string
1.82      anton    5279: doc-bounds
1.141     anton    5280: doc-pad
1.111     anton    5281: 
1.27      crook    5282: @comment TODO examples
                   5283: 
1.1       anton    5284: 
1.26      crook    5285: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5286: @section Control Structures
                   5287: @cindex control structures
                   5288: 
1.33      anton    5289: Control structures in Forth cannot be used interpretively, only in a
                   5290: colon definition@footnote{To be precise, they have no interpretation
                   5291: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5292: not like this limitation, but have not seen a satisfying way around it
                   5293: yet, although many schemes have been proposed.
1.1       anton    5294: 
                   5295: @menu
1.33      anton    5296: * Selection::                   IF ... ELSE ... ENDIF
                   5297: * Simple Loops::                BEGIN ...
1.29      crook    5298: * Counted Loops::               DO
1.67      anton    5299: * Arbitrary control structures::  
                   5300: * Calls and returns::           
1.1       anton    5301: * Exception Handling::          
                   5302: @end menu
                   5303: 
                   5304: @node Selection, Simple Loops, Control Structures, Control Structures
                   5305: @subsection Selection
                   5306: @cindex selection control structures
                   5307: @cindex control structures for selection
                   5308: 
                   5309: @cindex @code{IF} control structure
                   5310: @example
1.29      crook    5311: @i{flag}
1.1       anton    5312: IF
1.29      crook    5313:   @i{code}
1.1       anton    5314: ENDIF
                   5315: @end example
1.21      crook    5316: @noindent
1.33      anton    5317: 
1.44      crook    5318: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5319: with any bit set represents truth) @i{code} is executed.
1.33      anton    5320: 
1.1       anton    5321: @example
1.29      crook    5322: @i{flag}
1.1       anton    5323: IF
1.29      crook    5324:   @i{code1}
1.1       anton    5325: ELSE
1.29      crook    5326:   @i{code2}
1.1       anton    5327: ENDIF
                   5328: @end example
                   5329: 
1.44      crook    5330: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5331: executed.
1.33      anton    5332: 
1.1       anton    5333: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5334: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5335: recommend using @code{ENDIF}, because it is less confusing for people
                   5336: who also know other languages (and is not prone to reinforcing negative
                   5337: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5338: system that only supplies @code{THEN} is simple:
                   5339: @example
1.82      anton    5340: : ENDIF   POSTPONE then ; immediate
1.1       anton    5341: @end example
                   5342: 
                   5343: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5344: (adv.)}  has the following meanings:
                   5345: @quotation
                   5346: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5347: (if you were there, then you saw them).
                   5348: @end quotation
                   5349: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5350: and many other programming languages has the meaning 3d.]
                   5351: 
1.21      crook    5352: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5353: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5354: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5355: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5356: @file{compat/control.fs}.
                   5357: 
                   5358: @cindex @code{CASE} control structure
                   5359: @example
1.213     anton    5360: @i{x}
1.1       anton    5361: CASE
1.213     anton    5362:   @i{x1} OF @i{code1} ENDOF
                   5363:   @i{x2} OF @i{code2} ENDOF
1.1       anton    5364:   @dots{}
1.213     anton    5365:   ( x ) @i{default-code} ( x )
1.131     anton    5366: ENDCASE ( )
1.1       anton    5367: @end example
                   5368: 
1.213     anton    5369: Executes the first @i{codei}, where the @i{xi} is equal to @i{x}.  If no
                   5370: @i{xi} matches, the optional @i{default-code} is executed. The optional
1.211     anton    5371: default case can be added by simply writing the code after the last
1.213     anton    5372: @code{ENDOF}. It may use @i{x}, which is on top of the stack, but must
                   5373: not consume it.  The value @i{x} is consumed by this construction
1.211     anton    5374: (either by an @code{OF} that matches, or by the @code{ENDCASE}, if no OF
                   5375: matches).  Example:
                   5376: 
                   5377: @example
1.213     anton    5378: : num-name ( n -- c-addr u )
1.211     anton    5379:  case
1.213     anton    5380:    0 of s" zero " endof
                   5381:    1 of s" one "  endof
                   5382:    2 of s" two "  endof
                   5383:    \ default case:
                   5384:    s" other number" 
                   5385:    rot \ get n on top so ENDCASE can drop it
1.211     anton    5386:  endcase ;
                   5387: @end example
1.1       anton    5388: 
1.232     anton    5389: You can also use (the non-standard) @code{?of} to use @code{case} as a
                   5390: general selection structure for more than two alternatives.
                   5391: @code{?Of} takes a flag.  Example:
                   5392: 
                   5393: @example
                   5394: : sgn ( n1 -- n2 )
                   5395:     \ sign function
                   5396:     case
                   5397:        dup 0< ?of drop -1 endof
                   5398:        dup 0> ?of drop 1 endof
                   5399:        dup \ n1=0 -> n2=0; dup an item, to be consumed by ENDCASE
                   5400:     endcase ;
                   5401: @end example
                   5402: 
1.69      anton    5403: @progstyle
1.131     anton    5404: To keep the code understandable, you should ensure that you change the
                   5405: stack in the same way (wrt. number and types of stack items consumed
1.232     anton    5406: and pushed) on all paths through a selection structure.
1.69      anton    5407: 
1.1       anton    5408: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5409: @subsection Simple Loops
                   5410: @cindex simple loops
                   5411: @cindex loops without count 
                   5412: 
                   5413: @cindex @code{WHILE} loop
                   5414: @example
                   5415: BEGIN
1.29      crook    5416:   @i{code1}
                   5417:   @i{flag}
1.1       anton    5418: WHILE
1.29      crook    5419:   @i{code2}
1.1       anton    5420: REPEAT
                   5421: @end example
                   5422: 
1.29      crook    5423: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5424: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5425: false, execution continues after the @code{REPEAT}.
                   5426: 
                   5427: @cindex @code{UNTIL} loop
                   5428: @example
                   5429: BEGIN
1.29      crook    5430:   @i{code}
                   5431:   @i{flag}
1.1       anton    5432: UNTIL
                   5433: @end example
                   5434: 
1.29      crook    5435: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5436: 
1.69      anton    5437: @progstyle
                   5438: To keep the code understandable, a complete iteration of the loop should
                   5439: not change the number and types of the items on the stacks.
                   5440: 
1.1       anton    5441: @cindex endless loop
                   5442: @cindex loops, endless
                   5443: @example
                   5444: BEGIN
1.29      crook    5445:   @i{code}
1.1       anton    5446: AGAIN
                   5447: @end example
                   5448: 
                   5449: This is an endless loop.
                   5450: 
                   5451: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5452: @subsection Counted Loops
                   5453: @cindex counted loops
                   5454: @cindex loops, counted
                   5455: @cindex @code{DO} loops
                   5456: 
                   5457: The basic counted loop is:
                   5458: @example
1.29      crook    5459: @i{limit} @i{start}
1.1       anton    5460: ?DO
1.29      crook    5461:   @i{body}
1.1       anton    5462: LOOP
                   5463: @end example
                   5464: 
1.29      crook    5465: This performs one iteration for every integer, starting from @i{start}
                   5466: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5467: accessed with @code{i}. For example, the loop:
1.1       anton    5468: @example
                   5469: 10 0 ?DO
                   5470:   i .
                   5471: LOOP
                   5472: @end example
1.21      crook    5473: @noindent
                   5474: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5475: 
1.1       anton    5476: The index of the innermost loop can be accessed with @code{i}, the index
                   5477: of the next loop with @code{j}, and the index of the third loop with
                   5478: @code{k}.
                   5479: 
1.44      crook    5480: 
1.1       anton    5481: doc-i
                   5482: doc-j
                   5483: doc-k
                   5484: 
1.44      crook    5485: 
1.1       anton    5486: The loop control data are kept on the return stack, so there are some
1.21      crook    5487: restrictions on mixing return stack accesses and counted loop words. In
                   5488: particuler, if you put values on the return stack outside the loop, you
                   5489: cannot read them inside the loop@footnote{well, not in a way that is
                   5490: portable.}. If you put values on the return stack within a loop, you
                   5491: have to remove them before the end of the loop and before accessing the
                   5492: index of the loop.
1.1       anton    5493: 
                   5494: There are several variations on the counted loop:
                   5495: 
1.21      crook    5496: @itemize @bullet
                   5497: @item
                   5498: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5499: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5500: 
                   5501: @example
                   5502: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5503: @end example
                   5504: prints @code{0 1 2 3}
                   5505: 
1.1       anton    5506: 
1.21      crook    5507: @item
                   5508: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5509: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5510: return stack so @code{EXIT} can get to its return address. For example:
                   5511: 
                   5512: @example
                   5513: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5514: @end example
                   5515: prints @code{0 1 2 3}
                   5516: 
                   5517: 
                   5518: @item
1.29      crook    5519: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5520: (and @code{LOOP} iterates until they become equal by wrap-around
                   5521: arithmetic). This behaviour is usually not what you want. Therefore,
                   5522: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5523: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5524: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5525: unsigned loop parameters.
                   5526: 
1.21      crook    5527: @item
                   5528: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5529: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5530: if you know that the loop is entered in any case. Such knowledge tends
                   5531: to become invalid during maintenance of a program, and then the
                   5532: @code{DO} will make trouble.
                   5533: 
                   5534: @item
1.29      crook    5535: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5536: index by @i{n} instead of by 1. The loop is terminated when the border
                   5537: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5538: 
1.21      crook    5539: @example
                   5540: 4 0 +DO  i .  2 +LOOP
                   5541: @end example
                   5542: @noindent
                   5543: prints @code{0 2}
                   5544: 
                   5545: @example
                   5546: 4 1 +DO  i .  2 +LOOP
                   5547: @end example
                   5548: @noindent
                   5549: prints @code{1 3}
1.1       anton    5550: 
1.68      anton    5551: @item
1.1       anton    5552: @cindex negative increment for counted loops
                   5553: @cindex counted loops with negative increment
1.29      crook    5554: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5555: 
1.21      crook    5556: @example
                   5557: -1 0 ?DO  i .  -1 +LOOP
                   5558: @end example
                   5559: @noindent
                   5560: prints @code{0 -1}
1.1       anton    5561: 
1.21      crook    5562: @example
                   5563: 0 0 ?DO  i .  -1 +LOOP
                   5564: @end example
                   5565: prints nothing.
1.1       anton    5566: 
1.29      crook    5567: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5568: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5569: index by @i{u} each iteration. The loop is terminated when the border
                   5570: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5571: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5572: 
1.21      crook    5573: @example
                   5574: -2 0 -DO  i .  1 -LOOP
                   5575: @end example
                   5576: @noindent
                   5577: prints @code{0 -1}
1.1       anton    5578: 
1.21      crook    5579: @example
                   5580: -1 0 -DO  i .  1 -LOOP
                   5581: @end example
                   5582: @noindent
                   5583: prints @code{0}
                   5584: 
                   5585: @example
                   5586: 0 0 -DO  i .  1 -LOOP
                   5587: @end example
                   5588: @noindent
                   5589: prints nothing.
1.1       anton    5590: 
1.21      crook    5591: @end itemize
1.1       anton    5592: 
                   5593: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5594: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5595: for these words that uses only standard words is provided in
                   5596: @file{compat/loops.fs}.
1.1       anton    5597: 
                   5598: 
                   5599: @cindex @code{FOR} loops
1.26      crook    5600: Another counted loop is:
1.1       anton    5601: @example
1.29      crook    5602: @i{n}
1.1       anton    5603: FOR
1.29      crook    5604:   @i{body}
1.1       anton    5605: NEXT
                   5606: @end example
                   5607: This is the preferred loop of native code compiler writers who are too
1.26      crook    5608: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5609: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5610: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5611: Forth systems may behave differently, even if they support @code{FOR}
                   5612: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5613: 
                   5614: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5615: @subsection Arbitrary control structures
                   5616: @cindex control structures, user-defined
                   5617: 
                   5618: @cindex control-flow stack
                   5619: ANS Forth permits and supports using control structures in a non-nested
                   5620: way. Information about incomplete control structures is stored on the
                   5621: control-flow stack. This stack may be implemented on the Forth data
                   5622: stack, and this is what we have done in Gforth.
                   5623: 
                   5624: @cindex @code{orig}, control-flow stack item
                   5625: @cindex @code{dest}, control-flow stack item
                   5626: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5627: entry represents a backward branch target. A few words are the basis for
                   5628: building any control structure possible (except control structures that
                   5629: need storage, like calls, coroutines, and backtracking).
                   5630: 
1.44      crook    5631: 
1.1       anton    5632: doc-if
                   5633: doc-ahead
                   5634: doc-then
                   5635: doc-begin
                   5636: doc-until
                   5637: doc-again
                   5638: doc-cs-pick
                   5639: doc-cs-roll
                   5640: 
1.44      crook    5641: 
1.21      crook    5642: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5643: manipulate the control-flow stack in a portable way. Without them, you
                   5644: would need to know how many stack items are occupied by a control-flow
                   5645: entry (many systems use one cell. In Gforth they currently take three,
                   5646: but this may change in the future).
                   5647: 
1.1       anton    5648: Some standard control structure words are built from these words:
                   5649: 
1.44      crook    5650: 
1.1       anton    5651: doc-else
                   5652: doc-while
                   5653: doc-repeat
                   5654: 
1.44      crook    5655: 
                   5656: @noindent
1.1       anton    5657: Gforth adds some more control-structure words:
                   5658: 
1.44      crook    5659: 
1.1       anton    5660: doc-endif
                   5661: doc-?dup-if
                   5662: doc-?dup-0=-if
                   5663: 
1.44      crook    5664: 
                   5665: @noindent
1.1       anton    5666: Counted loop words constitute a separate group of words:
                   5667: 
1.44      crook    5668: 
1.1       anton    5669: doc-?do
                   5670: doc-+do
                   5671: doc-u+do
                   5672: doc--do
                   5673: doc-u-do
                   5674: doc-do
                   5675: doc-for
                   5676: doc-loop
                   5677: doc-+loop
                   5678: doc--loop
                   5679: doc-next
                   5680: doc-leave
                   5681: doc-?leave
                   5682: doc-unloop
                   5683: doc-done
                   5684: 
1.44      crook    5685: 
1.21      crook    5686: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5687: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5688: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5689: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5690: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5691: resolved (by using one of the loop-ending words or @code{DONE}).
                   5692: 
1.44      crook    5693: @noindent
1.26      crook    5694: Another group of control structure words are:
1.1       anton    5695: 
1.44      crook    5696: 
1.1       anton    5697: doc-case
                   5698: doc-endcase
                   5699: doc-of
1.232     anton    5700: doc-?ofx
1.1       anton    5701: doc-endof
                   5702: 
1.44      crook    5703: 
1.21      crook    5704: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5705: @code{CS-ROLL}.
1.1       anton    5706: 
                   5707: @subsubsection Programming Style
1.47      crook    5708: @cindex control structures programming style
                   5709: @cindex programming style, arbitrary control structures
1.1       anton    5710: 
                   5711: In order to ensure readability we recommend that you do not create
                   5712: arbitrary control structures directly, but define new control structure
                   5713: words for the control structure you want and use these words in your
1.26      crook    5714: program. For example, instead of writing:
1.1       anton    5715: 
                   5716: @example
1.26      crook    5717: BEGIN
1.1       anton    5718:   ...
1.26      crook    5719: IF [ 1 CS-ROLL ]
1.1       anton    5720:   ...
1.26      crook    5721: AGAIN THEN
1.1       anton    5722: @end example
                   5723: 
1.21      crook    5724: @noindent
1.1       anton    5725: we recommend defining control structure words, e.g.,
                   5726: 
                   5727: @example
1.26      crook    5728: : WHILE ( DEST -- ORIG DEST )
                   5729:  POSTPONE IF
                   5730:  1 CS-ROLL ; immediate
                   5731: 
                   5732: : REPEAT ( orig dest -- )
                   5733:  POSTPONE AGAIN
                   5734:  POSTPONE THEN ; immediate
1.1       anton    5735: @end example
                   5736: 
1.21      crook    5737: @noindent
1.1       anton    5738: and then using these to create the control structure:
                   5739: 
                   5740: @example
1.26      crook    5741: BEGIN
1.1       anton    5742:   ...
1.26      crook    5743: WHILE
1.1       anton    5744:   ...
1.26      crook    5745: REPEAT
1.1       anton    5746: @end example
                   5747: 
                   5748: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5749: @code{WHILE} are predefined, so in this example it would not be
                   5750: necessary to define them.
                   5751: 
                   5752: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5753: @subsection Calls and returns
                   5754: @cindex calling a definition
                   5755: @cindex returning from a definition
                   5756: 
1.3       anton    5757: @cindex recursive definitions
                   5758: A definition can be called simply be writing the name of the definition
1.26      crook    5759: to be called. Normally a definition is invisible during its own
1.3       anton    5760: definition. If you want to write a directly recursive definition, you
1.26      crook    5761: can use @code{recursive} to make the current definition visible, or
                   5762: @code{recurse} to call the current definition directly.
1.3       anton    5763: 
1.44      crook    5764: 
1.3       anton    5765: doc-recursive
                   5766: doc-recurse
                   5767: 
1.44      crook    5768: 
1.21      crook    5769: @comment TODO add example of the two recursion methods
1.12      anton    5770: @quotation
                   5771: @progstyle
                   5772: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5773: definition by name is more descriptive (if the name is well-chosen) than
                   5774: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5775: implementation, it is much better to read (and think) ``now sort the
                   5776: partitions'' than to read ``now do a recursive call''.
                   5777: @end quotation
1.3       anton    5778: 
1.29      crook    5779: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5780: 
                   5781: @example
1.28      crook    5782: Defer foo
1.3       anton    5783: 
                   5784: : bar ( ... -- ... )
                   5785:  ... foo ... ;
                   5786: 
                   5787: :noname ( ... -- ... )
                   5788:  ... bar ... ;
                   5789: IS foo
                   5790: @end example
                   5791: 
1.170     pazsan   5792: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33      anton    5793: 
1.26      crook    5794: The current definition returns control to the calling definition when
1.33      anton    5795: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5796: 
                   5797: doc-exit
                   5798: doc-;s
                   5799: 
1.44      crook    5800: 
1.1       anton    5801: @node Exception Handling,  , Calls and returns, Control Structures
                   5802: @subsection Exception Handling
1.26      crook    5803: @cindex exceptions
1.1       anton    5804: 
1.68      anton    5805: @c quit is a very bad idea for error handling, 
                   5806: @c because it does not translate into a THROW
                   5807: @c it also does not belong into this chapter
                   5808: 
                   5809: If a word detects an error condition that it cannot handle, it can
                   5810: @code{throw} an exception.  In the simplest case, this will terminate
                   5811: your program, and report an appropriate error.
1.21      crook    5812: 
1.68      anton    5813: doc-throw
1.1       anton    5814: 
1.69      anton    5815: @code{Throw} consumes a cell-sized error number on the stack. There are
                   5816: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
                   5817: Gforth (and most other systems) you can use the iors produced by various
                   5818: words as error numbers (e.g., a typical use of @code{allocate} is
                   5819: @code{allocate throw}).  Gforth also provides the word @code{exception}
                   5820: to define your own error numbers (with decent error reporting); an ANS
                   5821: Forth version of this word (but without the error messages) is available
                   5822: in @code{compat/except.fs}.  And finally, you can use your own error
1.68      anton    5823: numbers (anything outside the range -4095..0), but won't get nice error
                   5824: messages, only numbers.  For example, try:
                   5825: 
                   5826: @example
1.69      anton    5827: -10 throw                    \ ANS defined
                   5828: -267 throw                   \ system defined
                   5829: s" my error" exception throw \ user defined
                   5830: 7 throw                      \ arbitrary number
1.68      anton    5831: @end example
                   5832: 
                   5833: doc---exception-exception
1.1       anton    5834: 
1.69      anton    5835: A common idiom to @code{THROW} a specific error if a flag is true is
                   5836: this:
                   5837: 
                   5838: @example
                   5839: @code{( flag ) 0<> @i{errno} and throw}
                   5840: @end example
                   5841: 
                   5842: Your program can provide exception handlers to catch exceptions.  An
                   5843: exception handler can be used to correct the problem, or to clean up
                   5844: some data structures and just throw the exception to the next exception
                   5845: handler.  Note that @code{throw} jumps to the dynamically innermost
                   5846: exception handler.  The system's exception handler is outermost, and just
                   5847: prints an error and restarts command-line interpretation (or, in batch
                   5848: mode (i.e., while processing the shell command line), leaves Gforth).
1.1       anton    5849: 
1.68      anton    5850: The ANS Forth way to catch exceptions is @code{catch}:
1.1       anton    5851: 
1.68      anton    5852: doc-catch
1.160     anton    5853: doc-nothrow
1.68      anton    5854: 
                   5855: The most common use of exception handlers is to clean up the state when
                   5856: an error happens.  E.g.,
1.1       anton    5857: 
1.26      crook    5858: @example
1.68      anton    5859: base @ >r hex \ actually the hex should be inside foo, or we h
                   5860: ['] foo catch ( nerror|0 )
                   5861: r> base !
1.69      anton    5862: ( nerror|0 ) throw \ pass it on
1.26      crook    5863: @end example
1.1       anton    5864: 
1.69      anton    5865: A use of @code{catch} for handling the error @code{myerror} might look
                   5866: like this:
1.44      crook    5867: 
1.68      anton    5868: @example
1.69      anton    5869: ['] foo catch
                   5870: CASE
1.160     anton    5871:   myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5872:   dup throw \ default: pass other errors on, do nothing on non-errors
                   5873: ENDCASE
1.68      anton    5874: @end example
1.44      crook    5875: 
1.68      anton    5876: Having to wrap the code into a separate word is often cumbersome,
                   5877: therefore Gforth provides an alternative syntax:
1.1       anton    5878: 
                   5879: @example
1.69      anton    5880: TRY
1.68      anton    5881:   @i{code1}
1.172     anton    5882:   IFERROR
                   5883:     @i{code2}
                   5884:   THEN
                   5885:   @i{code3}
1.69      anton    5886: ENDTRY
1.1       anton    5887: @end example
                   5888: 
1.172     anton    5889: This performs @i{code1}.  If @i{code1} completes normally, execution
1.201     anton    5890: continues with @i{code3}.  If there is an exception in @i{code1} or
                   5891: before @code{endtry}, the stacks are reset to the depth during
1.172     anton    5892: @code{try}, the throw value is pushed on the data stack, and execution
1.239     anton    5893: continues at @i{code2}, and finally falls through to @i{code3}.
1.26      crook    5894: 
1.68      anton    5895: doc-try
                   5896: doc-endtry
1.172     anton    5897: doc-iferror
                   5898: 
                   5899: If you don't need @i{code2}, you can write @code{restore} instead of
                   5900: @code{iferror then}:
                   5901: 
                   5902: @example
                   5903: TRY
                   5904:   @i{code1}
                   5905: RESTORE
                   5906:   @i{code3}
                   5907: ENDTRY
                   5908: @end example
1.26      crook    5909: 
1.172     anton    5910: @cindex unwind-protect
1.69      anton    5911: The cleanup example from above in this syntax:
1.26      crook    5912: 
1.68      anton    5913: @example
1.174     anton    5914: base @@ @{ oldbase @}
1.172     anton    5915: TRY
1.68      anton    5916:   hex foo \ now the hex is placed correctly
1.69      anton    5917:   0       \ value for throw
1.172     anton    5918: RESTORE
                   5919:   oldbase base !
                   5920: ENDTRY
                   5921: throw
1.1       anton    5922: @end example
                   5923: 
1.172     anton    5924: An additional advantage of this variant is that an exception between
                   5925: @code{restore} and @code{endtry} (e.g., from the user pressing
                   5926: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
                   5927: so the base will be restored under all circumstances.
                   5928: 
                   5929: However, you have to ensure that this code does not cause an exception
                   5930: itself, otherwise the @code{iferror}/@code{restore} code will loop.
                   5931: Moreover, you should also make sure that the stack contents needed by
                   5932: the @code{iferror}/@code{restore} code exist everywhere between
                   5933: @code{try} and @code{endtry}; in our example this is achived by
                   5934: putting the data in a local before the @code{try} (you cannot use the
                   5935: return stack because the exception frame (@i{sys1}) is in the way
                   5936: there).
                   5937: 
                   5938: This kind of usage corresponds to Lisp's @code{unwind-protect}.
                   5939: 
                   5940: @cindex @code{recover} (old Gforth versions)
                   5941: If you do not want this exception-restarting behaviour, you achieve
                   5942: this as follows:
                   5943: 
                   5944: @example
                   5945: TRY
                   5946:   @i{code1}
                   5947: ENDTRY-IFERROR
                   5948:   @i{code2}
                   5949: THEN
                   5950: @end example
                   5951: 
                   5952: If there is an exception in @i{code1}, then @i{code2} is executed,
                   5953: otherwise execution continues behind the @code{then} (or in a possible
                   5954: @code{else} branch).  This corresponds to the construct
                   5955: 
                   5956: @example
                   5957: TRY
                   5958:   @i{code1}
                   5959: RECOVER
                   5960:   @i{code2}
                   5961: ENDTRY
                   5962: @end example
                   5963: 
                   5964: in Gforth before version 0.7.  So you can directly replace
                   5965: @code{recover}-using code; however, we recommend that you check if it
                   5966: would not be better to use one of the other @code{try} variants while
                   5967: you are at it.
                   5968: 
1.173     anton    5969: To ease the transition, Gforth provides two compatibility files:
                   5970: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
                   5971: ... then} syntax (but not @code{iferror} or @code{restore}) for old
                   5972: systems; @file{recover-endtry.fs} provides the @code{try ... recover
                   5973: ... endtry} syntax on new systems, so you can use that file as a
                   5974: stopgap to run old programs.  Both files work on any system (they just
                   5975: do nothing if the system already has the syntax it implements), so you
                   5976: can unconditionally @code{require} one of these files, even if you use
                   5977: a mix old and new systems.
                   5978: 
1.172     anton    5979: doc-restore
                   5980: doc-endtry-iferror
                   5981: 
                   5982: Here's the error handling example:
1.1       anton    5983: 
1.68      anton    5984: @example
1.69      anton    5985: TRY
1.68      anton    5986:   foo
1.172     anton    5987: ENDTRY-IFERROR
1.69      anton    5988:   CASE
1.160     anton    5989:     myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5990:     throw \ pass other errors on
                   5991:   ENDCASE
1.172     anton    5992: THEN
1.68      anton    5993: @end example
1.1       anton    5994: 
1.69      anton    5995: @progstyle
                   5996: As usual, you should ensure that the stack depth is statically known at
                   5997: the end: either after the @code{throw} for passing on errors, or after
                   5998: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
                   5999: selection construct for handling the error).
                   6000: 
1.68      anton    6001: There are two alternatives to @code{throw}: @code{Abort"} is conditional
                   6002: and you can provide an error message.  @code{Abort} just produces an
                   6003: ``Aborted'' error.
1.1       anton    6004: 
1.68      anton    6005: The problem with these words is that exception handlers cannot
                   6006: differentiate between different @code{abort"}s; they just look like
                   6007: @code{-2 throw} to them (the error message cannot be accessed by
                   6008: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
                   6009: exception handlers.
1.44      crook    6010: 
1.68      anton    6011: doc-abort"
1.26      crook    6012: doc-abort
1.29      crook    6013: 
                   6014: 
1.44      crook    6015: 
1.29      crook    6016: @c -------------------------------------------------------------
1.47      crook    6017: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    6018: @section Defining Words
                   6019: @cindex defining words
                   6020: 
1.47      crook    6021: Defining words are used to extend Forth by creating new entries in the dictionary.
                   6022: 
1.29      crook    6023: @menu
1.67      anton    6024: * CREATE::                      
1.44      crook    6025: * Variables::                   Variables and user variables
1.67      anton    6026: * Constants::                   
1.44      crook    6027: * Values::                      Initialised variables
1.67      anton    6028: * Colon Definitions::           
1.44      crook    6029: * Anonymous Definitions::       Definitions without names
1.236     anton    6030: * Quotations::                  
1.69      anton    6031: * Supplying names::             Passing definition names as strings
1.67      anton    6032: * User-defined Defining Words::  
1.170     pazsan   6033: * Deferred Words::              Allow forward references
1.67      anton    6034: * Aliases::                     
1.29      crook    6035: @end menu
                   6036: 
1.44      crook    6037: @node CREATE, Variables, Defining Words, Defining Words
                   6038: @subsection @code{CREATE}
1.29      crook    6039: @cindex simple defining words
                   6040: @cindex defining words, simple
                   6041: 
                   6042: Defining words are used to create new entries in the dictionary. The
                   6043: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   6044: this:
                   6045: 
                   6046: @example
                   6047: CREATE new-word1
                   6048: @end example
                   6049: 
1.69      anton    6050: @code{CREATE} is a parsing word, i.e., it takes an argument from the
                   6051: input stream (@code{new-word1} in our example).  It generates a
                   6052: dictionary entry for @code{new-word1}. When @code{new-word1} is
                   6053: executed, all that it does is leave an address on the stack. The address
                   6054: represents the value of the data space pointer (@code{HERE}) at the time
                   6055: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
                   6056: associating a name with the address of a region of memory.
1.29      crook    6057: 
1.34      anton    6058: doc-create
                   6059: 
1.69      anton    6060: Note that in ANS Forth guarantees only for @code{create} that its body
                   6061: is in dictionary data space (i.e., where @code{here}, @code{allot}
                   6062: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
                   6063: @code{create}d words can be modified with @code{does>}
                   6064: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
                   6065: can only be applied to @code{create}d words.
                   6066: 
1.29      crook    6067: By extending this example to reserve some memory in data space, we end
1.69      anton    6068: up with something like a @i{variable}. Here are two different ways to do
                   6069: it:
1.29      crook    6070: 
                   6071: @example
                   6072: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   6073: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   6074: @end example
                   6075: 
                   6076: The variable can be examined and modified using @code{@@} (``fetch'') and
                   6077: @code{!} (``store'') like this:
                   6078: 
                   6079: @example
                   6080: new-word2 @@ .      \ get address, fetch from it and display
                   6081: 1234 new-word2 !   \ new value, get address, store to it
                   6082: @end example
                   6083: 
1.44      crook    6084: @cindex arrays
                   6085: A similar mechanism can be used to create arrays. For example, an
                   6086: 80-character text input buffer:
1.29      crook    6087: 
                   6088: @example
1.44      crook    6089: CREATE text-buf 80 chars allot
                   6090: 
1.168     anton    6091: text-buf 0 chars + c@@ \ the 1st character (offset 0)
                   6092: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44      crook    6093: @end example
1.29      crook    6094: 
1.44      crook    6095: You can build arbitrarily complex data structures by allocating
1.49      anton    6096: appropriate areas of memory. For further discussions of this, and to
1.66      anton    6097: learn about some Gforth tools that make it easier,
1.49      anton    6098: @xref{Structures}.
1.44      crook    6099: 
                   6100: 
                   6101: @node Variables, Constants, CREATE, Defining Words
                   6102: @subsection Variables
                   6103: @cindex variables
                   6104: 
                   6105: The previous section showed how a sequence of commands could be used to
                   6106: generate a variable.  As a final refinement, the whole code sequence can
                   6107: be wrapped up in a defining word (pre-empting the subject of the next
                   6108: section), making it easier to create new variables:
                   6109: 
                   6110: @example
                   6111: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   6112: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   6113: 
                   6114: myvariableX foo \ variable foo starts off with an unknown value
                   6115: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    6116: 
                   6117: 45 3 * foo !   \ set foo to 135
                   6118: 1234 joe !     \ set joe to 1234
                   6119: 3 joe +!       \ increment joe by 3.. to 1237
                   6120: @end example
                   6121: 
                   6122: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    6123: Forth already has a definition @code{Variable}. ANS Forth does not
1.69      anton    6124: guarantee that a @code{Variable} is initialised when it is created
                   6125: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
                   6126: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
                   6127: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    6128: @code{fvariable} for double and floating-point variables, respectively
1.69      anton    6129: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47      crook    6130: store a boolean, you can use @code{on} and @code{off} to toggle its
                   6131: state.
1.29      crook    6132: 
1.34      anton    6133: doc-variable
                   6134: doc-2variable
                   6135: doc-fvariable
                   6136: 
1.29      crook    6137: @cindex user variables
                   6138: @cindex user space
                   6139: The defining word @code{User} behaves in the same way as @code{Variable}.
                   6140: The difference is that it reserves space in @i{user (data) space} rather
                   6141: than normal data space. In a Forth system that has a multi-tasker, each
                   6142: task has its own set of user variables.
                   6143: 
1.34      anton    6144: doc-user
1.67      anton    6145: @c doc-udp
                   6146: @c doc-uallot
1.34      anton    6147: 
1.29      crook    6148: @comment TODO is that stuff about user variables strictly correct? Is it
                   6149: @comment just terminal tasks that have user variables?
                   6150: @comment should document tasker.fs (with some examples) elsewhere
                   6151: @comment in this manual, then expand on user space and user variables.
                   6152: 
1.44      crook    6153: @node Constants, Values, Variables, Defining Words
                   6154: @subsection Constants
                   6155: @cindex constants
                   6156: 
                   6157: @code{Constant} allows you to declare a fixed value and refer to it by
                   6158: name. For example:
1.29      crook    6159: 
                   6160: @example
                   6161: 12 Constant INCHES-PER-FOOT
                   6162: 3E+08 fconstant SPEED-O-LIGHT
                   6163: @end example
                   6164: 
                   6165: A @code{Variable} can be both read and written, so its run-time
                   6166: behaviour is to supply an address through which its current value can be
                   6167: manipulated. In contrast, the value of a @code{Constant} cannot be
                   6168: changed once it has been declared@footnote{Well, often it can be -- but
                   6169: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   6170: on).} so it's not necessary to supply the address -- it is more
                   6171: efficient to return the value of the constant directly. That's exactly
                   6172: what happens; the run-time effect of a constant is to put its value on
1.49      anton    6173: the top of the stack (You can find one
                   6174: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    6175: 
1.69      anton    6176: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29      crook    6177: double and floating-point constants, respectively.
                   6178: 
1.34      anton    6179: doc-constant
                   6180: doc-2constant
                   6181: doc-fconstant
                   6182: 
                   6183: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    6184: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   6185: @c constant, use it and then delete the definition of the constant..
1.69      anton    6186: 
                   6187: @c anton->An ANS Forth system can compile a constant to a literal; On
                   6188: @c decompilation you would see only the number, just as if it had been used
                   6189: @c in the first place.  The word will stay, of course, but it will only be
                   6190: @c used by the text interpreter (no run-time duties, except when it is 
                   6191: @c POSTPONEd or somesuch).
                   6192: 
                   6193: @c nac:
1.44      crook    6194: @c I agree that it's rather deep, but IMO it is an important difference
                   6195: @c relative to other programming languages.. often it's annoying: it
                   6196: @c certainly changes my programming style relative to C.
                   6197: 
1.69      anton    6198: @c anton: In what way?
                   6199: 
1.29      crook    6200: Constants in Forth behave differently from their equivalents in other
                   6201: programming languages. In other languages, a constant (such as an EQU in
                   6202: assembler or a #define in C) only exists at compile-time; in the
                   6203: executable program the constant has been translated into an absolute
                   6204: number and, unless you are using a symbolic debugger, it's impossible to
                   6205: know what abstract thing that number represents. In Forth a constant has
1.44      crook    6206: an entry in the header space and remains there after the code that uses
                   6207: it has been defined. In fact, it must remain in the dictionary since it
                   6208: has run-time duties to perform. For example:
1.29      crook    6209: 
                   6210: @example
                   6211: 12 Constant INCHES-PER-FOOT
                   6212: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   6213: @end example
                   6214: 
                   6215: @cindex in-lining of constants
                   6216: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   6217: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   6218: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   6219: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   6220: attempt to optimise constants by in-lining them where they are used. You
                   6221: can force Gforth to in-line a constant like this:
                   6222: 
                   6223: @example
                   6224: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   6225: @end example
                   6226: 
                   6227: If you use @code{see} to decompile @i{this} version of
                   6228: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    6229: longer present. To understand how this works, read
                   6230: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    6231: 
                   6232: In-lining constants in this way might improve execution time
                   6233: fractionally, and can ensure that a constant is now only referenced at
                   6234: compile-time. However, the definition of the constant still remains in
                   6235: the dictionary. Some Forth compilers provide a mechanism for controlling
                   6236: a second dictionary for holding transient words such that this second
                   6237: dictionary can be deleted later in order to recover memory
                   6238: space. However, there is no standard way of doing this.
                   6239: 
                   6240: 
1.44      crook    6241: @node Values, Colon Definitions, Constants, Defining Words
                   6242: @subsection Values
                   6243: @cindex values
1.34      anton    6244: 
1.69      anton    6245: A @code{Value} behaves like a @code{Constant}, but it can be changed.
                   6246: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
                   6247: (not in ANS Forth) you can access (and change) a @code{value} also with
                   6248: @code{>body}.
                   6249: 
                   6250: Here are some
                   6251: examples:
1.29      crook    6252: 
                   6253: @example
1.69      anton    6254: 12 Value APPLES     \ Define APPLES with an initial value of 12
                   6255: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
                   6256: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
                   6257: APPLES              \ puts 35 on the top of the stack.
1.29      crook    6258: @end example
                   6259: 
1.44      crook    6260: doc-value
                   6261: doc-to
1.29      crook    6262: 
1.35      anton    6263: 
1.69      anton    6264: 
1.44      crook    6265: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   6266: @subsection Colon Definitions
                   6267: @cindex colon definitions
1.35      anton    6268: 
                   6269: @example
1.44      crook    6270: : name ( ... -- ... )
                   6271:     word1 word2 word3 ;
1.29      crook    6272: @end example
                   6273: 
1.44      crook    6274: @noindent
                   6275: Creates a word called @code{name} that, upon execution, executes
                   6276: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    6277: 
1.49      anton    6278: The explanation above is somewhat superficial. For simple examples of
                   6279: colon definitions see @ref{Your first definition}.  For an in-depth
1.66      anton    6280: discussion of some of the issues involved, @xref{Interpretation and
1.49      anton    6281: Compilation Semantics}.
1.29      crook    6282: 
1.44      crook    6283: doc-:
                   6284: doc-;
1.1       anton    6285: 
1.34      anton    6286: 
1.236     anton    6287: @node Anonymous Definitions, Quotations, Colon Definitions, Defining Words
1.44      crook    6288: @subsection Anonymous Definitions
                   6289: @cindex colon definitions
                   6290: @cindex defining words without name
1.34      anton    6291: 
1.44      crook    6292: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   6293: name. You can do this with:
1.1       anton    6294: 
1.44      crook    6295: doc-:noname
1.1       anton    6296: 
1.44      crook    6297: This leaves the execution token for the word on the stack after the
                   6298: closing @code{;}. Here's an example in which a deferred word is
                   6299: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6300: 
1.29      crook    6301: @example
1.44      crook    6302: Defer deferred
                   6303: :noname ( ... -- ... )
                   6304:   ... ;
                   6305: IS deferred
1.29      crook    6306: @end example
1.26      crook    6307: 
1.44      crook    6308: @noindent
                   6309: Gforth provides an alternative way of doing this, using two separate
                   6310: words:
1.27      crook    6311: 
1.44      crook    6312: doc-noname
                   6313: @cindex execution token of last defined word
1.116     anton    6314: doc-latestxt
1.1       anton    6315: 
1.44      crook    6316: @noindent
                   6317: The previous example can be rewritten using @code{noname} and
1.116     anton    6318: @code{latestxt}:
1.1       anton    6319: 
1.26      crook    6320: @example
1.44      crook    6321: Defer deferred
                   6322: noname : ( ... -- ... )
                   6323:   ... ;
1.116     anton    6324: latestxt IS deferred
1.26      crook    6325: @end example
1.1       anton    6326: 
1.29      crook    6327: @noindent
1.44      crook    6328: @code{noname} works with any defining word, not just @code{:}.
                   6329: 
1.116     anton    6330: @code{latestxt} also works when the last word was not defined as
1.71      anton    6331: @code{noname}.  It does not work for combined words, though.  It also has
                   6332: the useful property that is is valid as soon as the header for a
                   6333: definition has been built. Thus:
1.44      crook    6334: 
                   6335: @example
1.116     anton    6336: latestxt . : foo [ latestxt . ] ; ' foo .
1.44      crook    6337: @end example
1.1       anton    6338: 
1.44      crook    6339: @noindent
                   6340: prints 3 numbers; the last two are the same.
1.26      crook    6341: 
1.236     anton    6342: 
                   6343: @node Quotations, Supplying names, Anonymous Definitions, Defining Words
                   6344: @subsection Quotations
                   6345: @cindex quotations
                   6346: @cindex nested colon definitions
                   6347: @cindex colon definitions, nesting
                   6348: 
                   6349: A quotation is an anonymous colon definition inside another colon
                   6350: definition.  Quotations are useful when dealing with words that
                   6351: consume an execution token, like @code{catch} or
                   6352: @code{outfile-execute}.  E.g. consider the following example of using
                   6353: @code{outfile-execute} (@pxref{Redirection}):
                   6354: 
                   6355: @example
                   6356: : some-warning ( n -- )
                   6357:     cr ." warning# " . ;
                   6358: 
                   6359: : print-some-warning ( n -- )
                   6360:     ['] some-warning stderr outfile-execute ;
                   6361: @end example
                   6362: 
                   6363: Here we defined @code{some-warning} as a helper word whose xt we could
                   6364: pass to outfile-execute.  Instead, we can use a quotation to define
                   6365: such a word anonymously inside @code{print-some-warning}:
                   6366: 
                   6367: @example
                   6368: : print-some-warning ( n -- )
                   6369:   [: cr ." warning# " . ;] stderr outfile-execute ;
                   6370: @end example
                   6371: 
                   6372: The quotation is bouded by @code{[:} and @code{;]}.  It produces an
                   6373: execution token at run-time.
                   6374: 
                   6375: doc-[:
                   6376: doc-;]
                   6377: 
                   6378: 
                   6379: @node Supplying names, User-defined Defining Words, Quotations, Defining Words
1.69      anton    6380: @subsection Supplying the name of a defined word
                   6381: @cindex names for defined words
                   6382: @cindex defining words, name given in a string
                   6383: 
                   6384: By default, a defining word takes the name for the defined word from the
                   6385: input stream. Sometimes you want to supply the name from a string. You
                   6386: can do this with:
                   6387: 
                   6388: doc-nextname
                   6389: 
                   6390: For example:
                   6391: 
                   6392: @example
                   6393: s" foo" nextname create
                   6394: @end example
                   6395: 
                   6396: @noindent
                   6397: is equivalent to:
                   6398: 
                   6399: @example
                   6400: create foo
                   6401: @end example
                   6402: 
                   6403: @noindent
                   6404: @code{nextname} works with any defining word.
                   6405: 
1.1       anton    6406: 
1.170     pazsan   6407: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26      crook    6408: @subsection User-defined Defining Words
                   6409: @cindex user-defined defining words
                   6410: @cindex defining words, user-defined
1.1       anton    6411: 
1.29      crook    6412: You can create a new defining word by wrapping defining-time code around
                   6413: an existing defining word and putting the sequence in a colon
1.69      anton    6414: definition. 
                   6415: 
                   6416: @c anton: This example is very complex and leads in a quite different
                   6417: @c direction from the CREATE-DOES> stuff that follows.  It should probably
                   6418: @c be done elsewhere, or as a subsubsection of this subsection (or as a
                   6419: @c subsection of Defining Words)
                   6420: 
                   6421: For example, suppose that you have a word @code{stats} that
1.29      crook    6422: gathers statistics about colon definitions given the @i{xt} of the
                   6423: definition, and you want every colon definition in your application to
                   6424: make a call to @code{stats}. You can define and use a new version of
                   6425: @code{:} like this:
                   6426: 
                   6427: @example
                   6428: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6429:   ... ;  \ other code
                   6430: 
1.116     anton    6431: : my: : latestxt postpone literal ['] stats compile, ;
1.29      crook    6432: 
                   6433: my: foo + - ;
                   6434: @end example
                   6435: 
                   6436: When @code{foo} is defined using @code{my:} these steps occur:
                   6437: 
                   6438: @itemize @bullet
                   6439: @item
                   6440: @code{my:} is executed.
                   6441: @item
                   6442: The @code{:} within the definition (the one between @code{my:} and
1.116     anton    6443: @code{latestxt}) is executed, and does just what it always does; it parses
1.29      crook    6444: the input stream for a name, builds a dictionary header for the name
                   6445: @code{foo} and switches @code{state} from interpret to compile.
                   6446: @item
1.116     anton    6447: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29      crook    6448: being defined -- @code{foo} -- onto the stack.
                   6449: @item
                   6450: The code that was produced by @code{postpone literal} is executed; this
                   6451: causes the value on the stack to be compiled as a literal in the code
                   6452: area of @code{foo}.
                   6453: @item
                   6454: The code @code{['] stats} compiles a literal into the definition of
                   6455: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6456: execution token for @code{stats} -- is layed down in the code area of
                   6457: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6458: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6459: in the code area is implementation-dependent. A threaded implementation
                   6460: might spit out the execution token directly whilst another
                   6461: implementation might spit out a native code sequence.}.
                   6462: @item
                   6463: At this point, the execution of @code{my:} is complete, and control
                   6464: returns to the text interpreter. The text interpreter is in compile
                   6465: state, so subsequent text @code{+ -} is compiled into the definition of
                   6466: @code{foo} and the @code{;} terminates the definition as always.
                   6467: @end itemize
                   6468: 
                   6469: You can use @code{see} to decompile a word that was defined using
                   6470: @code{my:} and see how it is different from a normal @code{:}
                   6471: definition. For example:
                   6472: 
                   6473: @example
                   6474: : bar + - ;  \ like foo but using : rather than my:
                   6475: see bar
                   6476: : bar
                   6477:   + - ;
                   6478: see foo
                   6479: : foo
                   6480:   107645672 stats + - ;
                   6481: 
1.140     anton    6482: \ use ' foo . to show that 107645672 is the xt for foo
1.29      crook    6483: @end example
                   6484: 
                   6485: You can use techniques like this to make new defining words in terms of
                   6486: @i{any} existing defining word.
1.1       anton    6487: 
                   6488: 
1.29      crook    6489: @cindex defining defining words
1.26      crook    6490: @cindex @code{CREATE} ... @code{DOES>}
                   6491: If you want the words defined with your defining words to behave
                   6492: differently from words defined with standard defining words, you can
                   6493: write your defining word like this:
1.1       anton    6494: 
                   6495: @example
1.26      crook    6496: : def-word ( "name" -- )
1.29      crook    6497:     CREATE @i{code1}
1.26      crook    6498: DOES> ( ... -- ... )
1.29      crook    6499:     @i{code2} ;
1.26      crook    6500: 
                   6501: def-word name
1.1       anton    6502: @end example
                   6503: 
1.29      crook    6504: @cindex child words
                   6505: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6506: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6507: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6508: is not executed at this time. The word @code{name} is sometimes called a
                   6509: @dfn{child} of @code{def-word}.
                   6510: 
                   6511: When you execute @code{name}, the address of the body of @code{name} is
                   6512: put on the data stack and @i{code2} is executed (the address of the body
                   6513: of @code{name} is the address @code{HERE} returns immediately after the
1.69      anton    6514: @code{CREATE}, i.e., the address a @code{create}d word returns by
                   6515: default).
                   6516: 
                   6517: @c anton:
                   6518: @c www.dictionary.com says:
                   6519: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
                   6520: @c several generations of absence, usually caused by the chance
                   6521: @c recombination of genes.  2.An individual or a part that exhibits
                   6522: @c atavism. Also called throwback.  3.The return of a trait or recurrence
                   6523: @c of previous behavior after a period of absence.
                   6524: @c
                   6525: @c Doesn't seem to fit.
1.29      crook    6526: 
1.69      anton    6527: @c @cindex atavism in child words
1.33      anton    6528: You can use @code{def-word} to define a set of child words that behave
1.69      anton    6529: similarly; they all have a common run-time behaviour determined by
                   6530: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
                   6531: body of the child word. The structure of the data is common to all
                   6532: children of @code{def-word}, but the data values are specific -- and
                   6533: private -- to each child word. When a child word is executed, the
                   6534: address of its private data area is passed as a parameter on TOS to be
                   6535: used and manipulated@footnote{It is legitimate both to read and write to
                   6536: this data area.} by @i{code2}.
1.29      crook    6537: 
                   6538: The two fragments of code that make up the defining words act (are
                   6539: executed) at two completely separate times:
1.1       anton    6540: 
1.29      crook    6541: @itemize @bullet
                   6542: @item
                   6543: At @i{define time}, the defining word executes @i{code1} to generate a
                   6544: child word
                   6545: @item
                   6546: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6547: is executed, using parameters (data) that are private and specific to
                   6548: the child word.
                   6549: @end itemize
                   6550: 
1.44      crook    6551: Another way of understanding the behaviour of @code{def-word} and
                   6552: @code{name} is to say that, if you make the following definitions:
1.33      anton    6553: @example
                   6554: : def-word1 ( "name" -- )
                   6555:     CREATE @i{code1} ;
                   6556: 
                   6557: : action1 ( ... -- ... )
                   6558:     @i{code2} ;
                   6559: 
                   6560: def-word1 name1
                   6561: @end example
                   6562: 
1.44      crook    6563: @noindent
                   6564: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6565: 
1.29      crook    6566: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6567: 
1.1       anton    6568: @example
1.29      crook    6569: : CONSTANT ( w "name" -- )
                   6570:     CREATE ,
1.26      crook    6571: DOES> ( -- w )
                   6572:     @@ ;
1.1       anton    6573: @end example
                   6574: 
1.29      crook    6575: @comment There is a beautiful description of how this works and what
                   6576: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6577: @comment commentary on the Counting Fruits problem.
                   6578: 
                   6579: When you create a constant with @code{5 CONSTANT five}, a set of
                   6580: define-time actions take place; first a new word @code{five} is created,
                   6581: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6582: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6583: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6584: no code of its own; it simply contains a data field and a pointer to the
                   6585: code that follows @code{DOES>} in its defining word. That makes words
                   6586: created in this way very compact.
                   6587: 
                   6588: The final example in this section is intended to remind you that space
                   6589: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6590: both read and written by a Standard program@footnote{Exercise: use this
                   6591: example as a starting point for your own implementation of @code{Value}
                   6592: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6593: @code{[']}.}:
                   6594: 
                   6595: @example
                   6596: : foo ( "name" -- )
                   6597:     CREATE -1 ,
                   6598: DOES> ( -- )
1.33      anton    6599:     @@ . ;
1.29      crook    6600: 
                   6601: foo first-word
                   6602: foo second-word
                   6603: 
                   6604: 123 ' first-word >BODY !
                   6605: @end example
                   6606: 
                   6607: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6608: have executed it to get the address of its data field. However, since it
                   6609: was defined to have @code{DOES>} actions, its execution semantics are to
                   6610: perform those @code{DOES>} actions. To get the address of its data field
                   6611: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6612: translate the xt into the address of the data field.  When you execute
                   6613: @code{first-word}, it will display @code{123}. When you execute
                   6614: @code{second-word} it will display @code{-1}.
1.26      crook    6615: 
                   6616: @cindex stack effect of @code{DOES>}-parts
                   6617: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6618: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6619: the stack effect of the defined words, not the stack effect of the
                   6620: following code (the following code expects the address of the body on
                   6621: the top of stack, which is not reflected in the stack comment). This is
                   6622: the convention that I use and recommend (it clashes a bit with using
                   6623: locals declarations for stack effect specification, though).
1.1       anton    6624: 
1.53      anton    6625: @menu
                   6626: * CREATE..DOES> applications::  
                   6627: * CREATE..DOES> details::       
1.63      anton    6628: * Advanced does> usage example::  
1.155     anton    6629: * Const-does>::                 
1.53      anton    6630: @end menu
                   6631: 
                   6632: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26      crook    6633: @subsubsection Applications of @code{CREATE..DOES>}
                   6634: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6635: 
1.26      crook    6636: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6637: 
1.26      crook    6638: @cindex factoring similar colon definitions
                   6639: When you see a sequence of code occurring several times, and you can
                   6640: identify a meaning, you will factor it out as a colon definition. When
                   6641: you see similar colon definitions, you can factor them using
                   6642: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6643: that look very similar:
1.1       anton    6644: @example
1.26      crook    6645: : ori, ( reg-target reg-source n -- )
                   6646:     0 asm-reg-reg-imm ;
                   6647: : andi, ( reg-target reg-source n -- )
                   6648:     1 asm-reg-reg-imm ;
1.1       anton    6649: @end example
                   6650: 
1.26      crook    6651: @noindent
                   6652: This could be factored with:
                   6653: @example
                   6654: : reg-reg-imm ( op-code -- )
                   6655:     CREATE ,
                   6656: DOES> ( reg-target reg-source n -- )
                   6657:     @@ asm-reg-reg-imm ;
                   6658: 
                   6659: 0 reg-reg-imm ori,
                   6660: 1 reg-reg-imm andi,
                   6661: @end example
1.1       anton    6662: 
1.26      crook    6663: @cindex currying
                   6664: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6665: supply a part of the parameters for a word (known as @dfn{currying} in
                   6666: the functional language community). E.g., @code{+} needs two
                   6667: parameters. Creating versions of @code{+} with one parameter fixed can
                   6668: be done like this:
1.82      anton    6669: 
1.1       anton    6670: @example
1.82      anton    6671: : curry+ ( n1 "name" -- )
1.26      crook    6672:     CREATE ,
                   6673: DOES> ( n2 -- n1+n2 )
                   6674:     @@ + ;
                   6675: 
                   6676:  3 curry+ 3+
                   6677: -2 curry+ 2-
1.1       anton    6678: @end example
                   6679: 
1.91      anton    6680: 
1.63      anton    6681: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6682: @subsubsection The gory details of @code{CREATE..DOES>}
                   6683: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6684: 
1.26      crook    6685: doc-does>
1.1       anton    6686: 
1.26      crook    6687: @cindex @code{DOES>} in a separate definition
                   6688: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6689: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6690: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6691: @example
                   6692: : does1 
                   6693: DOES> ( ... -- ... )
1.44      crook    6694:     ... ;
                   6695: 
                   6696: : does2
                   6697: DOES> ( ... -- ... )
                   6698:     ... ;
                   6699: 
                   6700: : def-word ( ... -- ... )
                   6701:     create ...
                   6702:     IF
                   6703:        does1
                   6704:     ELSE
                   6705:        does2
                   6706:     ENDIF ;
                   6707: @end example
                   6708: 
                   6709: In this example, the selection of whether to use @code{does1} or
1.69      anton    6710: @code{does2} is made at definition-time; at the time that the child word is
1.44      crook    6711: @code{CREATE}d.
                   6712: 
                   6713: @cindex @code{DOES>} in interpretation state
                   6714: In a standard program you can apply a @code{DOES>}-part only if the last
                   6715: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6716: will override the behaviour of the last word defined in any case. In a
                   6717: standard program, you can use @code{DOES>} only in a colon
                   6718: definition. In Gforth, you can also use it in interpretation state, in a
                   6719: kind of one-shot mode; for example:
                   6720: @example
                   6721: CREATE name ( ... -- ... )
                   6722:   @i{initialization}
                   6723: DOES>
                   6724:   @i{code} ;
                   6725: @end example
                   6726: 
                   6727: @noindent
                   6728: is equivalent to the standard:
                   6729: @example
                   6730: :noname
                   6731: DOES>
                   6732:     @i{code} ;
                   6733: CREATE name EXECUTE ( ... -- ... )
                   6734:     @i{initialization}
                   6735: @end example
                   6736: 
1.53      anton    6737: doc->body
                   6738: 
1.152     pazsan   6739: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63      anton    6740: @subsubsection Advanced does> usage example
                   6741: 
                   6742: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
                   6743: for disassembling instructions, that follow a very repetetive scheme:
                   6744: 
                   6745: @example
                   6746: :noname @var{disasm-operands} s" @var{inst-name}" type ;
                   6747: @var{entry-num} cells @var{table} + !
                   6748: @end example
                   6749: 
                   6750: Of course, this inspires the idea to factor out the commonalities to
                   6751: allow a definition like
                   6752: 
                   6753: @example
                   6754: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
                   6755: @end example
                   6756: 
                   6757: The parameters @var{disasm-operands} and @var{table} are usually
1.69      anton    6758: correlated.  Moreover, before I wrote the disassembler, there already
                   6759: existed code that defines instructions like this:
1.63      anton    6760: 
                   6761: @example
                   6762: @var{entry-num} @var{inst-format} @var{inst-name}
                   6763: @end example
                   6764: 
                   6765: This code comes from the assembler and resides in
                   6766: @file{arch/mips/insts.fs}.
                   6767: 
                   6768: So I had to define the @var{inst-format} words that performed the scheme
                   6769: above when executed.  At first I chose to use run-time code-generation:
                   6770: 
                   6771: @example
                   6772: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
                   6773:   :noname Postpone @var{disasm-operands}
                   6774:   name Postpone sliteral Postpone type Postpone ;
                   6775:   swap cells @var{table} + ! ;
                   6776: @end example
                   6777: 
                   6778: Note that this supplies the other two parameters of the scheme above.
1.44      crook    6779: 
1.63      anton    6780: An alternative would have been to write this using
                   6781: @code{create}/@code{does>}:
                   6782: 
                   6783: @example
                   6784: : @var{inst-format} ( entry-num "name" -- )
                   6785:   here name string, ( entry-num c-addr ) \ parse and save "name"
                   6786:   noname create , ( entry-num )
1.116     anton    6787:   latestxt swap cells @var{table} + !
1.63      anton    6788: does> ( addr w -- )
                   6789:   \ disassemble instruction w at addr
                   6790:   @@ >r 
                   6791:   @var{disasm-operands}
                   6792:   r> count type ;
                   6793: @end example
                   6794: 
                   6795: Somehow the first solution is simpler, mainly because it's simpler to
                   6796: shift a string from definition-time to use-time with @code{sliteral}
                   6797: than with @code{string,} and friends.
                   6798: 
                   6799: I wrote a lot of words following this scheme and soon thought about
                   6800: factoring out the commonalities among them.  Note that this uses a
                   6801: two-level defining word, i.e., a word that defines ordinary defining
                   6802: words.
                   6803: 
                   6804: This time a solution involving @code{postpone} and friends seemed more
                   6805: difficult (try it as an exercise), so I decided to use a
                   6806: @code{create}/@code{does>} word; since I was already at it, I also used
                   6807: @code{create}/@code{does>} for the lower level (try using
                   6808: @code{postpone} etc. as an exercise), resulting in the following
                   6809: definition:
                   6810: 
                   6811: @example
                   6812: : define-format ( disasm-xt table-xt -- )
                   6813:     \ define an instruction format that uses disasm-xt for
                   6814:     \ disassembling and enters the defined instructions into table
                   6815:     \ table-xt
                   6816:     create 2,
                   6817: does> ( u "inst" -- )
                   6818:     \ defines an anonymous word for disassembling instruction inst,
                   6819:     \ and enters it as u-th entry into table-xt
                   6820:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
                   6821:     noname create 2,      \ define anonymous word
1.116     anton    6822:     execute latestxt swap ! \ enter xt of defined word into table-xt
1.63      anton    6823: does> ( addr w -- )
                   6824:     \ disassemble instruction w at addr
                   6825:     2@@ >r ( addr w disasm-xt R: c-addr )
                   6826:     execute ( R: c-addr ) \ disassemble operands
                   6827:     r> count type ; \ print name 
                   6828: @end example
                   6829: 
                   6830: Note that the tables here (in contrast to above) do the @code{cells +}
                   6831: by themselves (that's why you have to pass an xt).  This word is used in
                   6832: the following way:
                   6833: 
                   6834: @example
                   6835: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
                   6836: @end example
                   6837: 
1.71      anton    6838: As shown above, the defined instruction format is then used like this:
                   6839: 
                   6840: @example
                   6841: @var{entry-num} @var{inst-format} @var{inst-name}
                   6842: @end example
                   6843: 
1.63      anton    6844: In terms of currying, this kind of two-level defining word provides the
                   6845: parameters in three stages: first @var{disasm-operands} and @var{table},
                   6846: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
                   6847: the instruction to be disassembled.  
                   6848: 
                   6849: Of course this did not quite fit all the instruction format names used
                   6850: in @file{insts.fs}, so I had to define a few wrappers that conditioned
                   6851: the parameters into the right form.
                   6852: 
                   6853: If you have trouble following this section, don't worry.  First, this is
                   6854: involved and takes time (and probably some playing around) to
                   6855: understand; second, this is the first two-level
                   6856: @code{create}/@code{does>} word I have written in seventeen years of
                   6857: Forth; and if I did not have @file{insts.fs} to start with, I may well
                   6858: have elected to use just a one-level defining word (with some repeating
                   6859: of parameters when using the defining word). So it is not necessary to
                   6860: understand this, but it may improve your understanding of Forth.
1.44      crook    6861: 
                   6862: 
1.152     pazsan   6863: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
1.91      anton    6864: @subsubsection @code{Const-does>}
                   6865: 
                   6866: A frequent use of @code{create}...@code{does>} is for transferring some
                   6867: values from definition-time to run-time.  Gforth supports this use with
                   6868: 
                   6869: doc-const-does>
                   6870: 
                   6871: A typical use of this word is:
                   6872: 
                   6873: @example
                   6874: : curry+ ( n1 "name" -- )
                   6875: 1 0 CONST-DOES> ( n2 -- n1+n2 )
                   6876:     + ;
                   6877: 
                   6878: 3 curry+ 3+
                   6879: @end example
                   6880: 
                   6881: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
                   6882: definition to run-time.
                   6883: 
                   6884: The advantages of using @code{const-does>} are:
                   6885: 
                   6886: @itemize
                   6887: 
                   6888: @item
                   6889: You don't have to deal with storing and retrieving the values, i.e.,
                   6890: your program becomes more writable and readable.
                   6891: 
                   6892: @item
                   6893: When using @code{does>}, you have to introduce a @code{@@} that cannot
                   6894: be optimized away (because you could change the data using
                   6895: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
                   6896: 
                   6897: @end itemize
                   6898: 
                   6899: An ANS Forth implementation of @code{const-does>} is available in
                   6900: @file{compat/const-does.fs}.
                   6901: 
                   6902: 
1.170     pazsan   6903: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
                   6904: @subsection Deferred Words
1.44      crook    6905: @cindex deferred words
                   6906: 
                   6907: The defining word @code{Defer} allows you to define a word by name
                   6908: without defining its behaviour; the definition of its behaviour is
                   6909: deferred. Here are two situation where this can be useful:
                   6910: 
                   6911: @itemize @bullet
                   6912: @item
                   6913: Where you want to allow the behaviour of a word to be altered later, and
                   6914: for all precompiled references to the word to change when its behaviour
                   6915: is changed.
                   6916: @item
                   6917: For mutual recursion; @xref{Calls and returns}.
                   6918: @end itemize
                   6919: 
                   6920: In the following example, @code{foo} always invokes the version of
                   6921: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6922: always invokes the version that prints ``@code{Hello}''. There is no way
                   6923: of getting @code{foo} to use the later version without re-ordering the
                   6924: source code and recompiling it.
                   6925: 
                   6926: @example
                   6927: : greet ." Good morning" ;
                   6928: : foo ... greet ... ;
                   6929: : greet ." Hello" ;
                   6930: : bar ... greet ... ;
                   6931: @end example
                   6932: 
                   6933: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6934: word. The behaviour of a @code{Defer}red word can be defined and
                   6935: redefined at any time by using @code{IS} to associate the xt of a
                   6936: previously-defined word with it. The previous example becomes:
                   6937: 
                   6938: @example
1.69      anton    6939: Defer greet ( -- )
1.44      crook    6940: : foo ... greet ... ;
                   6941: : bar ... greet ... ;
1.69      anton    6942: : greet1 ( -- ) ." Good morning" ;
                   6943: : greet2 ( -- ) ." Hello" ;
1.132     anton    6944: ' greet2 IS greet  \ make greet behave like greet2
1.44      crook    6945: @end example
                   6946: 
1.69      anton    6947: @progstyle
                   6948: You should write a stack comment for every deferred word, and put only
                   6949: XTs into deferred words that conform to this stack effect.  Otherwise
                   6950: it's too difficult to use the deferred word.
                   6951: 
1.44      crook    6952: A deferred word can be used to improve the statistics-gathering example
                   6953: from @ref{User-defined Defining Words}; rather than edit the
                   6954: application's source code to change every @code{:} to a @code{my:}, do
                   6955: this:
                   6956: 
                   6957: @example
                   6958: : real: : ;     \ retain access to the original
                   6959: defer :         \ redefine as a deferred word
1.132     anton    6960: ' my: IS :      \ use special version of :
1.44      crook    6961: \
                   6962: \ load application here
                   6963: \
1.132     anton    6964: ' real: IS :    \ go back to the original
1.44      crook    6965: @end example
                   6966: 
                   6967: 
1.132     anton    6968: One thing to note is that @code{IS} has special compilation semantics,
                   6969: such that it parses the name at compile time (like @code{TO}):
1.44      crook    6970: 
                   6971: @example
                   6972: : set-greet ( xt -- )
1.132     anton    6973:   IS greet ;
1.44      crook    6974: 
                   6975: ' greet1 set-greet
                   6976: @end example
                   6977: 
1.132     anton    6978: In situations where @code{IS} does not fit, use @code{defer!} instead.
                   6979: 
1.69      anton    6980: A deferred word can only inherit execution semantics from the xt
                   6981: (because that is all that an xt can represent -- for more discussion of
                   6982: this @pxref{Tokens for Words}); by default it will have default
                   6983: interpretation and compilation semantics deriving from this execution
                   6984: semantics.  However, you can change the interpretation and compilation
                   6985: semantics of the deferred word in the usual ways:
1.44      crook    6986: 
                   6987: @example
1.132     anton    6988: : bar .... ; immediate
1.44      crook    6989: Defer fred immediate
                   6990: Defer jim
                   6991: 
1.132     anton    6992: ' bar IS jim  \ jim has default semantics
                   6993: ' bar IS fred \ fred is immediate
1.44      crook    6994: @end example
                   6995: 
                   6996: doc-defer
1.132     anton    6997: doc-defer!
1.44      crook    6998: doc-is
1.132     anton    6999: doc-defer@
                   7000: doc-action-of
1.44      crook    7001: @comment TODO document these: what's defers [is]
                   7002: doc-defers
                   7003: 
                   7004: @c Use @code{words-deferred} to see a list of deferred words.
                   7005: 
1.132     anton    7006: Definitions of these words (except @code{defers}) in ANS Forth are
                   7007: provided in @file{compat/defer.fs}.
1.44      crook    7008: 
                   7009: 
1.170     pazsan   7010: @node Aliases,  , Deferred Words, Defining Words
1.44      crook    7011: @subsection Aliases
                   7012: @cindex aliases
1.1       anton    7013: 
1.44      crook    7014: The defining word @code{Alias} allows you to define a word by name that
                   7015: has the same behaviour as some other word. Here are two situation where
                   7016: this can be useful:
1.1       anton    7017: 
1.44      crook    7018: @itemize @bullet
                   7019: @item
                   7020: When you want access to a word's definition from a different word list
                   7021: (for an example of this, see the definition of the @code{Root} word list
                   7022: in the Gforth source).
                   7023: @item
                   7024: When you want to create a synonym; a definition that can be known by
                   7025: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   7026: aliases).
                   7027: @end itemize
1.1       anton    7028: 
1.69      anton    7029: Like deferred words, an alias has default compilation and interpretation
                   7030: semantics at the beginning (not the modifications of the other word),
                   7031: but you can change them in the usual ways (@code{immediate},
                   7032: @code{compile-only}). For example:
1.1       anton    7033: 
                   7034: @example
1.44      crook    7035: : foo ... ; immediate
                   7036: 
                   7037: ' foo Alias bar \ bar is not an immediate word
                   7038: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    7039: @end example
                   7040: 
1.44      crook    7041: Words that are aliases have the same xt, different headers in the
                   7042: dictionary, and consequently different name tokens (@pxref{Tokens for
                   7043: Words}) and possibly different immediate flags.  An alias can only have
                   7044: default or immediate compilation semantics; you can define aliases for
                   7045: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    7046: 
1.44      crook    7047: doc-alias
1.1       anton    7048: 
                   7049: 
1.47      crook    7050: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   7051: @section Interpretation and Compilation Semantics
1.26      crook    7052: @cindex semantics, interpretation and compilation
1.1       anton    7053: 
1.71      anton    7054: @c !! state and ' are used without explanation
                   7055: @c example for immediate/compile-only? or is the tutorial enough
                   7056: 
1.26      crook    7057: @cindex interpretation semantics
1.71      anton    7058: The @dfn{interpretation semantics} of a (named) word are what the text
1.26      crook    7059: interpreter does when it encounters the word in interpret state. It also
                   7060: appears in some other contexts, e.g., the execution token returned by
1.71      anton    7061: @code{' @i{word}} identifies the interpretation semantics of @i{word}
                   7062: (in other words, @code{' @i{word} execute} is equivalent to
1.29      crook    7063: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    7064: 
1.26      crook    7065: @cindex compilation semantics
1.71      anton    7066: The @dfn{compilation semantics} of a (named) word are what the text
                   7067: interpreter does when it encounters the word in compile state. It also
                   7068: appears in other contexts, e.g, @code{POSTPONE @i{word}}
                   7069: compiles@footnote{In standard terminology, ``appends to the current
                   7070: definition''.} the compilation semantics of @i{word}.
1.1       anton    7071: 
1.26      crook    7072: @cindex execution semantics
                   7073: The standard also talks about @dfn{execution semantics}. They are used
                   7074: only for defining the interpretation and compilation semantics of many
                   7075: words. By default, the interpretation semantics of a word are to
                   7076: @code{execute} its execution semantics, and the compilation semantics of
                   7077: a word are to @code{compile,} its execution semantics.@footnote{In
                   7078: standard terminology: The default interpretation semantics are its
                   7079: execution semantics; the default compilation semantics are to append its
                   7080: execution semantics to the execution semantics of the current
                   7081: definition.}
                   7082: 
1.71      anton    7083: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
                   7084: the text interpreter, ticked, or @code{postpone}d, so they have no
                   7085: interpretation or compilation semantics.  Their behaviour is represented
                   7086: by their XT (@pxref{Tokens for Words}), and we call it execution
                   7087: semantics, too.
                   7088: 
1.26      crook    7089: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   7090: 
                   7091: @cindex immediate words
                   7092: @cindex compile-only words
                   7093: You can change the semantics of the most-recently defined word:
                   7094: 
1.44      crook    7095: 
1.26      crook    7096: doc-immediate
                   7097: doc-compile-only
                   7098: doc-restrict
                   7099: 
1.82      anton    7100: By convention, words with non-default compilation semantics (e.g.,
                   7101: immediate words) often have names surrounded with brackets (e.g.,
                   7102: @code{[']}, @pxref{Execution token}).
1.44      crook    7103: 
1.26      crook    7104: Note that ticking (@code{'}) a compile-only word gives an error
                   7105: (``Interpreting a compile-only word'').
1.1       anton    7106: 
1.47      crook    7107: @menu
1.67      anton    7108: * Combined words::              
1.47      crook    7109: @end menu
1.44      crook    7110: 
1.71      anton    7111: 
1.48      anton    7112: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    7113: @subsection Combined Words
                   7114: @cindex combined words
                   7115: 
                   7116: Gforth allows you to define @dfn{combined words} -- words that have an
                   7117: arbitrary combination of interpretation and compilation semantics.
                   7118: 
1.26      crook    7119: doc-interpret/compile:
1.1       anton    7120: 
1.26      crook    7121: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   7122: recommend that you do not define such words, as cute as they may be:
                   7123: they make it hard to get at both parts of the word in some contexts.
                   7124: E.g., assume you want to get an execution token for the compilation
                   7125: part. Instead, define two words, one that embodies the interpretation
                   7126: part, and one that embodies the compilation part.  Once you have done
                   7127: that, you can define a combined word with @code{interpret/compile:} for
                   7128: the convenience of your users.
1.1       anton    7129: 
1.26      crook    7130: You might try to use this feature to provide an optimizing
                   7131: implementation of the default compilation semantics of a word. For
                   7132: example, by defining:
1.1       anton    7133: @example
1.26      crook    7134: :noname
                   7135:    foo bar ;
                   7136: :noname
                   7137:    POSTPONE foo POSTPONE bar ;
1.29      crook    7138: interpret/compile: opti-foobar
1.1       anton    7139: @end example
1.26      crook    7140: 
1.23      crook    7141: @noindent
1.26      crook    7142: as an optimizing version of:
                   7143: 
1.1       anton    7144: @example
1.26      crook    7145: : foobar
                   7146:     foo bar ;
1.1       anton    7147: @end example
                   7148: 
1.26      crook    7149: Unfortunately, this does not work correctly with @code{[compile]},
                   7150: because @code{[compile]} assumes that the compilation semantics of all
                   7151: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    7152: opti-foobar} would compile compilation semantics, whereas
                   7153: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    7154: 
1.26      crook    7155: @cindex state-smart words (are a bad idea)
1.82      anton    7156: @anchor{state-smartness}
1.29      crook    7157: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    7158: by @code{interpret/compile:} (words are state-smart if they check
                   7159: @code{STATE} during execution). E.g., they would try to code
                   7160: @code{foobar} like this:
1.1       anton    7161: 
1.26      crook    7162: @example
                   7163: : foobar
                   7164:   STATE @@
                   7165:   IF ( compilation state )
                   7166:     POSTPONE foo POSTPONE bar
                   7167:   ELSE
                   7168:     foo bar
                   7169:   ENDIF ; immediate
                   7170: @end example
1.1       anton    7171: 
1.26      crook    7172: Although this works if @code{foobar} is only processed by the text
                   7173: interpreter, it does not work in other contexts (like @code{'} or
                   7174: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   7175: for a state-smart word, not for the interpretation semantics of the
                   7176: original @code{foobar}; when you execute this execution token (directly
                   7177: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   7178: state, the result will not be what you expected (i.e., it will not
                   7179: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   7180: write them@footnote{For a more detailed discussion of this topic, see
1.66      anton    7181: M. Anton Ertl,
                   7182: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
                   7183: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1       anton    7184: 
1.26      crook    7185: @cindex defining words with arbitrary semantics combinations
                   7186: It is also possible to write defining words that define words with
                   7187: arbitrary combinations of interpretation and compilation semantics. In
                   7188: general, they look like this:
1.1       anton    7189: 
1.26      crook    7190: @example
                   7191: : def-word
                   7192:     create-interpret/compile
1.29      crook    7193:     @i{code1}
1.26      crook    7194: interpretation>
1.29      crook    7195:     @i{code2}
1.26      crook    7196: <interpretation
                   7197: compilation>
1.29      crook    7198:     @i{code3}
1.26      crook    7199: <compilation ;
                   7200: @end example
1.1       anton    7201: 
1.29      crook    7202: For a @i{word} defined with @code{def-word}, the interpretation
                   7203: semantics are to push the address of the body of @i{word} and perform
                   7204: @i{code2}, and the compilation semantics are to push the address of
                   7205: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    7206: can also be defined like this (except that the defined constants don't
                   7207: behave correctly when @code{[compile]}d):
1.1       anton    7208: 
1.26      crook    7209: @example
                   7210: : constant ( n "name" -- )
                   7211:     create-interpret/compile
                   7212:     ,
                   7213: interpretation> ( -- n )
                   7214:     @@
                   7215: <interpretation
                   7216: compilation> ( compilation. -- ; run-time. -- n )
                   7217:     @@ postpone literal
                   7218: <compilation ;
                   7219: @end example
1.1       anton    7220: 
1.44      crook    7221: 
1.26      crook    7222: doc-create-interpret/compile
                   7223: doc-interpretation>
                   7224: doc-<interpretation
                   7225: doc-compilation>
                   7226: doc-<compilation
1.1       anton    7227: 
1.44      crook    7228: 
1.29      crook    7229: Words defined with @code{interpret/compile:} and
1.26      crook    7230: @code{create-interpret/compile} have an extended header structure that
                   7231: differs from other words; however, unless you try to access them with
                   7232: plain address arithmetic, you should not notice this. Words for
                   7233: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    7234: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   7235: with @code{create-interpret/compile}.
1.1       anton    7236: 
1.44      crook    7237: 
1.47      crook    7238: @c -------------------------------------------------------------
1.81      anton    7239: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47      crook    7240: @section Tokens for Words
                   7241: @cindex tokens for words
                   7242: 
                   7243: This section describes the creation and use of tokens that represent
                   7244: words.
                   7245: 
1.71      anton    7246: @menu
                   7247: * Execution token::             represents execution/interpretation semantics
                   7248: * Compilation token::           represents compilation semantics
                   7249: * Name token::                  represents named words
                   7250: @end menu
1.47      crook    7251: 
1.71      anton    7252: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
                   7253: @subsection Execution token
1.47      crook    7254: 
                   7255: @cindex xt
                   7256: @cindex execution token
1.71      anton    7257: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
                   7258: You can use @code{execute} to invoke this behaviour.
1.47      crook    7259: 
1.71      anton    7260: @cindex tick (')
                   7261: You can use @code{'} to get an execution token that represents the
                   7262: interpretation semantics of a named word:
1.47      crook    7263: 
                   7264: @example
1.97      anton    7265: 5 ' .   ( n xt ) 
                   7266: execute ( )      \ execute the xt (i.e., ".")
1.71      anton    7267: @end example
1.47      crook    7268: 
1.71      anton    7269: doc-'
                   7270: 
                   7271: @code{'} parses at run-time; there is also a word @code{[']} that parses
                   7272: when it is compiled, and compiles the resulting XT:
                   7273: 
                   7274: @example
                   7275: : foo ['] . execute ;
                   7276: 5 foo
                   7277: : bar ' execute ; \ by contrast,
                   7278: 5 bar .           \ ' parses "." when bar executes
                   7279: @end example
                   7280: 
                   7281: doc-[']
                   7282: 
                   7283: If you want the execution token of @i{word}, write @code{['] @i{word}}
                   7284: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
                   7285: @code{'} and @code{[']} behave somewhat unusually by complaining about
                   7286: compile-only words (because these words have no interpretation
                   7287: semantics).  You might get what you want by using @code{COMP' @i{word}
                   7288: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
                   7289: token}).
                   7290: 
1.116     anton    7291: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71      anton    7292: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
                   7293: for the only behaviour the word has (the execution semantics).  For
1.116     anton    7294: named words, @code{latestxt} produces an XT for the same behaviour it
1.71      anton    7295: would produce if the word was defined anonymously.
                   7296: 
                   7297: @example
                   7298: :noname ." hello" ;
                   7299: execute
1.47      crook    7300: @end example
                   7301: 
1.71      anton    7302: An XT occupies one cell and can be manipulated like any other cell.
                   7303: 
1.47      crook    7304: @cindex code field address
                   7305: @cindex CFA
1.71      anton    7306: In ANS Forth the XT is just an abstract data type (i.e., defined by the
                   7307: operations that produce or consume it).  For old hands: In Gforth, the
                   7308: XT is implemented as a code field address (CFA).
                   7309: 
                   7310: doc-execute
                   7311: doc-perform
                   7312: 
                   7313: @node Compilation token, Name token, Execution token, Tokens for Words
                   7314: @subsection Compilation token
1.47      crook    7315: 
                   7316: @cindex compilation token
1.71      anton    7317: @cindex CT (compilation token)
                   7318: Gforth represents the compilation semantics of a named word by a
1.47      crook    7319: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   7320: @i{xt} is an execution token. The compilation semantics represented by
                   7321: the compilation token can be performed with @code{execute}, which
                   7322: consumes the whole compilation token, with an additional stack effect
                   7323: determined by the represented compilation semantics.
                   7324: 
                   7325: At present, the @i{w} part of a compilation token is an execution token,
                   7326: and the @i{xt} part represents either @code{execute} or
                   7327: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   7328: word. If the word has default compilation semantics, the @i{xt} will
                   7329: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   7330: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   7331: knowledge, unless necessary; future versions of Gforth may introduce
                   7332: unusual compilation tokens (e.g., a compilation token that represents
                   7333: the compilation semantics of a literal).
                   7334: 
1.71      anton    7335: You can perform the compilation semantics represented by the compilation
                   7336: token with @code{execute}.  You can compile the compilation semantics
                   7337: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
                   7338: equivalent to @code{postpone @i{word}}.
                   7339: 
                   7340: doc-[comp']
                   7341: doc-comp'
                   7342: doc-postpone,
                   7343: 
                   7344: @node Name token,  , Compilation token, Tokens for Words
                   7345: @subsection Name token
1.47      crook    7346: 
                   7347: @cindex name token
1.116     anton    7348: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
                   7349: token is an abstract data type that occurs as argument or result of the
                   7350: words below.
                   7351: 
                   7352: @c !! put this elswhere?
1.47      crook    7353: @cindex name field address
                   7354: @cindex NFA
1.116     anton    7355: The closest thing to the nt in older Forth systems is the name field
                   7356: address (NFA), but there are significant differences: in older Forth
                   7357: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
                   7358: LFA, NFA, CFA, PFA) and there were words for getting from one to the
                   7359: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
                   7360: is a link field in the structure identified by the name token, but
                   7361: searching usually uses a hash table external to these structures; the
                   7362: name in Gforth has a cell-wide count-and-flags field, and the nt is not
                   7363: implemented as the address of that count field.
1.47      crook    7364: 
                   7365: doc-find-name
1.116     anton    7366: doc-latest
                   7367: doc->name
1.47      crook    7368: doc-name>int
                   7369: doc-name?int
                   7370: doc-name>comp
                   7371: doc-name>string
1.109     anton    7372: doc-id.
                   7373: doc-.name
                   7374: doc-.id
1.47      crook    7375: 
1.81      anton    7376: @c ----------------------------------------------------------
                   7377: @node Compiling words, The Text Interpreter, Tokens for Words, Words
                   7378: @section Compiling words
                   7379: @cindex compiling words
                   7380: @cindex macros
                   7381: 
                   7382: In contrast to most other languages, Forth has no strict boundary
1.82      anton    7383: between compilation and run-time.  E.g., you can run arbitrary code
                   7384: between defining words (or for computing data used by defining words
                   7385: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
                   7386: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
                   7387: running arbitrary code while compiling a colon definition (exception:
                   7388: you must not allot dictionary space).
                   7389: 
                   7390: @menu
                   7391: * Literals::                    Compiling data values
                   7392: * Macros::                      Compiling words
                   7393: @end menu
                   7394: 
                   7395: @node Literals, Macros, Compiling words, Compiling words
                   7396: @subsection Literals
                   7397: @cindex Literals
                   7398: 
                   7399: The simplest and most frequent example is to compute a literal during
                   7400: compilation.  E.g., the following definition prints an array of strings,
                   7401: one string per line:
                   7402: 
                   7403: @example
                   7404: : .strings ( addr u -- ) \ gforth
                   7405:     2* cells bounds U+DO
                   7406:        cr i 2@@ type
                   7407:     2 cells +LOOP ;  
                   7408: @end example
1.81      anton    7409: 
1.82      anton    7410: With a simple-minded compiler like Gforth's, this computes @code{2
                   7411: cells} on every loop iteration.  You can compute this value once and for
                   7412: all at compile time and compile it into the definition like this:
                   7413: 
                   7414: @example
                   7415: : .strings ( addr u -- ) \ gforth
                   7416:     2* cells bounds U+DO
                   7417:        cr i 2@@ type
                   7418:     [ 2 cells ] literal +LOOP ;  
                   7419: @end example
                   7420: 
                   7421: @code{[} switches the text interpreter to interpret state (you will get
                   7422: an @code{ok} prompt if you type this example interactively and insert a
                   7423: newline between @code{[} and @code{]}), so it performs the
                   7424: interpretation semantics of @code{2 cells}; this computes a number.
                   7425: @code{]} switches the text interpreter back into compile state.  It then
                   7426: performs @code{Literal}'s compilation semantics, which are to compile
                   7427: this number into the current word.  You can decompile the word with
                   7428: @code{see .strings} to see the effect on the compiled code.
1.81      anton    7429: 
1.82      anton    7430: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
                   7431: *} in this way.
1.81      anton    7432: 
1.82      anton    7433: doc-[
                   7434: doc-]
1.81      anton    7435: doc-literal
                   7436: doc-]L
1.82      anton    7437: 
                   7438: There are also words for compiling other data types than single cells as
                   7439: literals:
                   7440: 
1.81      anton    7441: doc-2literal
                   7442: doc-fliteral
1.82      anton    7443: doc-sliteral
                   7444: 
                   7445: @cindex colon-sys, passing data across @code{:}
                   7446: @cindex @code{:}, passing data across
                   7447: You might be tempted to pass data from outside a colon definition to the
                   7448: inside on the data stack.  This does not work, because @code{:} puhes a
                   7449: colon-sys, making stuff below unaccessible.  E.g., this does not work:
                   7450: 
                   7451: @example
                   7452: 5 : foo literal ; \ error: "unstructured"
                   7453: @end example
                   7454: 
                   7455: Instead, you have to pass the value in some other way, e.g., through a
                   7456: variable:
                   7457: 
                   7458: @example
                   7459: variable temp
                   7460: 5 temp !
                   7461: : foo [ temp @@ ] literal ;
                   7462: @end example
                   7463: 
                   7464: 
                   7465: @node Macros,  , Literals, Compiling words
                   7466: @subsection Macros
                   7467: @cindex Macros
                   7468: @cindex compiling compilation semantics
                   7469: 
                   7470: @code{Literal} and friends compile data values into the current
                   7471: definition.  You can also write words that compile other words into the
                   7472: current definition.  E.g.,
                   7473: 
                   7474: @example
                   7475: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
                   7476:   POSTPONE + ;
                   7477: 
                   7478: : foo ( n1 n2 -- n )
                   7479:   [ compile-+ ] ;
                   7480: 1 2 foo .
                   7481: @end example
                   7482: 
                   7483: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
                   7484: What happens in this example?  @code{Postpone} compiles the compilation
                   7485: semantics of @code{+} into @code{compile-+}; later the text interpreter
                   7486: executes @code{compile-+} and thus the compilation semantics of +, which
                   7487: compile (the execution semantics of) @code{+} into
                   7488: @code{foo}.@footnote{A recent RFI answer requires that compiling words
                   7489: should only be executed in compile state, so this example is not
                   7490: guaranteed to work on all standard systems, but on any decent system it
                   7491: will work.}
                   7492: 
                   7493: doc-postpone
                   7494: 
                   7495: Compiling words like @code{compile-+} are usually immediate (or similar)
                   7496: so you do not have to switch to interpret state to execute them;
1.206     anton    7497: modifying the last example accordingly produces:
1.82      anton    7498: 
                   7499: @example
                   7500: : [compile-+] ( compilation: --; interpretation: -- )
                   7501:   \ compiled code: ( n1 n2 -- n )
                   7502:   POSTPONE + ; immediate
                   7503: 
                   7504: : foo ( n1 n2 -- n )
                   7505:   [compile-+] ;
                   7506: 1 2 foo .
                   7507: @end example
                   7508: 
1.206     anton    7509: You will occassionally find the need to POSTPONE several words;
                   7510: putting POSTPONE before each such word is cumbersome, so Gforth
                   7511: provides a more convenient syntax: @code{]] ... [[}.  This
                   7512: allows us to write @code{[compile-+]} as:
                   7513: 
                   7514: @example
                   7515: : [compile-+] ( compilation: --; interpretation: -- )
                   7516:   ]] + [[ ; immediate
                   7517: @end example
                   7518: 
                   7519: doc-]]
                   7520: doc-[[
                   7521: 
                   7522: The unusual direction of the brackets indicates their function:
                   7523: @code{]]} switches from compilation to postponing (i.e., compilation
                   7524: of compilation), just like @code{]} switches from immediate execution
                   7525: (interpretation) to compilation.  Conversely, @code{[[} switches from
                   7526: postponing to compilation, ananlogous to @code{[} which switches from
                   7527: compilation to immediate execution.
                   7528: 
                   7529: The real advantage of @code{]] }...@code{ [[} becomes apparent when
                   7530: there are many words to POSTPONE.  E.g., the word
                   7531: @code{compile-map-array} (@pxref{Advanced macros Tutorial}) can be
                   7532: written much shorter as follows:
                   7533: 
                   7534: @example
                   7535: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   7536: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   7537: \ array beginning at addr and containing u elements
                   7538:   @{ xt @}
                   7539:   ]] cells over + swap ?do
                   7540:     i @@ [[ xt compile, 
                   7541:   1 cells ]]L +loop [[ ;
                   7542: @end example
                   7543: 
                   7544: This example also uses @code{]]L} as a shortcut for @code{]] literal}.
                   7545: There are also other shortcuts
                   7546: 
                   7547: doc-]]L
                   7548: doc-]]2L
                   7549: doc-]]FL
                   7550: doc-]]SL
                   7551: 
                   7552: Note that parsing words don't parse at postpone time; if you want to
                   7553: provide the parsed string right away, you have to switch back to
                   7554: compilation:
                   7555: 
                   7556: @example
                   7557: ]] ... [[ s" some string" ]]2L ... [[
                   7558: ]] ... [[ ['] + ]]L ... [[
                   7559: @end example
                   7560: 
                   7561: Definitions of @code{]]} and friends in ANS Forth are provided in
                   7562: @file{compat/macros.fs}.
                   7563: 
1.82      anton    7564: Immediate compiling words are similar to macros in other languages (in
                   7565: particular, Lisp).  The important differences to macros in, e.g., C are:
                   7566: 
                   7567: @itemize @bullet
                   7568: 
                   7569: @item
                   7570: You use the same language for defining and processing macros, not a
                   7571: separate preprocessing language and processor.
                   7572: 
                   7573: @item
                   7574: Consequently, the full power of Forth is available in macro definitions.
                   7575: E.g., you can perform arbitrarily complex computations, or generate
                   7576: different code conditionally or in a loop (e.g., @pxref{Advanced macros
                   7577: Tutorial}).  This power is very useful when writing a parser generators
                   7578: or other code-generating software.
                   7579: 
                   7580: @item
                   7581: Macros defined using @code{postpone} etc. deal with the language at a
                   7582: higher level than strings; name binding happens at macro definition
                   7583: time, so you can avoid the pitfalls of name collisions that can happen
                   7584: in C macros.  Of course, Forth is a liberal language and also allows to
                   7585: shoot yourself in the foot with text-interpreted macros like
                   7586: 
                   7587: @example
                   7588: : [compile-+] s" +" evaluate ; immediate
                   7589: @end example
                   7590: 
                   7591: Apart from binding the name at macro use time, using @code{evaluate}
                   7592: also makes your definition @code{state}-smart (@pxref{state-smartness}).
                   7593: @end itemize
                   7594: 
                   7595: You may want the macro to compile a number into a word.  The word to do
                   7596: it is @code{literal}, but you have to @code{postpone} it, so its
                   7597: compilation semantics take effect when the macro is executed, not when
                   7598: it is compiled:
                   7599: 
                   7600: @example
                   7601: : [compile-5] ( -- ) \ compiled code: ( -- n )
                   7602:   5 POSTPONE literal ; immediate
                   7603: 
                   7604: : foo [compile-5] ;
                   7605: foo .
                   7606: @end example
                   7607: 
                   7608: You may want to pass parameters to a macro, that the macro should
                   7609: compile into the current definition.  If the parameter is a number, then
                   7610: you can use @code{postpone literal} (similar for other values).
                   7611: 
                   7612: If you want to pass a word that is to be compiled, the usual way is to
                   7613: pass an execution token and @code{compile,} it:
                   7614: 
                   7615: @example
                   7616: : twice1 ( xt -- ) \ compiled code: ... -- ...
                   7617:   dup compile, compile, ;
                   7618: 
                   7619: : 2+ ( n1 -- n2 )
                   7620:   [ ' 1+ twice1 ] ;
                   7621: @end example
                   7622: 
                   7623: doc-compile,
                   7624: 
                   7625: An alternative available in Gforth, that allows you to pass compile-only
                   7626: words as parameters is to use the compilation token (@pxref{Compilation
                   7627: token}).  The same example in this technique:
                   7628: 
                   7629: @example
                   7630: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
                   7631:   2dup 2>r execute 2r> execute ;
                   7632: 
                   7633: : 2+ ( n1 -- n2 )
                   7634:   [ comp' 1+ twice ] ;
                   7635: @end example
                   7636: 
                   7637: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
                   7638: works even if the executed compilation semantics has an effect on the
                   7639: data stack.
                   7640: 
                   7641: You can also define complete definitions with these words; this provides
                   7642: an alternative to using @code{does>} (@pxref{User-defined Defining
                   7643: Words}).  E.g., instead of
                   7644: 
                   7645: @example
                   7646: : curry+ ( n1 "name" -- )
                   7647:     CREATE ,
                   7648: DOES> ( n2 -- n1+n2 )
                   7649:     @@ + ;
                   7650: @end example
                   7651: 
                   7652: you could define
                   7653: 
                   7654: @example
                   7655: : curry+ ( n1 "name" -- )
                   7656:   \ name execution: ( n2 -- n1+n2 )
                   7657:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81      anton    7658: 
1.82      anton    7659: -3 curry+ 3-
                   7660: see 3-
                   7661: @end example
1.81      anton    7662: 
1.82      anton    7663: The sequence @code{>r : r>} is necessary, because @code{:} puts a
                   7664: colon-sys on the data stack that makes everything below it unaccessible.
1.81      anton    7665: 
1.82      anton    7666: This way of writing defining words is sometimes more, sometimes less
                   7667: convenient than using @code{does>} (@pxref{Advanced does> usage
                   7668: example}).  One advantage of this method is that it can be optimized
                   7669: better, because the compiler knows that the value compiled with
                   7670: @code{literal} is fixed, whereas the data associated with a
                   7671: @code{create}d word can be changed.
1.47      crook    7672: 
1.206     anton    7673: @c doc-[compile] !! not properly documented
                   7674: 
1.26      crook    7675: @c ----------------------------------------------------------
1.111     anton    7676: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26      crook    7677: @section  The Text Interpreter
                   7678: @cindex interpreter - outer
                   7679: @cindex text interpreter
                   7680: @cindex outer interpreter
1.1       anton    7681: 
1.34      anton    7682: @c Should we really describe all these ugly details?  IMO the text
                   7683: @c interpreter should be much cleaner, but that may not be possible within
                   7684: @c ANS Forth. - anton
1.44      crook    7685: @c nac-> I wanted to explain how it works to show how you can exploit
                   7686: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   7687: @c some of these gory details was very helpful to me. None of the textbooks
                   7688: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   7689: @c seems to positively avoid going into too much detail for some of
                   7690: @c the internals.
1.34      anton    7691: 
1.71      anton    7692: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
                   7693: @c it is; for the ugly details, I would prefer another place.  I wonder
                   7694: @c whether we should have a chapter before "Words" that describes some
                   7695: @c basic concepts referred to in words, and a chapter after "Words" that
                   7696: @c describes implementation details.
                   7697: 
1.29      crook    7698: The text interpreter@footnote{This is an expanded version of the
                   7699: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    7700: that processes input from the current input device. It is also called
                   7701: the outer interpreter, in contrast to the inner interpreter
                   7702: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   7703: implementations.
1.27      crook    7704: 
1.29      crook    7705: @cindex interpret state
                   7706: @cindex compile state
                   7707: The text interpreter operates in one of two states: @dfn{interpret
                   7708: state} and @dfn{compile state}. The current state is defined by the
1.71      anton    7709: aptly-named variable @code{state}.
1.29      crook    7710: 
                   7711: This section starts by describing how the text interpreter behaves when
                   7712: it is in interpret state, processing input from the user input device --
                   7713: the keyboard. This is the mode that a Forth system is in after it starts
                   7714: up.
                   7715: 
                   7716: @cindex input buffer
                   7717: @cindex terminal input buffer
                   7718: The text interpreter works from an area of memory called the @dfn{input
                   7719: buffer}@footnote{When the text interpreter is processing input from the
                   7720: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   7721: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   7722: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    7723: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    7724: leading spaces (called @dfn{delimiters}) then parses a string (a
                   7725: sequence of non-space characters) until it reaches either a space
                   7726: character or the end of the buffer. Having parsed a string, it makes two
                   7727: attempts to process it:
1.27      crook    7728: 
1.29      crook    7729: @cindex dictionary
1.27      crook    7730: @itemize @bullet
                   7731: @item
1.29      crook    7732: It looks for the string in a @dfn{dictionary} of definitions. If the
                   7733: string is found, the string names a @dfn{definition} (also known as a
                   7734: @dfn{word}) and the dictionary search returns information that allows
                   7735: the text interpreter to perform the word's @dfn{interpretation
                   7736: semantics}. In most cases, this simply means that the word will be
                   7737: executed.
1.27      crook    7738: @item
                   7739: If the string is not found in the dictionary, the text interpreter
1.29      crook    7740: attempts to treat it as a number, using the rules described in
                   7741: @ref{Number Conversion}. If the string represents a legal number in the
                   7742: current radix, the number is pushed onto a parameter stack (the data
                   7743: stack for integers, the floating-point stack for floating-point
                   7744: numbers).
                   7745: @end itemize
                   7746: 
                   7747: If both attempts fail, or if the word is found in the dictionary but has
                   7748: no interpretation semantics@footnote{This happens if the word was
                   7749: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   7750: remainder of the input buffer, issues an error message and waits for
                   7751: more input. If one of the attempts succeeds, the text interpreter
                   7752: repeats the parsing process until the whole of the input buffer has been
                   7753: processed, at which point it prints the status message ``@code{ ok}''
                   7754: and waits for more input.
                   7755: 
1.71      anton    7756: @c anton: this should be in the input stream subsection (or below it)
                   7757: 
1.29      crook    7758: @cindex parse area
                   7759: The text interpreter keeps track of its position in the input buffer by
                   7760: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   7761: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   7762: of the input buffer. The region from offset @code{>IN @@} to the end of
                   7763: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   7764: the text interpreter processes the contents of the input buffer by
                   7765: parsing strings from the parse area until the parse area is empty.}.
                   7766: This example shows how @code{>IN} changes as the text interpreter parses
                   7767: the input buffer:
                   7768: 
                   7769: @example
                   7770: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   7771:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   7772: 
                   7773: 1 2 3 remaining + remaining . 
                   7774: 
                   7775: : foo 1 2 3 remaining SWAP remaining ;
                   7776: @end example
                   7777: 
                   7778: @noindent
                   7779: The result is:
                   7780: 
                   7781: @example
                   7782: ->+ remaining .<-
                   7783: ->.<-5  ok
                   7784: 
                   7785: ->SWAP remaining ;-<
                   7786: ->;<-  ok
                   7787: @end example
                   7788: 
                   7789: @cindex parsing words
                   7790: The value of @code{>IN} can also be modified by a word in the input
                   7791: buffer that is executed by the text interpreter.  This means that a word
                   7792: can ``trick'' the text interpreter into either skipping a section of the
                   7793: input buffer@footnote{This is how parsing words work.} or into parsing a
                   7794: section twice. For example:
1.27      crook    7795: 
1.29      crook    7796: @example
1.71      anton    7797: : lat ." <<foo>>" ;
                   7798: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29      crook    7799: @end example
                   7800: 
                   7801: @noindent
                   7802: When @code{flat} is executed, this output is produced@footnote{Exercise
                   7803: for the reader: what would happen if the @code{3} were replaced with
                   7804: @code{4}?}:
                   7805: 
                   7806: @example
1.71      anton    7807: <<bar>><<foo>>
1.29      crook    7808: @end example
                   7809: 
1.71      anton    7810: This technique can be used to work around some of the interoperability
                   7811: problems of parsing words.  Of course, it's better to avoid parsing
                   7812: words where possible.
                   7813: 
1.29      crook    7814: @noindent
                   7815: Two important notes about the behaviour of the text interpreter:
1.27      crook    7816: 
                   7817: @itemize @bullet
                   7818: @item
                   7819: It processes each input string to completion before parsing additional
1.29      crook    7820: characters from the input buffer.
                   7821: @item
                   7822: It treats the input buffer as a read-only region (and so must your code).
                   7823: @end itemize
                   7824: 
                   7825: @noindent
                   7826: When the text interpreter is in compile state, its behaviour changes in
                   7827: these ways:
                   7828: 
                   7829: @itemize @bullet
                   7830: @item
                   7831: If a parsed string is found in the dictionary, the text interpreter will
                   7832: perform the word's @dfn{compilation semantics}. In most cases, this
                   7833: simply means that the execution semantics of the word will be appended
                   7834: to the current definition.
1.27      crook    7835: @item
1.29      crook    7836: When a number is encountered, it is compiled into the current definition
                   7837: (as a literal) rather than being pushed onto a parameter stack.
                   7838: @item
                   7839: If an error occurs, @code{state} is modified to put the text interpreter
                   7840: back into interpret state.
                   7841: @item
                   7842: Each time a line is entered from the keyboard, Gforth prints
                   7843: ``@code{ compiled}'' rather than `` @code{ok}''.
                   7844: @end itemize
                   7845: 
                   7846: @cindex text interpreter - input sources
                   7847: When the text interpreter is using an input device other than the
                   7848: keyboard, its behaviour changes in these ways:
                   7849: 
                   7850: @itemize @bullet
                   7851: @item
                   7852: When the parse area is empty, the text interpreter attempts to refill
                   7853: the input buffer from the input source. When the input source is
1.71      anton    7854: exhausted, the input source is set back to the previous input source.
1.29      crook    7855: @item
                   7856: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7857: time the parse area is emptied.
                   7858: @item
                   7859: If an error occurs, the input source is set back to the user input
                   7860: device.
1.27      crook    7861: @end itemize
1.21      crook    7862: 
1.49      anton    7863: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7864: 
1.26      crook    7865: doc->in
1.27      crook    7866: doc-source
                   7867: 
1.26      crook    7868: doc-tib
                   7869: doc-#tib
1.1       anton    7870: 
1.44      crook    7871: 
1.26      crook    7872: @menu
1.67      anton    7873: * Input Sources::               
                   7874: * Number Conversion::           
                   7875: * Interpret/Compile states::    
                   7876: * Interpreter Directives::      
1.26      crook    7877: @end menu
1.1       anton    7878: 
1.29      crook    7879: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7880: @subsection Input Sources
                   7881: @cindex input sources
                   7882: @cindex text interpreter - input sources
                   7883: 
1.44      crook    7884: By default, the text interpreter processes input from the user input
1.29      crook    7885: device (the keyboard) when Forth starts up. The text interpreter can
                   7886: process input from any of these sources:
                   7887: 
                   7888: @itemize @bullet
                   7889: @item
                   7890: The user input device -- the keyboard.
                   7891: @item
                   7892: A file, using the words described in @ref{Forth source files}.
                   7893: @item
                   7894: A block, using the words described in @ref{Blocks}.
                   7895: @item
                   7896: A text string, using @code{evaluate}.
                   7897: @end itemize
                   7898: 
                   7899: A program can identify the current input device from the values of
                   7900: @code{source-id} and @code{blk}.
                   7901: 
1.44      crook    7902: 
1.29      crook    7903: doc-source-id
                   7904: doc-blk
                   7905: 
                   7906: doc-save-input
                   7907: doc-restore-input
                   7908: 
                   7909: doc-evaluate
1.111     anton    7910: doc-query
1.1       anton    7911: 
1.29      crook    7912: 
1.44      crook    7913: 
1.29      crook    7914: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7915: @subsection Number Conversion
                   7916: @cindex number conversion
                   7917: @cindex double-cell numbers, input format
                   7918: @cindex input format for double-cell numbers
                   7919: @cindex single-cell numbers, input format
                   7920: @cindex input format for single-cell numbers
                   7921: @cindex floating-point numbers, input format
                   7922: @cindex input format for floating-point numbers
1.1       anton    7923: 
1.29      crook    7924: This section describes the rules that the text interpreter uses when it
                   7925: tries to convert a string into a number.
1.1       anton    7926: 
1.26      crook    7927: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7928: number base@footnote{For example, 0-9 when the number base is decimal or
                   7929: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7930: 
1.26      crook    7931: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7932: 
1.29      crook    7933: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7934: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7935: 
1.26      crook    7936: Let * represent any number of instances of the previous character
                   7937: (including none).
1.1       anton    7938: 
1.26      crook    7939: Let any other character represent itself.
1.1       anton    7940: 
1.29      crook    7941: @noindent
1.26      crook    7942: Now, the conversion rules are:
1.21      crook    7943: 
1.26      crook    7944: @itemize @bullet
                   7945: @item
                   7946: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7947: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7948: @item
                   7949: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7950: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7951: arithmetic. Examples are -45 -5681 -0
                   7952: @item
                   7953: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7954: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7955: (all three of these represent the same number).
1.26      crook    7956: @item
                   7957: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7958: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7959: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7960: -34.65 (all three of these represent the same number).
1.26      crook    7961: @item
1.29      crook    7962: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7963: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7964: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7965: number) +12.E-4
1.26      crook    7966: @end itemize
1.1       anton    7967: 
1.174     anton    7968: By default, the number base used for integer number conversion is
                   7969: given by the contents of the variable @code{base}.  Note that a lot of
1.35      anton    7970: confusion can result from unexpected values of @code{base}.  If you
1.174     anton    7971: change @code{base} anywhere, make sure to save the old value and
                   7972: restore it afterwards; better yet, use @code{base-execute}, which does
                   7973: this for you.  In general I recommend keeping @code{base} decimal, and
1.35      anton    7974: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7975: 
1.29      crook    7976: doc-dpl
1.174     anton    7977: doc-base-execute
1.26      crook    7978: doc-base
                   7979: doc-hex
                   7980: doc-decimal
1.1       anton    7981: 
1.26      crook    7982: @cindex '-prefix for character strings
                   7983: @cindex &-prefix for decimal numbers
1.133     anton    7984: @cindex #-prefix for decimal numbers
1.26      crook    7985: @cindex %-prefix for binary numbers
                   7986: @cindex $-prefix for hexadecimal numbers
1.133     anton    7987: @cindex 0x-prefix for hexadecimal numbers
1.35      anton    7988: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7989: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7990: implementing @code{$} etc. as parsing words that process the subsequent
                   7991: number in the input stream and push it onto the stack. For example, see
                   7992: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7993: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7994: is required between the prefix and the number.} before the first digit
1.133     anton    7995: of an (integer) number. The following prefixes are supported:
1.1       anton    7996: 
1.26      crook    7997: @itemize @bullet
                   7998: @item
1.35      anton    7999: @code{&} -- decimal
1.26      crook    8000: @item
1.133     anton    8001: @code{#} -- decimal
                   8002: @item
1.35      anton    8003: @code{%} -- binary
1.26      crook    8004: @item
1.35      anton    8005: @code{$} -- hexadecimal
1.26      crook    8006: @item
1.133     anton    8007: @code{0x} -- hexadecimal, if base<33.
                   8008: @item
                   8009: @code{'} -- numeric value (e.g., ASCII code) of next character; an
                   8010: optional @code{'} may be present after the character.
1.26      crook    8011: @end itemize
1.1       anton    8012: 
1.26      crook    8013: Here are some examples, with the equivalent decimal number shown after
                   8014: in braces:
1.1       anton    8015: 
1.26      crook    8016: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133     anton    8017: 'A (65),
                   8018: -'a' (-97),
1.26      crook    8019: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    8020: 
1.26      crook    8021: @cindex number conversion - traps for the unwary
1.29      crook    8022: @noindent
1.26      crook    8023: Number conversion has a number of traps for the unwary:
1.1       anton    8024: 
1.26      crook    8025: @itemize @bullet
                   8026: @item
                   8027: You cannot determine the current number base using the code sequence
1.35      anton    8028: @code{base @@ .} -- the number base is always 10 in the current number
                   8029: base. Instead, use something like @code{base @@ dec.}
1.26      crook    8030: @item
                   8031: If the number base is set to a value greater than 14 (for example,
                   8032: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   8033: it to be intepreted as either a single-precision integer or a
                   8034: floating-point number (Gforth treats it as an integer). The ambiguity
                   8035: can be resolved by explicitly stating the sign of the mantissa and/or
                   8036: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   8037: ambiguity arises; either representation will be treated as a
                   8038: floating-point number.
                   8039: @item
1.29      crook    8040: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    8041: It is used to specify file types.
                   8042: @item
1.72      anton    8043: ANS Forth requires the @code{.} of a double-precision number to be the
                   8044: final character in the string.  Gforth allows the @code{.} to be
                   8045: anywhere after the first digit.
1.26      crook    8046: @item
                   8047: The number conversion process does not check for overflow.
                   8048: @item
1.72      anton    8049: In an ANS Forth program @code{base} is required to be decimal when
                   8050: converting floating-point numbers.  In Gforth, number conversion to
                   8051: floating-point numbers always uses base &10, irrespective of the value
                   8052: of @code{base}.
1.26      crook    8053: @end itemize
1.1       anton    8054: 
1.49      anton    8055: You can read numbers into your programs with the words described in
1.181     anton    8056: @ref{Line input and conversion}.
1.1       anton    8057: 
1.82      anton    8058: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26      crook    8059: @subsection Interpret/Compile states
                   8060: @cindex Interpret/Compile states
1.1       anton    8061: 
1.29      crook    8062: A standard program is not permitted to change @code{state}
                   8063: explicitly. However, it can change @code{state} implicitly, using the
                   8064: words @code{[} and @code{]}. When @code{[} is executed it switches
                   8065: @code{state} to interpret state, and therefore the text interpreter
                   8066: starts interpreting. When @code{]} is executed it switches @code{state}
                   8067: to compile state and therefore the text interpreter starts
1.44      crook    8068: compiling. The most common usage for these words is for switching into
                   8069: interpret state and back from within a colon definition; this technique
1.49      anton    8070: can be used to compile a literal (for an example, @pxref{Literals}) or
                   8071: for conditional compilation (for an example, @pxref{Interpreter
                   8072: Directives}).
1.44      crook    8073: 
1.35      anton    8074: 
                   8075: @c This is a bad example: It's non-standard, and it's not necessary.
                   8076: @c However, I can't think of a good example for switching into compile
                   8077: @c state when there is no current word (@code{state}-smart words are not a
                   8078: @c good reason).  So maybe we should use an example for switching into
                   8079: @c interpret @code{state} in a colon def. - anton
1.44      crook    8080: @c nac-> I agree. I started out by putting in the example, then realised
                   8081: @c that it was non-ANS, so wrote more words around it. I hope this
                   8082: @c re-written version is acceptable to you. I do want to keep the example
                   8083: @c as it is helpful for showing what is and what is not portable, particularly
                   8084: @c where it outlaws a style in common use.
                   8085: 
1.72      anton    8086: @c anton: it's more important to show what's portable.  After we have done
1.83      anton    8087: @c that, we can also show what's not.  In any case, I have written a
                   8088: @c section Compiling Words which also deals with [ ].
1.35      anton    8089: 
1.95      anton    8090: @c  !! The following example does not work in Gforth 0.5.9 or later.
1.29      crook    8091: 
1.95      anton    8092: @c  @code{[} and @code{]} also give you the ability to switch into compile
                   8093: @c  state and back, but we cannot think of any useful Standard application
                   8094: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
                   8095: 
                   8096: @c  @example
                   8097: @c  : AA ." this is A" ;
                   8098: @c  : BB ." this is B" ;
                   8099: @c  : CC ." this is C" ;
                   8100: 
                   8101: @c  create table ] aa bb cc [
                   8102: 
                   8103: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   8104: @c    cells table + @@ execute ;
                   8105: @c  @end example
                   8106: 
                   8107: @c  This example builds a jump table; @code{0 go} will display ``@code{this
                   8108: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   8109: @c  defining @code{table} like this:
                   8110: 
                   8111: @c  @example
                   8112: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
                   8113: @c  @end example
                   8114: 
                   8115: @c  The problem with this code is that the definition of @code{table} is not
                   8116: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
                   8117: @c  @i{may} work on systems where code space and data space co-incide, the
                   8118: @c  Standard only allows data space to be assigned for a @code{CREATE}d
                   8119: @c  word. In addition, the Standard only allows @code{@@} to access data
                   8120: @c  space, whilst this example is using it to access code space. The only
                   8121: @c  portable, Standard way to build this table is to build it in data space,
                   8122: @c  like this:
                   8123: 
                   8124: @c  @example
                   8125: @c  create table ' aa , ' bb , ' cc ,
                   8126: @c  @end example
1.29      crook    8127: 
1.95      anton    8128: @c  doc-state
1.44      crook    8129: 
1.29      crook    8130: 
1.82      anton    8131: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
1.26      crook    8132: @subsection Interpreter Directives
                   8133: @cindex interpreter directives
1.72      anton    8134: @cindex conditional compilation
1.1       anton    8135: 
1.29      crook    8136: These words are usually used in interpret state; typically to control
                   8137: which parts of a source file are processed by the text
1.26      crook    8138: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   8139: supplements these with a rich set of immediate control structure words
                   8140: to compensate for the fact that the non-immediate versions can only be
1.29      crook    8141: used in compile state (@pxref{Control Structures}). Typical usages:
                   8142: 
                   8143: @example
1.72      anton    8144: FALSE Constant HAVE-ASSEMBLER
1.29      crook    8145: .
                   8146: .
1.72      anton    8147: HAVE-ASSEMBLER [IF]
1.29      crook    8148: : ASSEMBLER-FEATURE
                   8149:   ...
                   8150: ;
                   8151: [ENDIF]
                   8152: .
                   8153: .
                   8154: : SEE
                   8155:   ... \ general-purpose SEE code
1.72      anton    8156:   [ HAVE-ASSEMBLER [IF] ]
1.29      crook    8157:   ... \ assembler-specific SEE code
                   8158:   [ [ENDIF] ]
                   8159: ;
                   8160: @end example
1.1       anton    8161: 
1.44      crook    8162: 
1.26      crook    8163: doc-[IF]
                   8164: doc-[ELSE]
                   8165: doc-[THEN]
                   8166: doc-[ENDIF]
1.1       anton    8167: 
1.26      crook    8168: doc-[IFDEF]
                   8169: doc-[IFUNDEF]
1.1       anton    8170: 
1.26      crook    8171: doc-[?DO]
                   8172: doc-[DO]
                   8173: doc-[FOR]
                   8174: doc-[LOOP]
                   8175: doc-[+LOOP]
                   8176: doc-[NEXT]
1.1       anton    8177: 
1.26      crook    8178: doc-[BEGIN]
                   8179: doc-[UNTIL]
                   8180: doc-[AGAIN]
                   8181: doc-[WHILE]
                   8182: doc-[REPEAT]
1.1       anton    8183: 
1.27      crook    8184: 
1.26      crook    8185: @c -------------------------------------------------------------
1.111     anton    8186: @node The Input Stream, Word Lists, The Text Interpreter, Words
                   8187: @section The Input Stream
                   8188: @cindex input stream
                   8189: 
                   8190: @c !! integrate this better with the "Text Interpreter" section
                   8191: The text interpreter reads from the input stream, which can come from
                   8192: several sources (@pxref{Input Sources}).  Some words, in particular
                   8193: defining words, but also words like @code{'}, read parameters from the
                   8194: input stream instead of from the stack.
                   8195: 
                   8196: Such words are called parsing words, because they parse the input
                   8197: stream.  Parsing words are hard to use in other words, because it is
                   8198: hard to pass program-generated parameters through the input stream.
                   8199: They also usually have an unintuitive combination of interpretation and
                   8200: compilation semantics when implemented naively, leading to various
                   8201: approaches that try to produce a more intuitive behaviour
                   8202: (@pxref{Combined words}).
                   8203: 
                   8204: It should be obvious by now that parsing words are a bad idea.  If you
                   8205: want to implement a parsing word for convenience, also provide a factor
                   8206: of the word that does not parse, but takes the parameters on the stack.
                   8207: To implement the parsing word on top if it, you can use the following
                   8208: words:
                   8209: 
                   8210: @c anton: these belong in the input stream section
                   8211: doc-parse
1.138     anton    8212: doc-parse-name
1.111     anton    8213: doc-parse-word
                   8214: doc-name
                   8215: doc-word
                   8216: doc-refill
                   8217: 
                   8218: Conversely, if you have the bad luck (or lack of foresight) to have to
                   8219: deal with parsing words without having such factors, how do you pass a
                   8220: string that is not in the input stream to it?
                   8221: 
                   8222: doc-execute-parsing
                   8223: 
1.146     anton    8224: A definition of this word in ANS Forth is provided in
                   8225: @file{compat/execute-parsing.fs}.
                   8226: 
1.111     anton    8227: If you want to run a parsing word on a file, the following word should
                   8228: help:
                   8229: 
                   8230: doc-execute-parsing-file
                   8231: 
                   8232: @c -------------------------------------------------------------
                   8233: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26      crook    8234: @section Word Lists
                   8235: @cindex word lists
1.32      anton    8236: @cindex header space
1.1       anton    8237: 
1.36      anton    8238: A wordlist is a list of named words; you can add new words and look up
                   8239: words by name (and you can remove words in a restricted way with
                   8240: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   8241: 
                   8242: @cindex search order stack
                   8243: The text interpreter searches the wordlists present in the search order
                   8244: (a stack of wordlists), from the top to the bottom.  Within each
                   8245: wordlist, the search starts conceptually at the newest word; i.e., if
                   8246: two words in a wordlist have the same name, the newer word is found.
1.1       anton    8247: 
1.26      crook    8248: @cindex compilation word list
1.36      anton    8249: New words are added to the @dfn{compilation wordlist} (aka current
                   8250: wordlist).
1.1       anton    8251: 
1.36      anton    8252: @cindex wid
                   8253: A word list is identified by a cell-sized word list identifier (@i{wid})
                   8254: in much the same way as a file is identified by a file handle. The
                   8255: numerical value of the wid has no (portable) meaning, and might change
                   8256: from session to session.
1.1       anton    8257: 
1.29      crook    8258: The ANS Forth ``Search order'' word set is intended to provide a set of
                   8259: low-level tools that allow various different schemes to be
1.74      anton    8260: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26      crook    8261: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    8262: Forth.
1.1       anton    8263: 
1.27      crook    8264: @comment TODO: locals section refers to here, saying that every word list (aka
                   8265: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78      anton    8266: @c anton: but better in a separate subsection on wordlist internals
1.1       anton    8267: 
1.45      crook    8268: @comment TODO: document markers, reveal, tables, mappedwordlist
                   8269: 
                   8270: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    8271: @comment word from the source files, rather than some alias.
1.44      crook    8272: 
1.26      crook    8273: doc-forth-wordlist
                   8274: doc-definitions
                   8275: doc-get-current
                   8276: doc-set-current
                   8277: doc-get-order
1.185     anton    8278: doc-set-order
1.26      crook    8279: doc-wordlist
1.30      anton    8280: doc-table
1.79      anton    8281: doc->order
1.36      anton    8282: doc-previous
1.26      crook    8283: doc-also
1.185     anton    8284: doc-forth
1.26      crook    8285: doc-only
1.185     anton    8286: doc-order
1.15      anton    8287: 
1.26      crook    8288: doc-find
                   8289: doc-search-wordlist
1.15      anton    8290: 
1.26      crook    8291: doc-words
                   8292: doc-vlist
1.44      crook    8293: @c doc-words-deferred
1.1       anton    8294: 
1.74      anton    8295: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26      crook    8296: doc-root
                   8297: doc-vocabulary
                   8298: doc-seal
                   8299: doc-vocs
                   8300: doc-current
                   8301: doc-context
1.1       anton    8302: 
1.44      crook    8303: 
1.26      crook    8304: @menu
1.75      anton    8305: * Vocabularies::                
1.67      anton    8306: * Why use word lists?::         
1.75      anton    8307: * Word list example::           
1.26      crook    8308: @end menu
                   8309: 
1.75      anton    8310: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
                   8311: @subsection Vocabularies
                   8312: @cindex Vocabularies, detailed explanation
                   8313: 
                   8314: Here is an example of creating and using a new wordlist using ANS
                   8315: Forth words:
                   8316: 
                   8317: @example
                   8318: wordlist constant my-new-words-wordlist
                   8319: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
                   8320: 
                   8321: \ add it to the search order
                   8322: also my-new-words
                   8323: 
                   8324: \ alternatively, add it to the search order and make it
                   8325: \ the compilation word list
                   8326: also my-new-words definitions
                   8327: \ type "order" to see the problem
                   8328: @end example
                   8329: 
                   8330: The problem with this example is that @code{order} has no way to
                   8331: associate the name @code{my-new-words} with the wid of the word list (in
                   8332: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   8333: that has no associated name). There is no Standard way of associating a
                   8334: name with a wid.
                   8335: 
                   8336: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   8337: associates a name with a wid:
                   8338: 
                   8339: @example
                   8340: vocabulary my-new-words
                   8341: 
                   8342: \ add it to the search order
                   8343: also my-new-words
                   8344: 
                   8345: \ alternatively, add it to the search order and make it
                   8346: \ the compilation word list
                   8347: my-new-words definitions
                   8348: \ type "order" to see that the problem is solved
                   8349: @end example
                   8350: 
                   8351: 
                   8352: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26      crook    8353: @subsection Why use word lists?
                   8354: @cindex word lists - why use them?
                   8355: 
1.74      anton    8356: Here are some reasons why people use wordlists:
1.26      crook    8357: 
                   8358: @itemize @bullet
1.74      anton    8359: 
                   8360: @c anton: Gforth's hashing implementation makes the search speed
                   8361: @c independent from the number of words.  But it is linear with the number
                   8362: @c of wordlists that have to be searched, so in effect using more wordlists
                   8363: @c actually slows down compilation.
                   8364: 
                   8365: @c @item
                   8366: @c To improve compilation speed by reducing the number of header space
                   8367: @c entries that must be searched. This is achieved by creating a new
                   8368: @c word list that contains all of the definitions that are used in the
                   8369: @c definition of a Forth system but which would not usually be used by
                   8370: @c programs running on that system. That word list would be on the search
                   8371: @c list when the Forth system was compiled but would be removed from the
                   8372: @c search list for normal operation. This can be a useful technique for
                   8373: @c low-performance systems (for example, 8-bit processors in embedded
                   8374: @c systems) but is unlikely to be necessary in high-performance desktop
                   8375: @c systems.
                   8376: 
1.26      crook    8377: @item
                   8378: To prevent a set of words from being used outside the context in which
                   8379: they are valid. Two classic examples of this are an integrated editor
                   8380: (all of the edit commands are defined in a separate word list; the
                   8381: search order is set to the editor word list when the editor is invoked;
                   8382: the old search order is restored when the editor is terminated) and an
                   8383: integrated assembler (the op-codes for the machine are defined in a
                   8384: separate word list which is used when a @code{CODE} word is defined).
1.74      anton    8385: 
                   8386: @item
                   8387: To organize the words of an application or library into a user-visible
                   8388: set (in @code{forth-wordlist} or some other common wordlist) and a set
                   8389: of helper words used just for the implementation (hidden in a separate
1.75      anton    8390: wordlist).  This keeps @code{words}' output smaller, separates
                   8391: implementation and interface, and reduces the chance of name conflicts
                   8392: within the common wordlist.
1.74      anton    8393: 
1.26      crook    8394: @item
                   8395: To prevent a name-space clash between multiple definitions with the same
                   8396: name. For example, when building a cross-compiler you might have a word
                   8397: @code{IF} that generates conditional code for your target system. By
                   8398: placing this definition in a different word list you can control whether
                   8399: the host system's @code{IF} or the target system's @code{IF} get used in
                   8400: any particular context by controlling the order of the word lists on the
                   8401: search order stack.
1.74      anton    8402: 
1.26      crook    8403: @end itemize
1.1       anton    8404: 
1.74      anton    8405: The downsides of using wordlists are:
                   8406: 
                   8407: @itemize
                   8408: 
                   8409: @item
                   8410: Debugging becomes more cumbersome.
                   8411: 
                   8412: @item
                   8413: Name conflicts worked around with wordlists are still there, and you
                   8414: have to arrange the search order carefully to get the desired results;
                   8415: if you forget to do that, you get hard-to-find errors (as in any case
                   8416: where you read the code differently from the compiler; @code{see} can
1.75      anton    8417: help seeing which of several possible words the name resolves to in such
                   8418: cases).  @code{See} displays just the name of the words, not what
                   8419: wordlist they belong to, so it might be misleading.  Using unique names
                   8420: is a better approach to avoid name conflicts.
1.74      anton    8421: 
                   8422: @item
                   8423: You have to explicitly undo any changes to the search order.  In many
                   8424: cases it would be more convenient if this happened implicitly.  Gforth
                   8425: currently does not provide such a feature, but it may do so in the
                   8426: future.
                   8427: @end itemize
                   8428: 
                   8429: 
1.75      anton    8430: @node Word list example,  , Why use word lists?, Word Lists
                   8431: @subsection Word list example
                   8432: @cindex word lists - example
1.1       anton    8433: 
1.74      anton    8434: The following example is from the
                   8435: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   8436: garbage collector} and uses wordlists to separate public words from
                   8437: helper words:
                   8438: 
                   8439: @example
                   8440: get-current ( wid )
                   8441: vocabulary garbage-collector also garbage-collector definitions
                   8442: ... \ define helper words
                   8443: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
                   8444: ... \ define the public (i.e., API) words
                   8445:     \ they can refer to the helper words
                   8446: previous \ restore original search order (helper words become invisible)
                   8447: @end example
                   8448: 
1.26      crook    8449: @c -------------------------------------------------------------
                   8450: @node Environmental Queries, Files, Word Lists, Words
                   8451: @section Environmental Queries
                   8452: @cindex environmental queries
1.21      crook    8453: 
1.26      crook    8454: ANS Forth introduced the idea of ``environmental queries'' as a way
                   8455: for a program running on a system to determine certain characteristics of the system.
                   8456: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    8457: 
1.32      anton    8458: The Standard requires that the header space used for environmental queries
                   8459: be distinct from the header space used for definitions.
1.21      crook    8460: 
1.26      crook    8461: Typically, environmental queries are supported by creating a set of
1.29      crook    8462: definitions in a word list that is @i{only} used during environmental
1.26      crook    8463: queries; that is what Gforth does. There is no Standard way of adding
                   8464: definitions to the set of recognised environmental queries, but any
                   8465: implementation that supports the loading of optional word sets must have
                   8466: some mechanism for doing this (after loading the word set, the
                   8467: associated environmental query string must return @code{true}). In
                   8468: Gforth, the word list used to honour environmental queries can be
                   8469: manipulated just like any other word list.
1.21      crook    8470: 
1.44      crook    8471: 
1.26      crook    8472: doc-environment?
                   8473: doc-environment-wordlist
1.21      crook    8474: 
1.26      crook    8475: doc-gforth
                   8476: doc-os-class
1.21      crook    8477: 
1.44      crook    8478: 
1.26      crook    8479: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   8480: returning two items on the stack, querying it using @code{environment?}
                   8481: will return an additional item; the @code{true} flag that shows that the
                   8482: string was recognised.
1.21      crook    8483: 
1.26      crook    8484: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    8485: 
1.26      crook    8486: Here are some examples of using environmental queries:
1.21      crook    8487: 
1.26      crook    8488: @example
                   8489: s" address-unit-bits" environment? 0=
                   8490: [IF]
                   8491:      cr .( environmental attribute address-units-bits unknown... ) cr
1.75      anton    8492: [ELSE]
                   8493:      drop \ ensure balanced stack effect
1.26      crook    8494: [THEN]
1.21      crook    8495: 
1.75      anton    8496: \ this might occur in the prelude of a standard program that uses THROW
                   8497: s" exception" environment? [IF]
                   8498:    0= [IF]
                   8499:       : throw abort" exception thrown" ;
                   8500:    [THEN]
                   8501: [ELSE] \ we don't know, so make sure
                   8502:    : throw abort" exception thrown" ;
                   8503: [THEN]
1.21      crook    8504: 
1.26      crook    8505: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   8506:                         [ELSE] .( Not Gforth..) [THEN]
1.75      anton    8507: 
                   8508: \ a program using v*
                   8509: s" gforth" environment? [IF]
                   8510:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
                   8511:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8512:      >r swap 2swap swap 0e r> 0 ?DO
1.190     anton    8513:        dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75      anton    8514:      LOOP
                   8515:      2drop 2drop ; 
                   8516:   [THEN]
                   8517: [ELSE] \ 
                   8518:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8519:   ...
                   8520: [THEN]
1.26      crook    8521: @end example
1.21      crook    8522: 
1.26      crook    8523: Here is an example of adding a definition to the environment word list:
1.21      crook    8524: 
1.26      crook    8525: @example
                   8526: get-current environment-wordlist set-current
                   8527: true constant block
                   8528: true constant block-ext
                   8529: set-current
                   8530: @end example
1.21      crook    8531: 
1.26      crook    8532: You can see what definitions are in the environment word list like this:
1.21      crook    8533: 
1.26      crook    8534: @example
1.79      anton    8535: environment-wordlist >order words previous
1.26      crook    8536: @end example
1.21      crook    8537: 
                   8538: 
1.26      crook    8539: @c -------------------------------------------------------------
                   8540: @node Files, Blocks, Environmental Queries, Words
                   8541: @section Files
1.28      crook    8542: @cindex files
                   8543: @cindex I/O - file-handling
1.21      crook    8544: 
1.26      crook    8545: Gforth provides facilities for accessing files that are stored in the
                   8546: host operating system's file-system. Files that are processed by Gforth
                   8547: can be divided into two categories:
1.21      crook    8548: 
1.23      crook    8549: @itemize @bullet
                   8550: @item
1.29      crook    8551: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    8552: @item
1.29      crook    8553: Files that are processed by some other program (@dfn{general files}).
1.26      crook    8554: @end itemize
                   8555: 
                   8556: @menu
1.48      anton    8557: * Forth source files::          
                   8558: * General files::               
1.167     anton    8559: * Redirection::                 
1.48      anton    8560: * Search Paths::                
1.26      crook    8561: @end menu
                   8562: 
                   8563: @c -------------------------------------------------------------
                   8564: @node Forth source files, General files, Files, Files
                   8565: @subsection Forth source files
                   8566: @cindex including files
                   8567: @cindex Forth source files
1.21      crook    8568: 
1.26      crook    8569: The simplest way to interpret the contents of a file is to use one of
                   8570: these two formats:
1.21      crook    8571: 
1.26      crook    8572: @example
                   8573: include mysource.fs
                   8574: s" mysource.fs" included
                   8575: @end example
1.21      crook    8576: 
1.75      anton    8577: You usually want to include a file only if it is not included already
1.26      crook    8578: (by, say, another source file). In that case, you can use one of these
1.45      crook    8579: three formats:
1.21      crook    8580: 
1.26      crook    8581: @example
                   8582: require mysource.fs
                   8583: needs mysource.fs
                   8584: s" mysource.fs" required
                   8585: @end example
1.21      crook    8586: 
1.26      crook    8587: @cindex stack effect of included files
                   8588: @cindex including files, stack effect
1.45      crook    8589: It is good practice to write your source files such that interpreting them
                   8590: does not change the stack. Source files designed in this way can be used with
1.26      crook    8591: @code{required} and friends without complications. For example:
1.21      crook    8592: 
1.26      crook    8593: @example
1.75      anton    8594: 1024 require foo.fs drop
1.26      crook    8595: @end example
1.21      crook    8596: 
1.75      anton    8597: Here you want to pass the argument 1024 (e.g., a buffer size) to
                   8598: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
                   8599: ), which allows its use with @code{require}.  Of course with such
                   8600: parameters to required files, you have to ensure that the first
                   8601: @code{require} fits for all uses (i.e., @code{require} it early in the
                   8602: master load file).
1.44      crook    8603: 
1.26      crook    8604: doc-include-file
                   8605: doc-included
1.28      crook    8606: doc-included?
1.26      crook    8607: doc-include
                   8608: doc-required
                   8609: doc-require
                   8610: doc-needs
1.75      anton    8611: @c doc-init-included-files @c internal
                   8612: doc-sourcefilename
                   8613: doc-sourceline#
1.44      crook    8614: 
1.26      crook    8615: A definition in ANS Forth for @code{required} is provided in
                   8616: @file{compat/required.fs}.
1.21      crook    8617: 
1.26      crook    8618: @c -------------------------------------------------------------
1.167     anton    8619: @node General files, Redirection, Forth source files, Files
1.26      crook    8620: @subsection General files
                   8621: @cindex general files
                   8622: @cindex file-handling
1.21      crook    8623: 
1.75      anton    8624: Files are opened/created by name and type. The following file access
                   8625: methods (FAMs) are recognised:
1.44      crook    8626: 
1.75      anton    8627: @cindex fam (file access method)
1.26      crook    8628: doc-r/o
                   8629: doc-r/w
                   8630: doc-w/o
                   8631: doc-bin
1.1       anton    8632: 
1.44      crook    8633: 
1.26      crook    8634: When a file is opened/created, it returns a file identifier,
1.29      crook    8635: @i{wfileid} that is used for all other file commands. All file
                   8636: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    8637: successful operation and an implementation-defined non-zero value in the
                   8638: case of an error.
1.21      crook    8639: 
1.44      crook    8640: 
1.26      crook    8641: doc-open-file
                   8642: doc-create-file
1.21      crook    8643: 
1.26      crook    8644: doc-close-file
                   8645: doc-delete-file
                   8646: doc-rename-file
                   8647: doc-read-file
                   8648: doc-read-line
1.154     anton    8649: doc-key-file
                   8650: doc-key?-file
1.26      crook    8651: doc-write-file
                   8652: doc-write-line
                   8653: doc-emit-file
                   8654: doc-flush-file
1.21      crook    8655: 
1.26      crook    8656: doc-file-status
                   8657: doc-file-position
                   8658: doc-reposition-file
                   8659: doc-file-size
                   8660: doc-resize-file
1.21      crook    8661: 
1.93      anton    8662: doc-slurp-file
                   8663: doc-slurp-fid
1.112     anton    8664: doc-stdin
                   8665: doc-stdout
                   8666: doc-stderr
1.44      crook    8667: 
1.26      crook    8668: @c ---------------------------------------------------------
1.167     anton    8669: @node Redirection, Search Paths, General files, Files
                   8670: @subsection Redirection
                   8671: @cindex Redirection
                   8672: @cindex Input Redirection
                   8673: @cindex Output Redirection
                   8674: 
                   8675: You can redirect the output of @code{type} and @code{emit} and all the
                   8676: words that use them (all output words that don't have an explicit
1.174     anton    8677: target file) to an arbitrary file with the @code{outfile-execute},
                   8678: used like this:
1.167     anton    8679: 
                   8680: @example
1.174     anton    8681: : some-warning ( n -- )
                   8682:     cr ." warning# " . ;
                   8683: 
1.167     anton    8684: : print-some-warning ( n -- )
1.174     anton    8685:     ['] some-warning stderr outfile-execute ;
1.167     anton    8686: @end example
                   8687: 
1.174     anton    8688: After @code{some-warning} is executed, the original output direction
                   8689: is restored; this construct is safe against exceptions.  Similarly,
                   8690: there is @code{infile-execute} for redirecting the input of @code{key}
                   8691: and its users (any input word that does not take a file explicitly).
                   8692: 
                   8693: doc-outfile-execute
                   8694: doc-infile-execute
1.167     anton    8695: 
                   8696: If you do not want to redirect the input or output to a file, you can
                   8697: also make use of the fact that @code{key}, @code{emit} and @code{type}
                   8698: are deferred words (@pxref{Deferred Words}).  However, in that case
                   8699: you have to worry about the restoration and the protection against
                   8700: exceptions yourself; also, note that for redirecting the output in
                   8701: this way, you have to redirect both @code{emit} and @code{type}.
                   8702: 
                   8703: @c ---------------------------------------------------------
                   8704: @node Search Paths,  , Redirection, Files
1.26      crook    8705: @subsection Search Paths
                   8706: @cindex path for @code{included}
                   8707: @cindex file search path
                   8708: @cindex @code{include} search path
                   8709: @cindex search path for files
1.21      crook    8710: 
1.26      crook    8711: If you specify an absolute filename (i.e., a filename starting with
                   8712: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   8713: @samp{C:...})) for @code{included} and friends, that file is included
                   8714: just as you would expect.
1.21      crook    8715: 
1.75      anton    8716: If the filename starts with @file{./}, this refers to the directory that
                   8717: the present file was @code{included} from.  This allows files to include
                   8718: other files relative to their own position (irrespective of the current
                   8719: working directory or the absolute position).  This feature is essential
                   8720: for libraries consisting of several files, where a file may include
                   8721: other files from the library.  It corresponds to @code{#include "..."}
                   8722: in C. If the current input source is not a file, @file{.} refers to the
                   8723: directory of the innermost file being included, or, if there is no file
                   8724: being included, to the current working directory.
                   8725: 
                   8726: For relative filenames (not starting with @file{./}), Gforth uses a
                   8727: search path similar to Forth's search order (@pxref{Word Lists}). It
                   8728: tries to find the given filename in the directories present in the path,
                   8729: and includes the first one it finds. There are separate search paths for
                   8730: Forth source files and general files.  If the search path contains the
                   8731: directory @file{.}, this refers to the directory of the current file, or
                   8732: the working directory, as if the file had been specified with @file{./}.
1.21      crook    8733: 
1.26      crook    8734: Use @file{~+} to refer to the current working directory (as in the
                   8735: @code{bash}).
1.1       anton    8736: 
1.75      anton    8737: @c anton: fold the following subsubsections into this subsection?
1.1       anton    8738: 
1.48      anton    8739: @menu
1.75      anton    8740: * Source Search Paths::         
1.48      anton    8741: * General Search Paths::        
                   8742: @end menu
                   8743: 
1.26      crook    8744: @c ---------------------------------------------------------
1.75      anton    8745: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
                   8746: @subsubsection Source Search Paths
                   8747: @cindex search path control, source files
1.5       anton    8748: 
1.26      crook    8749: The search path is initialized when you start Gforth (@pxref{Invoking
1.75      anton    8750: Gforth}). You can display it and change it using @code{fpath} in
                   8751: combination with the general path handling words.
1.5       anton    8752: 
1.75      anton    8753: doc-fpath
                   8754: @c the functionality of the following words is easily available through
                   8755: @c   fpath and the general path words.  The may go away.
                   8756: @c doc-.fpath
                   8757: @c doc-fpath+
                   8758: @c doc-fpath=
                   8759: @c doc-open-fpath-file
1.44      crook    8760: 
                   8761: @noindent
1.26      crook    8762: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    8763: 
1.26      crook    8764: @example
1.75      anton    8765: fpath path= /usr/lib/forth/|./
1.26      crook    8766: require timer.fs
                   8767: @end example
1.5       anton    8768: 
1.75      anton    8769: 
1.26      crook    8770: @c ---------------------------------------------------------
1.75      anton    8771: @node General Search Paths,  , Source Search Paths, Search Paths
1.26      crook    8772: @subsubsection General Search Paths
1.75      anton    8773: @cindex search path control, source files
1.5       anton    8774: 
1.26      crook    8775: Your application may need to search files in several directories, like
                   8776: @code{included} does. To facilitate this, Gforth allows you to define
                   8777: and use your own search paths, by providing generic equivalents of the
                   8778: Forth search path words:
1.5       anton    8779: 
1.75      anton    8780: doc-open-path-file
                   8781: doc-path-allot
                   8782: doc-clear-path
                   8783: doc-also-path
1.26      crook    8784: doc-.path
                   8785: doc-path+
                   8786: doc-path=
1.5       anton    8787: 
1.75      anton    8788: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44      crook    8789: 
1.75      anton    8790: Here's an example of creating an empty search path:
                   8791: @c
1.26      crook    8792: @example
1.75      anton    8793: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26      crook    8794: @end example
1.5       anton    8795: 
1.26      crook    8796: @c -------------------------------------------------------------
                   8797: @node Blocks, Other I/O, Files, Words
                   8798: @section Blocks
1.28      crook    8799: @cindex I/O - blocks
                   8800: @cindex blocks
                   8801: 
                   8802: When you run Gforth on a modern desk-top computer, it runs under the
                   8803: control of an operating system which provides certain services.  One of
                   8804: these services is @var{file services}, which allows Forth source code
                   8805: and data to be stored in files and read into Gforth (@pxref{Files}).
                   8806: 
                   8807: Traditionally, Forth has been an important programming language on
                   8808: systems where it has interfaced directly to the underlying hardware with
                   8809: no intervening operating system. Forth provides a mechanism, called
1.29      crook    8810: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    8811: 
                   8812: A block is a 1024-byte data area, which can be used to hold data or
                   8813: Forth source code. No structure is imposed on the contents of the
                   8814: block. A block is identified by its number; blocks are numbered
                   8815: contiguously from 1 to an implementation-defined maximum.
                   8816: 
                   8817: A typical system that used blocks but no operating system might use a
                   8818: single floppy-disk drive for mass storage, with the disks formatted to
                   8819: provide 256-byte sectors. Blocks would be implemented by assigning the
                   8820: first four sectors of the disk to block 1, the second four sectors to
                   8821: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   8822: would not contain any file system information, just the set of blocks.
                   8823: 
1.29      crook    8824: @cindex blocks file
1.28      crook    8825: On systems that do provide file services, blocks are typically
1.29      crook    8826: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    8827: file}.  The size of the blocks file will be an exact multiple of 1024
                   8828: bytes, corresponding to the number of blocks it contains. This is the
                   8829: mechanism that Gforth uses.
                   8830: 
1.29      crook    8831: @cindex @file{blocks.fb}
1.75      anton    8832: Only one blocks file can be open at a time. If you use block words without
1.28      crook    8833: having specified a blocks file, Gforth defaults to the blocks file
                   8834: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75      anton    8835: locate a blocks file (@pxref{Source Search Paths}).
1.28      crook    8836: 
1.29      crook    8837: @cindex block buffers
1.28      crook    8838: When you read and write blocks under program control, Gforth uses a
1.29      crook    8839: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    8840: not used when you use @code{load} to interpret the contents of a block.
                   8841: 
1.75      anton    8842: The behaviour of the block buffers is analagous to that of a cache.
                   8843: Each block buffer has three states:
1.28      crook    8844: 
                   8845: @itemize @bullet
                   8846: @item
                   8847: Unassigned
                   8848: @item
                   8849: Assigned-clean
                   8850: @item
                   8851: Assigned-dirty
                   8852: @end itemize
                   8853: 
1.29      crook    8854: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    8855: block, the block (specified by its block number) must be assigned to a
                   8856: block buffer.
                   8857: 
                   8858: The assignment of a block to a block buffer is performed by @code{block}
                   8859: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   8860: contents of a block. Use @code{buffer} when you don't care about the
                   8861: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    8862: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    8863: with the particular block is already stored in a block buffer due to an
                   8864: earlier @code{block} command, @code{buffer} will return that block
                   8865: buffer and the existing contents of the block will be
                   8866: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    8867: block buffer for the block.}.
1.28      crook    8868: 
1.47      crook    8869: Once a block has been assigned to a block buffer using @code{block} or
1.75      anton    8870: @code{buffer}, that block buffer becomes the @i{current block
                   8871: buffer}. Data may only be manipulated (read or written) within the
                   8872: current block buffer.
1.47      crook    8873: 
                   8874: When the contents of the current block buffer has been modified it is
1.48      anton    8875: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75      anton    8876: either abandon the changes (by doing nothing) or mark the block as
                   8877: changed (assigned-dirty), using @code{update}. Using @code{update} does
                   8878: not change the blocks file; it simply changes a block buffer's state to
                   8879: @i{assigned-dirty}.  The block will be written implicitly when it's
                   8880: buffer is needed for another block, or explicitly by @code{flush} or
                   8881: @code{save-buffers}.
                   8882: 
                   8883: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
                   8884: blocks file on disk. Leaving Gforth with @code{bye} also performs a
                   8885: @code{flush}.
1.28      crook    8886: 
1.29      crook    8887: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    8888: algorithm to assign a block buffer to a block. That means that any
                   8889: particular block can only be assigned to one specific block buffer,
1.29      crook    8890: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    8891: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   8892: the new block immediately. If it is @i{assigned-dirty} its current
                   8893: contents are written back to the blocks file on disk before it is
1.28      crook    8894: allocated to the new block.
                   8895: 
                   8896: Although no structure is imposed on the contents of a block, it is
                   8897: traditional to display the contents as 16 lines each of 64 characters.  A
                   8898: block provides a single, continuous stream of input (for example, it
                   8899: acts as a single parse area) -- there are no end-of-line characters
                   8900: within a block, and no end-of-file character at the end of a
                   8901: block. There are two consequences of this:
1.26      crook    8902: 
1.28      crook    8903: @itemize @bullet
                   8904: @item
                   8905: The last character of one line wraps straight into the first character
                   8906: of the following line
                   8907: @item
                   8908: The word @code{\} -- comment to end of line -- requires special
                   8909: treatment; in the context of a block it causes all characters until the
                   8910: end of the current 64-character ``line'' to be ignored.
                   8911: @end itemize
                   8912: 
                   8913: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    8914: the current blocks file will be extended to the appropriate size and the
1.28      crook    8915: block buffer will be initialised with spaces.
                   8916: 
1.47      crook    8917: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   8918: for details) but doesn't encourage the use of blocks; the mechanism is
                   8919: only provided for backward compatibility -- ANS Forth requires blocks to
                   8920: be available when files are.
1.28      crook    8921: 
                   8922: Common techniques that are used when working with blocks include:
                   8923: 
                   8924: @itemize @bullet
                   8925: @item
                   8926: A screen editor that allows you to edit blocks without leaving the Forth
                   8927: environment.
                   8928: @item
                   8929: Shadow screens; where every code block has an associated block
                   8930: containing comments (for example: code in odd block numbers, comments in
                   8931: even block numbers). Typically, the block editor provides a convenient
                   8932: mechanism to toggle between code and comments.
                   8933: @item
                   8934: Load blocks; a single block (typically block 1) contains a number of
                   8935: @code{thru} commands which @code{load} the whole of the application.
                   8936: @end itemize
1.26      crook    8937: 
1.29      crook    8938: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   8939: integrated into a Forth programming environment.
1.26      crook    8940: 
                   8941: @comment TODO what about errors on open-blocks?
1.44      crook    8942: 
1.26      crook    8943: doc-open-blocks
                   8944: doc-use
1.75      anton    8945: doc-block-offset
1.26      crook    8946: doc-get-block-fid
                   8947: doc-block-position
1.28      crook    8948: 
1.75      anton    8949: doc-list
1.28      crook    8950: doc-scr
                   8951: 
1.184     anton    8952: doc-block
1.28      crook    8953: doc-buffer
                   8954: 
1.75      anton    8955: doc-empty-buffers
                   8956: doc-empty-buffer
1.26      crook    8957: doc-update
1.28      crook    8958: doc-updated?
1.26      crook    8959: doc-save-buffers
1.75      anton    8960: doc-save-buffer
1.26      crook    8961: doc-flush
1.28      crook    8962: 
1.26      crook    8963: doc-load
                   8964: doc-thru
                   8965: doc-+load
                   8966: doc-+thru
1.45      crook    8967: doc---gforthman--->
1.26      crook    8968: doc-block-included
                   8969: 
1.44      crook    8970: 
1.26      crook    8971: @c -------------------------------------------------------------
1.126     pazsan   8972: @node Other I/O, OS command line arguments, Blocks, Words
1.26      crook    8973: @section Other I/O
1.28      crook    8974: @cindex I/O - keyboard and display
1.26      crook    8975: 
                   8976: @menu
                   8977: * Simple numeric output::       Predefined formats
                   8978: * Formatted numeric output::    Formatted (pictured) output
                   8979: * String Formats::              How Forth stores strings in memory
1.67      anton    8980: * Displaying characters and strings::  Other stuff
1.231     pazsan   8981: * String words::                Gforth's little string library
1.175     anton    8982: * Terminal output::             Cursor positioning etc.
1.181     anton    8983: * Single-key input::            
                   8984: * Line input and conversion::   
1.112     anton    8985: * Pipes::                       How to create your own pipes
1.149     pazsan   8986: * Xchars and Unicode::          Non-ASCII characters
1.26      crook    8987: @end menu
                   8988: 
                   8989: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8990: @subsection Simple numeric output
1.28      crook    8991: @cindex numeric output - simple/free-format
1.5       anton    8992: 
1.26      crook    8993: The simplest output functions are those that display numbers from the
                   8994: data or floating-point stacks. Floating-point output is always displayed
                   8995: using base 10. Numbers displayed from the data stack use the value stored
                   8996: in @code{base}.
1.5       anton    8997: 
1.44      crook    8998: 
1.26      crook    8999: doc-.
                   9000: doc-dec.
                   9001: doc-hex.
                   9002: doc-u.
                   9003: doc-.r
                   9004: doc-u.r
                   9005: doc-d.
                   9006: doc-ud.
                   9007: doc-d.r
                   9008: doc-ud.r
                   9009: doc-f.
                   9010: doc-fe.
                   9011: doc-fs.
1.111     anton    9012: doc-f.rdp
1.44      crook    9013: 
1.26      crook    9014: Examples of printing the number 1234.5678E23 in the different floating-point output
                   9015: formats are shown below:
1.5       anton    9016: 
                   9017: @example
1.26      crook    9018: f. 123456779999999000000000000.
                   9019: fe. 123.456779999999E24
                   9020: fs. 1.23456779999999E26
1.5       anton    9021: @end example
                   9022: 
                   9023: 
1.26      crook    9024: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   9025: @subsection Formatted numeric output
1.28      crook    9026: @cindex formatted numeric output
1.26      crook    9027: @cindex pictured numeric output
1.28      crook    9028: @cindex numeric output - formatted
1.26      crook    9029: 
1.29      crook    9030: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    9031: output} for formatted printing of integers.  In this technique, digits
                   9032: are extracted from the number (using the current output radix defined by
                   9033: @code{base}), converted to ASCII codes and appended to a string that is
                   9034: built in a scratch-pad area of memory (@pxref{core-idef,
                   9035: Implementation-defined options, Implementation-defined
                   9036: options}). Arbitrary characters can be appended to the string during the
                   9037: extraction process. The completed string is specified by an address
                   9038: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   9039: under program control.
1.5       anton    9040: 
1.75      anton    9041: All of the integer output words described in the previous section
                   9042: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
                   9043: numeric output.
1.5       anton    9044: 
1.47      crook    9045: Three important things to remember about pictured numeric output:
1.5       anton    9046: 
1.26      crook    9047: @itemize @bullet
                   9048: @item
1.28      crook    9049: It always operates on double-precision numbers; to display a
1.49      anton    9050: single-precision number, convert it first (for ways of doing this
                   9051: @pxref{Double precision}).
1.26      crook    9052: @item
1.28      crook    9053: It always treats the double-precision number as though it were
                   9054: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    9055: @item
                   9056: The string is built up from right to left; least significant digit first.
                   9057: @end itemize
1.5       anton    9058: 
1.44      crook    9059: 
1.26      crook    9060: doc-<#
1.47      crook    9061: doc-<<#
1.26      crook    9062: doc-#
                   9063: doc-#s
                   9064: doc-hold
                   9065: doc-sign
                   9066: doc-#>
1.47      crook    9067: doc-#>>
1.5       anton    9068: 
1.26      crook    9069: doc-represent
1.111     anton    9070: doc-f>str-rdp
                   9071: doc-f>buf-rdp
1.5       anton    9072: 
1.44      crook    9073: 
                   9074: @noindent
1.26      crook    9075: Here are some examples of using pictured numeric output:
1.5       anton    9076: 
                   9077: @example
1.26      crook    9078: : my-u. ( u -- )
                   9079:   \ Simplest use of pns.. behaves like Standard u. 
                   9080:   0              \ convert to unsigned double
1.75      anton    9081:   <<#            \ start conversion
1.26      crook    9082:   #s             \ convert all digits
                   9083:   #>             \ complete conversion
1.75      anton    9084:   TYPE SPACE     \ display, with trailing space
                   9085:   #>> ;          \ release hold area
1.5       anton    9086: 
1.26      crook    9087: : cents-only ( u -- )
                   9088:   0              \ convert to unsigned double
1.75      anton    9089:   <<#            \ start conversion
1.26      crook    9090:   # #            \ convert two least-significant digits
                   9091:   #>             \ complete conversion, discard other digits
1.75      anton    9092:   TYPE SPACE     \ display, with trailing space
                   9093:   #>> ;          \ release hold area
1.5       anton    9094: 
1.26      crook    9095: : dollars-and-cents ( u -- )
                   9096:   0              \ convert to unsigned double
1.75      anton    9097:   <<#            \ start conversion
1.26      crook    9098:   # #            \ convert two least-significant digits
                   9099:   [char] . hold  \ insert decimal point
                   9100:   #s             \ convert remaining digits
                   9101:   [char] $ hold  \ append currency symbol
                   9102:   #>             \ complete conversion
1.75      anton    9103:   TYPE SPACE     \ display, with trailing space
                   9104:   #>> ;          \ release hold area
1.5       anton    9105: 
1.26      crook    9106: : my-. ( n -- )
                   9107:   \ handling negatives.. behaves like Standard .
                   9108:   s>d            \ convert to signed double
                   9109:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    9110:   <<#            \ start conversion
1.26      crook    9111:   #s             \ convert all digits
                   9112:   rot sign       \ get at sign byte, append "-" if needed
                   9113:   #>             \ complete conversion
1.75      anton    9114:   TYPE SPACE     \ display, with trailing space
                   9115:   #>> ;          \ release hold area
1.5       anton    9116: 
1.26      crook    9117: : account. ( n -- )
1.75      anton    9118:   \ accountants don't like minus signs, they use parentheses
1.26      crook    9119:   \ for negative numbers
                   9120:   s>d            \ convert to signed double
                   9121:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    9122:   <<#            \ start conversion
1.26      crook    9123:   2 pick         \ get copy of sign byte
                   9124:   0< IF [char] ) hold THEN \ right-most character of output
                   9125:   #s             \ convert all digits
                   9126:   rot            \ get at sign byte
                   9127:   0< IF [char] ( hold THEN
                   9128:   #>             \ complete conversion
1.75      anton    9129:   TYPE SPACE     \ display, with trailing space
                   9130:   #>> ;          \ release hold area
                   9131: 
1.5       anton    9132: @end example
                   9133: 
1.26      crook    9134: Here are some examples of using these words:
1.5       anton    9135: 
                   9136: @example
1.26      crook    9137: 1 my-u. 1
                   9138: hex -1 my-u. decimal FFFFFFFF
                   9139: 1 cents-only 01
                   9140: 1234 cents-only 34
                   9141: 2 dollars-and-cents $0.02
                   9142: 1234 dollars-and-cents $12.34
                   9143: 123 my-. 123
                   9144: -123 my. -123
                   9145: 123 account. 123
                   9146: -456 account. (456)
1.5       anton    9147: @end example
                   9148: 
                   9149: 
1.26      crook    9150: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   9151: @subsection String Formats
1.27      crook    9152: @cindex strings - see character strings
                   9153: @cindex character strings - formats
1.28      crook    9154: @cindex I/O - see character strings
1.75      anton    9155: @cindex counted strings
                   9156: 
                   9157: @c anton: this does not really belong here; maybe the memory section,
                   9158: @c  or the principles chapter
1.26      crook    9159: 
1.27      crook    9160: Forth commonly uses two different methods for representing character
                   9161: strings:
1.26      crook    9162: 
                   9163: @itemize @bullet
                   9164: @item
                   9165: @cindex address of counted string
1.45      crook    9166: @cindex counted string
1.29      crook    9167: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   9168: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   9169: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    9170: memory.
                   9171: @item
1.29      crook    9172: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   9173: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    9174: first byte of the string.
                   9175: @end itemize
                   9176: 
                   9177: ANS Forth encourages the use of the second format when representing
1.75      anton    9178: strings.
1.26      crook    9179: 
1.44      crook    9180: 
1.26      crook    9181: doc-count
                   9182: 
1.44      crook    9183: 
1.49      anton    9184: For words that move, copy and search for strings see @ref{Memory
                   9185: Blocks}. For words that display characters and strings see
                   9186: @ref{Displaying characters and strings}.
1.26      crook    9187: 
1.231     pazsan   9188: @node Displaying characters and strings, String words, String Formats, Other I/O
1.26      crook    9189: @subsection Displaying characters and strings
1.27      crook    9190: @cindex characters - compiling and displaying
                   9191: @cindex character strings - compiling and displaying
1.26      crook    9192: 
                   9193: This section starts with a glossary of Forth words and ends with a set
                   9194: of examples.
                   9195: 
                   9196: doc-bl
                   9197: doc-space
                   9198: doc-spaces
                   9199: doc-emit
                   9200: doc-toupper
                   9201: doc-."
                   9202: doc-.(
1.98      anton    9203: doc-.\"
1.26      crook    9204: doc-type
1.44      crook    9205: doc-typewhite
1.26      crook    9206: doc-cr
1.27      crook    9207: @cindex cursor control
1.26      crook    9208: doc-s"
1.98      anton    9209: doc-s\"
1.26      crook    9210: doc-c"
                   9211: doc-char
                   9212: doc-[char]
                   9213: 
1.44      crook    9214: 
                   9215: @noindent
1.26      crook    9216: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    9217: 
                   9218: @example
1.26      crook    9219: .( text-1)
                   9220: : my-word
                   9221:   ." text-2" cr
                   9222:   .( text-3)
                   9223: ;
                   9224: 
                   9225: ." text-4"
                   9226: 
                   9227: : my-char
                   9228:   [char] ALPHABET emit
                   9229:   char emit
                   9230: ;
1.5       anton    9231: @end example
                   9232: 
1.26      crook    9233: When you load this code into Gforth, the following output is generated:
1.5       anton    9234: 
1.26      crook    9235: @example
1.30      anton    9236: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    9237: @end example
1.5       anton    9238: 
1.26      crook    9239: @itemize @bullet
                   9240: @item
                   9241: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   9242: is an immediate word; it behaves in the same way whether it is used inside
                   9243: or outside a colon definition.
                   9244: @item
                   9245: Message @code{text-4} is displayed because of Gforth's added interpretation
                   9246: semantics for @code{."}.
                   9247: @item
1.29      crook    9248: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    9249: performs the compilation semantics for @code{."} within the definition of
                   9250: @code{my-word}.
                   9251: @end itemize
1.5       anton    9252: 
1.26      crook    9253: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    9254: 
1.26      crook    9255: @example
1.30      anton    9256: @kbd{my-word @key{RET}} text-2
1.26      crook    9257:  ok
1.30      anton    9258: @kbd{my-char fred @key{RET}} Af ok
                   9259: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    9260: @end example
1.5       anton    9261: 
                   9262: @itemize @bullet
                   9263: @item
1.26      crook    9264: Message @code{text-2} is displayed because of the run-time behaviour of
                   9265: @code{."}.
                   9266: @item
                   9267: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   9268: on the stack at run-time. @code{emit} always displays the character
                   9269: when @code{my-char} is executed.
                   9270: @item
                   9271: @code{char} parses a string at run-time and the second @code{emit} displays
                   9272: the first character of the string.
1.5       anton    9273: @item
1.26      crook    9274: If you type @code{see my-char} you can see that @code{[char]} discarded
                   9275: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   9276: definition of @code{my-char}.
1.5       anton    9277: @end itemize
                   9278: 
1.231     pazsan   9279: @node String words, Terminal output, Displaying characters and strings, Other I/O
                   9280: @subsection String words
                   9281: @cindex string words
                   9282: 
                   9283: The following string library stores strings in ordinary variables,
                   9284: which then contain a pointer to a counted string stored allocated from
                   9285: the heap.  Instead of a count byte, there's a whole count cell,
                   9286: sufficient for all normal use.  The string library originates from
                   9287: bigFORTH.
                   9288: 
                   9289: doc-delete
                   9290: doc-insert
                   9291: doc-$!
                   9292: doc-$@
                   9293: doc-$@len
                   9294: doc-$!len
                   9295: doc-$del
                   9296: doc-$ins
                   9297: doc-$+!
                   9298: doc-$off
                   9299: doc-$init
                   9300: doc-$split
                   9301: doc-$iter
1.238     pazsan   9302: doc-$over
                   9303: doc-$[]
                   9304: doc-$[]!
                   9305: doc-$[]+!
                   9306: doc-$[]@
1.5       anton    9307: 
1.231     pazsan   9308: @node Terminal output, Single-key input, String words, Other I/O
1.175     anton    9309: @subsection Terminal output
                   9310: @cindex output to terminal
                   9311: @cindex terminal output
                   9312: 
                   9313: If you are outputting to a terminal, you may want to control the
                   9314: positioning of the cursor:
                   9315: @cindex cursor positioning
                   9316: 
                   9317: doc-at-xy
                   9318: 
                   9319: In order to know where to position the cursor, it is often helpful to
                   9320: know the size of the screen:
                   9321: @cindex terminal size 
                   9322: 
                   9323: doc-form
                   9324: 
                   9325: And sometimes you want to use:
                   9326: @cindex clear screen
                   9327: 
                   9328: doc-page
                   9329: 
                   9330: Note that on non-terminals you should use @code{12 emit}, not
                   9331: @code{page}, to get a form feed.
                   9332: 
1.5       anton    9333: 
1.181     anton    9334: @node Single-key input, Line input and conversion, Terminal output, Other I/O
                   9335: @subsection Single-key input
                   9336: @cindex single-key input
                   9337: @cindex input, single-key
                   9338: 
                   9339: If you want to get a single printable character, you can use
                   9340: @code{key}; to check whether a character is available for @code{key},
                   9341: you can use @code{key?}.
1.5       anton    9342: 
1.181     anton    9343: doc-key
                   9344: doc-key?
1.27      crook    9345: 
1.181     anton    9346: If you want to process a mix of printable and non-printable
                   9347: characters, you can do that with @code{ekey} and friends.  @code{Ekey}
                   9348: produces a keyboard event that you have to convert into a character
                   9349: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
                   9350: 
                   9351: Typical code for using EKEY looks like this:
                   9352: 
                   9353: @example
                   9354: ekey ekey>char if ( c )
                   9355:   ... \ do something with the character
                   9356: else ekey>fkey if ( key-id )
                   9357:   case
                   9358:     k-up                                  of ... endof
                   9359:     k-f1                                  of ... endof
                   9360:     k-left k-shift-mask or k-ctrl-mask or of ... endof
                   9361:     ...
                   9362:   endcase
                   9363: else ( keyboard-event )
                   9364:   drop \ just ignore an unknown keyboard event type
                   9365: then then
                   9366: @end example
1.44      crook    9367: 
1.45      crook    9368: doc-ekey
1.141     anton    9369: doc-ekey>char
1.181     anton    9370: doc-ekey>fkey
1.45      crook    9371: doc-ekey?
1.141     anton    9372: 
1.181     anton    9373: The key identifiers for cursor keys are:
1.141     anton    9374: 
                   9375: doc-k-left
                   9376: doc-k-right
1.185     anton    9377: doc-k-up
                   9378: doc-k-down
                   9379: doc-k-home
                   9380: doc-k-end
1.141     anton    9381: doc-k-prior
                   9382: doc-k-next
                   9383: doc-k-insert
                   9384: doc-k-delete
                   9385: 
1.181     anton    9386: The key identifiers for function keys (aka keypad keys) are:
1.141     anton    9387: 
1.181     anton    9388: doc-k-f1
                   9389: doc-k-f2
                   9390: doc-k-f3
                   9391: doc-k-f4
                   9392: doc-k-f5
                   9393: doc-k-f6
                   9394: doc-k-f7
                   9395: doc-k-f8
                   9396: doc-k-f9
                   9397: doc-k-f10
                   9398: doc-k-f11
                   9399: doc-k-f12
                   9400: 
                   9401: Note that @code{k-f11} and @code{k-f12} are not as widely available.
                   9402: 
                   9403: You can combine these key identifiers with masks for various shift keys:
                   9404: 
                   9405: doc-k-shift-mask
                   9406: doc-k-ctrl-mask
                   9407: doc-k-alt-mask
                   9408: 
                   9409: Note that, even if a Forth system has @code{ekey>fkey} and the key
                   9410: identifier words, the keys are not necessarily available or it may not
                   9411: necessarily be able to report all the keys and all the possible
                   9412: combinations with shift masks.  Therefore, write your programs in such
                   9413: a way that they are still useful even if the keys and key combinations
                   9414: cannot be pressed or are not recognized.
                   9415: 
                   9416: Examples: Older keyboards often do not have an F11 and F12 key.  If
                   9417: you run Gforth in an xterm, the xterm catches a number of combinations
                   9418: (e.g., @key{Shift-Up}), and never passes it to Gforth.  Finally,
                   9419: Gforth currently does not recognize and report combinations with
                   9420: multiple shift keys (so the @key{shift-ctrl-left} case in the example
                   9421: above would never be entered).
                   9422: 
                   9423: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
                   9424: you need the ANSI.SYS driver to get that behaviour); it works by
                   9425: recognizing the escape sequences that ANSI terminals send when such a
                   9426: key is pressed.  If you have a terminal that sends other escape
                   9427: sequences, you will not get useful results on Gforth.  Other Forth
                   9428: systems may work in a different way.
                   9429: 
1.200     anton    9430: Gforth also provides a few words for outputting names of function
                   9431: keys:
                   9432: 
                   9433: doc-fkey.
                   9434: doc-simple-fkey-string
                   9435: 
1.181     anton    9436: 
                   9437: @node  Line input and conversion, Pipes, Single-key input, Other I/O
                   9438: @subsection Line input and conversion
                   9439: @cindex line input from terminal
                   9440: @cindex input, linewise from terminal
                   9441: @cindex convertin strings to numbers
                   9442: @cindex I/O - see input
                   9443: 
                   9444: For ways of storing character strings in memory see @ref{String Formats}.
                   9445: 
                   9446: @comment TODO examples for >number >float accept key key? pad parse word refill
                   9447: @comment then index them
1.141     anton    9448: 
                   9449: Words for inputting one line from the keyboard:
                   9450: 
                   9451: doc-accept
                   9452: doc-edit-line
                   9453: 
                   9454: Conversion words:
                   9455: 
1.143     anton    9456: doc-s>number?
                   9457: doc-s>unumber?
1.26      crook    9458: doc->number
                   9459: doc->float
1.237     pazsan   9460: doc->float1
1.141     anton    9461: 
1.27      crook    9462: @comment obsolescent words..
1.141     anton    9463: Obsolescent input and conversion words:
                   9464: 
1.27      crook    9465: doc-convert
1.26      crook    9466: doc-expect
1.27      crook    9467: doc-span
1.5       anton    9468: 
                   9469: 
1.181     anton    9470: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112     anton    9471: @subsection Pipes
                   9472: @cindex pipes, creating your own
                   9473: 
                   9474: In addition to using Gforth in pipes created by other processes
                   9475: (@pxref{Gforth in pipes}), you can create your own pipe with
                   9476: @code{open-pipe}, and read from or write to it.
                   9477: 
                   9478: doc-open-pipe
                   9479: doc-close-pipe
                   9480: 
                   9481: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
                   9482: you don't catch this exception, Gforth will catch it and exit, usually
                   9483: silently (@pxref{Gforth in pipes}).  Since you probably do not want
                   9484: this, you should wrap a @code{catch} or @code{try} block around the code
                   9485: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
                   9486: problem yourself, and then return to regular processing.
                   9487: 
                   9488: doc-broken-pipe-error
                   9489: 
1.155     anton    9490: @node Xchars and Unicode,  , Pipes, Other I/O
                   9491: @subsection Xchars and Unicode
1.149     pazsan   9492: 
1.188     pazsan   9493: ASCII is only appropriate for the English language. Most western
                   9494: languages however fit somewhat into the Forth frame, since a byte is
                   9495: sufficient to encode the few special characters in each (though not
                   9496: always the same encoding can be used; latin-1 is most widely used,
                   9497: though). For other languages, different char-sets have to be used,
                   9498: several of them variable-width. Most prominent representant is
                   9499: UTF-8. Let's call these extended characters xchars. The primitive
                   9500: fixed-size characters stored as bytes are called pchars in this
                   9501: section.
                   9502: 
                   9503: The xchar words add a few data types:
                   9504: 
                   9505: @itemize
                   9506: 
                   9507: @item
                   9508: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
                   9509: and is a subset of unsigned cell. Note: UTF-8 can not store more that
                   9510: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
                   9511: character set can be used.
                   9512: 
                   9513: @item
                   9514: @var{xc-addr} is the address of an xchar in memory. Alignment
                   9515: requirements are the same as @var{c-addr}. The memory representation of an
                   9516: xchar differs from the stack representation, and depends on the
                   9517: encoding used. An xchar may use a variable number of pchars in memory.
                   9518: 
                   9519: @item
                   9520: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
                   9521: @var{xc-addr}, @var{u} pchars long.
                   9522: 
                   9523: @end itemize
                   9524: 
                   9525: doc-xc-size
                   9526: doc-x-size
                   9527: doc-xc@+
                   9528: doc-xc!+?
                   9529: doc-xchar+
                   9530: doc-xchar-
                   9531: doc-+x/string
                   9532: doc-x\string-
                   9533: doc--trailing-garbage
                   9534: doc-x-width
                   9535: doc-xkey
                   9536: doc-xemit
                   9537: 
                   9538: There's a new environment query
                   9539: 
                   9540: doc-xchar-encoding
1.112     anton    9541: 
1.121     anton    9542: @node OS command line arguments, Locals, Other I/O, Words
                   9543: @section OS command line arguments
                   9544: @cindex OS command line arguments
                   9545: @cindex command line arguments, OS
                   9546: @cindex arguments, OS command line
                   9547: 
                   9548: The usual way to pass arguments to Gforth programs on the command line
                   9549: is via the @option{-e} option, e.g.
                   9550: 
                   9551: @example
                   9552: gforth -e "123 456" foo.fs -e bye
                   9553: @end example
                   9554: 
                   9555: However, you may want to interpret the command-line arguments directly.
                   9556: In that case, you can access the (image-specific) command-line arguments
1.123     anton    9557: through @code{next-arg}:
1.121     anton    9558: 
1.123     anton    9559: doc-next-arg
1.121     anton    9560: 
1.123     anton    9561: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121     anton    9562: 
                   9563: @example
                   9564: : echo ( -- )
1.122     anton    9565:     begin
1.123     anton    9566:        next-arg 2dup 0 0 d<> while
                   9567:            type space
                   9568:     repeat
                   9569:     2drop ;
1.121     anton    9570: 
                   9571: echo cr bye
                   9572: @end example
                   9573: 
                   9574: This can be invoked with
                   9575: 
                   9576: @example
                   9577: gforth echo.fs hello world
                   9578: @end example
1.123     anton    9579: 
                   9580: and it will print
                   9581: 
                   9582: @example
                   9583: hello world
                   9584: @end example
                   9585: 
                   9586: The next lower level of dealing with the OS command line are the
                   9587: following words:
                   9588: 
                   9589: doc-arg
                   9590: doc-shift-args
                   9591: 
                   9592: Finally, at the lowest level Gforth provides the following words:
                   9593: 
                   9594: doc-argc
                   9595: doc-argv
1.121     anton    9596: 
1.78      anton    9597: @c -------------------------------------------------------------
1.126     pazsan   9598: @node Locals, Structures, OS command line arguments, Words
1.78      anton    9599: @section Locals
                   9600: @cindex locals
                   9601: 
                   9602: Local variables can make Forth programming more enjoyable and Forth
                   9603: programs easier to read. Unfortunately, the locals of ANS Forth are
                   9604: laden with restrictions. Therefore, we provide not only the ANS Forth
                   9605: locals wordset, but also our own, more powerful locals wordset (we
                   9606: implemented the ANS Forth locals wordset through our locals wordset).
1.44      crook    9607: 
1.78      anton    9608: The ideas in this section have also been published in M. Anton Ertl,
                   9609: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
                   9610: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12      anton    9611: 
                   9612: @menu
1.78      anton    9613: * Gforth locals::               
                   9614: * ANS Forth locals::            
1.5       anton    9615: @end menu
                   9616: 
1.78      anton    9617: @node Gforth locals, ANS Forth locals, Locals, Locals
                   9618: @subsection Gforth locals
                   9619: @cindex Gforth locals
                   9620: @cindex locals, Gforth style
1.5       anton    9621: 
1.78      anton    9622: Locals can be defined with
1.44      crook    9623: 
1.78      anton    9624: @example
                   9625: @{ local1 local2 ... -- comment @}
                   9626: @end example
                   9627: or
                   9628: @example
                   9629: @{ local1 local2 ... @}
                   9630: @end example
1.5       anton    9631: 
1.78      anton    9632: E.g.,
                   9633: @example
                   9634: : max @{ n1 n2 -- n3 @}
                   9635:  n1 n2 > if
                   9636:    n1
                   9637:  else
                   9638:    n2
                   9639:  endif ;
                   9640: @end example
1.44      crook    9641: 
1.78      anton    9642: The similarity of locals definitions with stack comments is intended. A
                   9643: locals definition often replaces the stack comment of a word. The order
                   9644: of the locals corresponds to the order in a stack comment and everything
                   9645: after the @code{--} is really a comment.
1.77      anton    9646: 
1.78      anton    9647: This similarity has one disadvantage: It is too easy to confuse locals
                   9648: declarations with stack comments, causing bugs and making them hard to
                   9649: find. However, this problem can be avoided by appropriate coding
                   9650: conventions: Do not use both notations in the same program. If you do,
                   9651: they should be distinguished using additional means, e.g. by position.
1.77      anton    9652: 
1.78      anton    9653: @cindex types of locals
                   9654: @cindex locals types
                   9655: The name of the local may be preceded by a type specifier, e.g.,
                   9656: @code{F:} for a floating point value:
1.5       anton    9657: 
1.78      anton    9658: @example
                   9659: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   9660: \ complex multiplication
                   9661:  Ar Br f* Ai Bi f* f-
                   9662:  Ar Bi f* Ai Br f* f+ ;
                   9663: @end example
1.44      crook    9664: 
1.78      anton    9665: @cindex flavours of locals
                   9666: @cindex locals flavours
                   9667: @cindex value-flavoured locals
                   9668: @cindex variable-flavoured locals
                   9669: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   9670: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   9671: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   9672: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   9673: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   9674: produces its address (which becomes invalid when the variable's scope is
                   9675: left). E.g., the standard word @code{emit} can be defined in terms of
                   9676: @code{type} like this:
1.5       anton    9677: 
1.78      anton    9678: @example
                   9679: : emit @{ C^ char* -- @}
                   9680:     char* 1 type ;
                   9681: @end example
1.5       anton    9682: 
1.78      anton    9683: @cindex default type of locals
                   9684: @cindex locals, default type
                   9685: A local without type specifier is a @code{W:} local. Both flavours of
                   9686: locals are initialized with values from the data or FP stack.
1.44      crook    9687: 
1.78      anton    9688: Currently there is no way to define locals with user-defined data
                   9689: structures, but we are working on it.
1.5       anton    9690: 
1.78      anton    9691: Gforth allows defining locals everywhere in a colon definition. This
                   9692: poses the following questions:
1.5       anton    9693: 
1.78      anton    9694: @menu
                   9695: * Where are locals visible by name?::  
                   9696: * How long do locals live?::    
                   9697: * Locals programming style::    
                   9698: * Locals implementation::       
                   9699: @end menu
1.44      crook    9700: 
1.78      anton    9701: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   9702: @subsubsection Where are locals visible by name?
                   9703: @cindex locals visibility
                   9704: @cindex visibility of locals
                   9705: @cindex scope of locals
1.5       anton    9706: 
1.78      anton    9707: Basically, the answer is that locals are visible where you would expect
                   9708: it in block-structured languages, and sometimes a little longer. If you
                   9709: want to restrict the scope of a local, enclose its definition in
                   9710: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    9711: 
                   9712: 
1.78      anton    9713: doc-scope
                   9714: doc-endscope
1.5       anton    9715: 
                   9716: 
1.78      anton    9717: These words behave like control structure words, so you can use them
                   9718: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   9719: arbitrary ways.
1.77      anton    9720: 
1.78      anton    9721: If you want a more exact answer to the visibility question, here's the
                   9722: basic principle: A local is visible in all places that can only be
                   9723: reached through the definition of the local@footnote{In compiler
                   9724: construction terminology, all places dominated by the definition of the
                   9725: local.}. In other words, it is not visible in places that can be reached
                   9726: without going through the definition of the local. E.g., locals defined
                   9727: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   9728: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   9729: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77      anton    9730: 
1.78      anton    9731: The reasoning behind this solution is: We want to have the locals
                   9732: visible as long as it is meaningful. The user can always make the
                   9733: visibility shorter by using explicit scoping. In a place that can
                   9734: only be reached through the definition of a local, the meaning of a
                   9735: local name is clear. In other places it is not: How is the local
                   9736: initialized at the control flow path that does not contain the
                   9737: definition? Which local is meant, if the same name is defined twice in
                   9738: two independent control flow paths?
1.77      anton    9739: 
1.78      anton    9740: This should be enough detail for nearly all users, so you can skip the
                   9741: rest of this section. If you really must know all the gory details and
                   9742: options, read on.
1.77      anton    9743: 
1.78      anton    9744: In order to implement this rule, the compiler has to know which places
                   9745: are unreachable. It knows this automatically after @code{AHEAD},
                   9746: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   9747: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   9748: compiler that the control flow never reaches that place. If
                   9749: @code{UNREACHABLE} is not used where it could, the only consequence is
                   9750: that the visibility of some locals is more limited than the rule above
                   9751: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   9752: lie to the compiler), buggy code will be produced.
1.77      anton    9753: 
1.5       anton    9754: 
1.78      anton    9755: doc-unreachable
1.5       anton    9756: 
1.23      crook    9757: 
1.78      anton    9758: Another problem with this rule is that at @code{BEGIN}, the compiler
                   9759: does not know which locals will be visible on the incoming
                   9760: back-edge. All problems discussed in the following are due to this
                   9761: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   9762: loops as examples; the discussion also applies to @code{?DO} and other
                   9763: loops). Perhaps the most insidious example is:
1.26      crook    9764: @example
1.78      anton    9765: AHEAD
                   9766: BEGIN
                   9767:   x
                   9768: [ 1 CS-ROLL ] THEN
                   9769:   @{ x @}
                   9770:   ...
                   9771: UNTIL
1.26      crook    9772: @end example
1.23      crook    9773: 
1.78      anton    9774: This should be legal according to the visibility rule. The use of
                   9775: @code{x} can only be reached through the definition; but that appears
                   9776: textually below the use.
                   9777: 
                   9778: From this example it is clear that the visibility rules cannot be fully
                   9779: implemented without major headaches. Our implementation treats common
                   9780: cases as advertised and the exceptions are treated in a safe way: The
                   9781: compiler makes a reasonable guess about the locals visible after a
                   9782: @code{BEGIN}; if it is too pessimistic, the
                   9783: user will get a spurious error about the local not being defined; if the
                   9784: compiler is too optimistic, it will notice this later and issue a
                   9785: warning. In the case above the compiler would complain about @code{x}
                   9786: being undefined at its use. You can see from the obscure examples in
                   9787: this section that it takes quite unusual control structures to get the
                   9788: compiler into trouble, and even then it will often do fine.
1.23      crook    9789: 
1.78      anton    9790: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   9791: is that all locals visible before the @code{BEGIN} will also be
                   9792: visible after the @code{BEGIN}. This guess is valid for all loops that
                   9793: are entered only through the @code{BEGIN}, in particular, for normal
                   9794: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   9795: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   9796: compiler. When the branch to the @code{BEGIN} is finally generated by
                   9797: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   9798: warns the user if it was too optimistic:
1.26      crook    9799: @example
1.78      anton    9800: IF
                   9801:   @{ x @}
                   9802: BEGIN
                   9803:   \ x ? 
                   9804: [ 1 cs-roll ] THEN
                   9805:   ...
                   9806: UNTIL
1.26      crook    9807: @end example
1.23      crook    9808: 
1.78      anton    9809: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   9810: optimistically assumes that it lives until the @code{THEN}. It notices
                   9811: this difference when it compiles the @code{UNTIL} and issues a
                   9812: warning. The user can avoid the warning, and make sure that @code{x}
                   9813: is not used in the wrong area by using explicit scoping:
                   9814: @example
                   9815: IF
                   9816:   SCOPE
                   9817:   @{ x @}
                   9818:   ENDSCOPE
                   9819: BEGIN
                   9820: [ 1 cs-roll ] THEN
                   9821:   ...
                   9822: UNTIL
                   9823: @end example
1.23      crook    9824: 
1.78      anton    9825: Since the guess is optimistic, there will be no spurious error messages
                   9826: about undefined locals.
1.44      crook    9827: 
1.78      anton    9828: If the @code{BEGIN} is not reachable from above (e.g., after
                   9829: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   9830: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   9831: defined later. Therefore, the compiler assumes that no locals are
                   9832: visible after the @code{BEGIN}. However, the user can use
                   9833: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   9834: visible at the BEGIN as at the point where the top control-flow stack
                   9835: item was created.
1.23      crook    9836: 
1.44      crook    9837: 
1.78      anton    9838: doc-assume-live
1.26      crook    9839: 
1.23      crook    9840: 
1.78      anton    9841: @noindent
                   9842: E.g.,
                   9843: @example
                   9844: @{ x @}
                   9845: AHEAD
                   9846: ASSUME-LIVE
                   9847: BEGIN
                   9848:   x
                   9849: [ 1 CS-ROLL ] THEN
                   9850:   ...
                   9851: UNTIL
                   9852: @end example
1.44      crook    9853: 
1.78      anton    9854: Other cases where the locals are defined before the @code{BEGIN} can be
                   9855: handled by inserting an appropriate @code{CS-ROLL} before the
                   9856: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   9857: behind the @code{ASSUME-LIVE}).
1.23      crook    9858: 
1.78      anton    9859: Cases where locals are defined after the @code{BEGIN} (but should be
                   9860: visible immediately after the @code{BEGIN}) can only be handled by
                   9861: rearranging the loop. E.g., the ``most insidious'' example above can be
                   9862: arranged into:
                   9863: @example
                   9864: BEGIN
                   9865:   @{ x @}
                   9866:   ... 0=
                   9867: WHILE
                   9868:   x
                   9869: REPEAT
                   9870: @end example
1.44      crook    9871: 
1.78      anton    9872: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
                   9873: @subsubsection How long do locals live?
                   9874: @cindex locals lifetime
                   9875: @cindex lifetime of locals
1.23      crook    9876: 
1.78      anton    9877: The right answer for the lifetime question would be: A local lives at
                   9878: least as long as it can be accessed. For a value-flavoured local this
                   9879: means: until the end of its visibility. However, a variable-flavoured
                   9880: local could be accessed through its address far beyond its visibility
                   9881: scope. Ultimately, this would mean that such locals would have to be
                   9882: garbage collected. Since this entails un-Forth-like implementation
                   9883: complexities, I adopted the same cowardly solution as some other
                   9884: languages (e.g., C): The local lives only as long as it is visible;
                   9885: afterwards its address is invalid (and programs that access it
                   9886: afterwards are erroneous).
1.23      crook    9887: 
1.78      anton    9888: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
                   9889: @subsubsection Locals programming style
                   9890: @cindex locals programming style
                   9891: @cindex programming style, locals
1.23      crook    9892: 
1.78      anton    9893: The freedom to define locals anywhere has the potential to change
                   9894: programming styles dramatically. In particular, the need to use the
                   9895: return stack for intermediate storage vanishes. Moreover, all stack
                   9896: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9897: determined arguments) can be eliminated: If the stack items are in the
                   9898: wrong order, just write a locals definition for all of them; then
                   9899: write the items in the order you want.
1.23      crook    9900: 
1.78      anton    9901: This seems a little far-fetched and eliminating stack manipulations is
                   9902: unlikely to become a conscious programming objective. Still, the number
                   9903: of stack manipulations will be reduced dramatically if local variables
                   9904: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
                   9905: a traditional implementation of @code{max}).
1.23      crook    9906: 
1.78      anton    9907: This shows one potential benefit of locals: making Forth programs more
                   9908: readable. Of course, this benefit will only be realized if the
                   9909: programmers continue to honour the principle of factoring instead of
                   9910: using the added latitude to make the words longer.
1.23      crook    9911: 
1.78      anton    9912: @cindex single-assignment style for locals
                   9913: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9914: every value-flavoured local has only a single assignment and many
                   9915: advantages of functional languages apply to Forth. I.e., programs are
                   9916: easier to analyse, to optimize and to read: It is clear from the
                   9917: definition what the local stands for, it does not turn into something
                   9918: different later.
1.23      crook    9919: 
1.78      anton    9920: E.g., a definition using @code{TO} might look like this:
                   9921: @example
                   9922: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9923:  u1 u2 min 0
                   9924:  ?do
                   9925:    addr1 c@@ addr2 c@@ -
                   9926:    ?dup-if
                   9927:      unloop exit
                   9928:    then
                   9929:    addr1 char+ TO addr1
                   9930:    addr2 char+ TO addr2
                   9931:  loop
                   9932:  u1 u2 - ;
1.26      crook    9933: @end example
1.78      anton    9934: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9935: every loop iteration. @code{strcmp} is a typical example of the
                   9936: readability problems of using @code{TO}. When you start reading
                   9937: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9938: string. Only near the end of the loop you realize that it is something
                   9939: else.
1.23      crook    9940: 
1.78      anton    9941: This can be avoided by defining two locals at the start of the loop that
                   9942: are initialized with the right value for the current iteration.
                   9943: @example
                   9944: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9945:  addr1 addr2
                   9946:  u1 u2 min 0 
                   9947:  ?do @{ s1 s2 @}
                   9948:    s1 c@@ s2 c@@ -
                   9949:    ?dup-if
                   9950:      unloop exit
                   9951:    then
                   9952:    s1 char+ s2 char+
                   9953:  loop
                   9954:  2drop
                   9955:  u1 u2 - ;
                   9956: @end example
                   9957: Here it is clear from the start that @code{s1} has a different value
                   9958: in every loop iteration.
1.23      crook    9959: 
1.78      anton    9960: @node Locals implementation,  , Locals programming style, Gforth locals
                   9961: @subsubsection Locals implementation
                   9962: @cindex locals implementation
                   9963: @cindex implementation of locals
1.23      crook    9964: 
1.78      anton    9965: @cindex locals stack
                   9966: Gforth uses an extra locals stack. The most compelling reason for
                   9967: this is that the return stack is not float-aligned; using an extra stack
                   9968: also eliminates the problems and restrictions of using the return stack
                   9969: as locals stack. Like the other stacks, the locals stack grows toward
                   9970: lower addresses. A few primitives allow an efficient implementation:
                   9971: 
                   9972: 
                   9973: doc-@local#
                   9974: doc-f@local#
                   9975: doc-laddr#
                   9976: doc-lp+!#
                   9977: doc-lp!
                   9978: doc->l
                   9979: doc-f>l
                   9980: 
                   9981: 
                   9982: In addition to these primitives, some specializations of these
                   9983: primitives for commonly occurring inline arguments are provided for
                   9984: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9985: @code{@@local#} for the inline argument 0. The following compiling words
                   9986: compile the right specialized version, or the general version, as
                   9987: appropriate:
1.23      crook    9988: 
1.5       anton    9989: 
1.107     dvdkhlng 9990: @c doc-compile-@local
                   9991: @c doc-compile-f@local
1.78      anton    9992: doc-compile-lp+!
1.5       anton    9993: 
                   9994: 
1.78      anton    9995: Combinations of conditional branches and @code{lp+!#} like
                   9996: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9997: is taken) are provided for efficiency and correctness in loops.
1.5       anton    9998: 
1.78      anton    9999: A special area in the dictionary space is reserved for keeping the
                   10000: local variable names. @code{@{} switches the dictionary pointer to this
                   10001: area and @code{@}} switches it back and generates the locals
                   10002: initializing code. @code{W:} etc.@ are normal defining words. This
                   10003: special area is cleared at the start of every colon definition.
1.5       anton    10004: 
1.78      anton    10005: @cindex word list for defining locals
                   10006: A special feature of Gforth's dictionary is used to implement the
                   10007: definition of locals without type specifiers: every word list (aka
                   10008: vocabulary) has its own methods for searching
                   10009: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   10010: with a special search method: When it is searched for a word, it
                   10011: actually creates that word using @code{W:}. @code{@{} changes the search
                   10012: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   10013: and then the word list for defining locals without type specifiers.
1.5       anton    10014: 
1.78      anton    10015: The lifetime rules support a stack discipline within a colon
                   10016: definition: The lifetime of a local is either nested with other locals
                   10017: lifetimes or it does not overlap them.
1.23      crook    10018: 
1.78      anton    10019: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   10020: pointer manipulation is generated. Between control structure words
                   10021: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   10022: is the simplest of the other three control flow words. It has to
                   10023: restore the locals stack depth of the corresponding @code{BEGIN}
                   10024: before branching. The code looks like this:
                   10025: @format
                   10026: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   10027: @code{branch} <begin>
                   10028: @end format
1.26      crook    10029: 
1.78      anton    10030: @code{UNTIL} is a little more complicated: If it branches back, it
                   10031: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   10032: the locals stack must not be changed. The compiler generates the
                   10033: following code:
                   10034: @format
                   10035: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   10036: @end format
                   10037: The locals stack pointer is only adjusted if the branch is taken.
1.44      crook    10038: 
1.78      anton    10039: @code{THEN} can produce somewhat inefficient code:
                   10040: @format
                   10041: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   10042: <orig target>:
                   10043: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   10044: @end format
                   10045: The second @code{lp+!#} adjusts the locals stack pointer from the
                   10046: level at the @i{orig} point to the level after the @code{THEN}. The
                   10047: first @code{lp+!#} adjusts the locals stack pointer from the current
                   10048: level to the level at the orig point, so the complete effect is an
                   10049: adjustment from the current level to the right level after the
                   10050: @code{THEN}.
1.26      crook    10051: 
1.78      anton    10052: @cindex locals information on the control-flow stack
                   10053: @cindex control-flow stack items, locals information
                   10054: In a conventional Forth implementation a dest control-flow stack entry
                   10055: is just the target address and an orig entry is just the address to be
                   10056: patched. Our locals implementation adds a word list to every orig or dest
                   10057: item. It is the list of locals visible (or assumed visible) at the point
                   10058: described by the entry. Our implementation also adds a tag to identify
                   10059: the kind of entry, in particular to differentiate between live and dead
                   10060: (reachable and unreachable) orig entries.
1.26      crook    10061: 
1.78      anton    10062: A few unusual operations have to be performed on locals word lists:
1.44      crook    10063: 
1.5       anton    10064: 
1.78      anton    10065: doc-common-list
                   10066: doc-sub-list?
                   10067: doc-list-size
1.52      anton    10068: 
                   10069: 
1.78      anton    10070: Several features of our locals word list implementation make these
                   10071: operations easy to implement: The locals word lists are organised as
                   10072: linked lists; the tails of these lists are shared, if the lists
                   10073: contain some of the same locals; and the address of a name is greater
                   10074: than the address of the names behind it in the list.
1.5       anton    10075: 
1.78      anton    10076: Another important implementation detail is the variable
                   10077: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   10078: determine if they can be reached directly or only through the branch
                   10079: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   10080: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   10081: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5       anton    10082: 
1.78      anton    10083: Counted loops are similar to other loops in most respects, but
                   10084: @code{LEAVE} requires special attention: It performs basically the same
                   10085: service as @code{AHEAD}, but it does not create a control-flow stack
                   10086: entry. Therefore the information has to be stored elsewhere;
                   10087: traditionally, the information was stored in the target fields of the
                   10088: branches created by the @code{LEAVE}s, by organizing these fields into a
                   10089: linked list. Unfortunately, this clever trick does not provide enough
                   10090: space for storing our extended control flow information. Therefore, we
                   10091: introduce another stack, the leave stack. It contains the control-flow
                   10092: stack entries for all unresolved @code{LEAVE}s.
1.44      crook    10093: 
1.78      anton    10094: Local names are kept until the end of the colon definition, even if
                   10095: they are no longer visible in any control-flow path. In a few cases
                   10096: this may lead to increased space needs for the locals name area, but
                   10097: usually less than reclaiming this space would cost in code size.
1.5       anton    10098: 
1.44      crook    10099: 
1.78      anton    10100: @node ANS Forth locals,  , Gforth locals, Locals
                   10101: @subsection ANS Forth locals
                   10102: @cindex locals, ANS Forth style
1.5       anton    10103: 
1.78      anton    10104: The ANS Forth locals wordset does not define a syntax for locals, but
                   10105: words that make it possible to define various syntaxes. One of the
                   10106: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   10107: wordset, i.e.:
1.29      crook    10108: 
                   10109: @example
1.78      anton    10110: @{ local1 local2 ... -- comment @}
                   10111: @end example
                   10112: @noindent
                   10113: or
                   10114: @example
                   10115: @{ local1 local2 ... @}
1.29      crook    10116: @end example
                   10117: 
1.78      anton    10118: The order of the locals corresponds to the order in a stack comment. The
                   10119: restrictions are:
1.5       anton    10120: 
1.78      anton    10121: @itemize @bullet
                   10122: @item
                   10123: Locals can only be cell-sized values (no type specifiers are allowed).
                   10124: @item
                   10125: Locals can be defined only outside control structures.
                   10126: @item
                   10127: Locals can interfere with explicit usage of the return stack. For the
                   10128: exact (and long) rules, see the standard. If you don't use return stack
                   10129: accessing words in a definition using locals, you will be all right. The
                   10130: purpose of this rule is to make locals implementation on the return
                   10131: stack easier.
                   10132: @item
                   10133: The whole definition must be in one line.
                   10134: @end itemize
1.5       anton    10135: 
1.78      anton    10136: Locals defined in ANS Forth behave like @code{VALUE}s
                   10137: (@pxref{Values}). I.e., they are initialized from the stack. Using their
                   10138: name produces their value. Their value can be changed using @code{TO}.
1.77      anton    10139: 
1.78      anton    10140: Since the syntax above is supported by Gforth directly, you need not do
                   10141: anything to use it. If you want to port a program using this syntax to
                   10142: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   10143: syntax on the other system.
1.5       anton    10144: 
1.78      anton    10145: Note that a syntax shown in the standard, section A.13 looks
                   10146: similar, but is quite different in having the order of locals
                   10147: reversed. Beware!
1.5       anton    10148: 
1.78      anton    10149: The ANS Forth locals wordset itself consists of one word:
1.5       anton    10150: 
1.78      anton    10151: doc-(local)
1.5       anton    10152: 
1.78      anton    10153: The ANS Forth locals extension wordset defines a syntax using
                   10154: @code{locals|}, but it is so awful that we strongly recommend not to use
                   10155: it. We have implemented this syntax to make porting to Gforth easy, but
                   10156: do not document it here. The problem with this syntax is that the locals
                   10157: are defined in an order reversed with respect to the standard stack
                   10158: comment notation, making programs harder to read, and easier to misread
                   10159: and miswrite. The only merit of this syntax is that it is easy to
                   10160: implement using the ANS Forth locals wordset.
1.53      anton    10161: 
                   10162: 
1.78      anton    10163: @c ----------------------------------------------------------
                   10164: @node Structures, Object-oriented Forth, Locals, Words
                   10165: @section  Structures
                   10166: @cindex structures
                   10167: @cindex records
1.53      anton    10168: 
1.78      anton    10169: This section presents the structure package that comes with Gforth. A
                   10170: version of the package implemented in ANS Forth is available in
                   10171: @file{compat/struct.fs}. This package was inspired by a posting on
                   10172: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   10173: possibly John Hayes). A version of this section has been published in
                   10174: M. Anton Ertl,
                   10175: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
                   10176: Another Forth Structures Package}, Forth Dimensions 19(3), pages
                   10177: 13--16. Marcel Hendrix provided helpful comments.
1.53      anton    10178: 
1.78      anton    10179: @menu
                   10180: * Why explicit structure support?::  
                   10181: * Structure Usage::             
                   10182: * Structure Naming Convention::  
                   10183: * Structure Implementation::    
                   10184: * Structure Glossary::          
1.183     anton    10185: * Forth200x Structures::        
1.78      anton    10186: @end menu
1.55      anton    10187: 
1.78      anton    10188: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   10189: @subsection Why explicit structure support?
1.53      anton    10190: 
1.78      anton    10191: @cindex address arithmetic for structures
                   10192: @cindex structures using address arithmetic
                   10193: If we want to use a structure containing several fields, we could simply
                   10194: reserve memory for it, and access the fields using address arithmetic
                   10195: (@pxref{Address arithmetic}). As an example, consider a structure with
                   10196: the following fields
1.57      anton    10197: 
1.78      anton    10198: @table @code
                   10199: @item a
                   10200: is a float
                   10201: @item b
                   10202: is a cell
                   10203: @item c
                   10204: is a float
                   10205: @end table
1.57      anton    10206: 
1.78      anton    10207: Given the (float-aligned) base address of the structure we get the
                   10208: address of the field
1.52      anton    10209: 
1.78      anton    10210: @table @code
                   10211: @item a
                   10212: without doing anything further.
                   10213: @item b
                   10214: with @code{float+}
                   10215: @item c
                   10216: with @code{float+ cell+ faligned}
                   10217: @end table
1.52      anton    10218: 
1.78      anton    10219: It is easy to see that this can become quite tiring. 
1.52      anton    10220: 
1.78      anton    10221: Moreover, it is not very readable, because seeing a
                   10222: @code{cell+} tells us neither which kind of structure is
                   10223: accessed nor what field is accessed; we have to somehow infer the kind
                   10224: of structure, and then look up in the documentation, which field of
                   10225: that structure corresponds to that offset.
1.53      anton    10226: 
1.78      anton    10227: Finally, this kind of address arithmetic also causes maintenance
                   10228: troubles: If you add or delete a field somewhere in the middle of the
                   10229: structure, you have to find and change all computations for the fields
                   10230: afterwards.
1.52      anton    10231: 
1.78      anton    10232: So, instead of using @code{cell+} and friends directly, how
                   10233: about storing the offsets in constants:
1.52      anton    10234: 
1.78      anton    10235: @example
                   10236: 0 constant a-offset
                   10237: 0 float+ constant b-offset
                   10238: 0 float+ cell+ faligned c-offset
                   10239: @end example
1.64      pazsan   10240: 
1.78      anton    10241: Now we can get the address of field @code{x} with @code{x-offset
                   10242: +}. This is much better in all respects. Of course, you still
                   10243: have to change all later offset definitions if you add a field. You can
                   10244: fix this by declaring the offsets in the following way:
1.57      anton    10245: 
1.78      anton    10246: @example
                   10247: 0 constant a-offset
                   10248: a-offset float+ constant b-offset
                   10249: b-offset cell+ faligned constant c-offset
                   10250: @end example
1.57      anton    10251: 
1.78      anton    10252: Since we always use the offsets with @code{+}, we could use a defining
                   10253: word @code{cfield} that includes the @code{+} in the action of the
                   10254: defined word:
1.64      pazsan   10255: 
1.78      anton    10256: @example
                   10257: : cfield ( n "name" -- )
                   10258:     create ,
                   10259: does> ( name execution: addr1 -- addr2 )
                   10260:     @@ + ;
1.64      pazsan   10261: 
1.78      anton    10262: 0 cfield a
                   10263: 0 a float+ cfield b
                   10264: 0 b cell+ faligned cfield c
                   10265: @end example
1.64      pazsan   10266: 
1.78      anton    10267: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64      pazsan   10268: 
1.78      anton    10269: The structure field words now can be used quite nicely. However,
                   10270: their definition is still a bit cumbersome: We have to repeat the
                   10271: name, the information about size and alignment is distributed before
                   10272: and after the field definitions etc.  The structure package presented
                   10273: here addresses these problems.
1.64      pazsan   10274: 
1.78      anton    10275: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   10276: @subsection Structure Usage
                   10277: @cindex structure usage
1.57      anton    10278: 
1.78      anton    10279: @cindex @code{field} usage
                   10280: @cindex @code{struct} usage
                   10281: @cindex @code{end-struct} usage
                   10282: You can define a structure for a (data-less) linked list with:
1.57      anton    10283: @example
1.78      anton    10284: struct
                   10285:     cell% field list-next
                   10286: end-struct list%
1.57      anton    10287: @end example
                   10288: 
1.78      anton    10289: With the address of the list node on the stack, you can compute the
                   10290: address of the field that contains the address of the next node with
                   10291: @code{list-next}. E.g., you can determine the length of a list
                   10292: with:
1.57      anton    10293: 
                   10294: @example
1.78      anton    10295: : list-length ( list -- n )
                   10296: \ "list" is a pointer to the first element of a linked list
                   10297: \ "n" is the length of the list
                   10298:     0 BEGIN ( list1 n1 )
                   10299:         over
                   10300:     WHILE ( list1 n1 )
                   10301:         1+ swap list-next @@ swap
                   10302:     REPEAT
                   10303:     nip ;
1.57      anton    10304: @end example
                   10305: 
1.78      anton    10306: You can reserve memory for a list node in the dictionary with
                   10307: @code{list% %allot}, which leaves the address of the list node on the
                   10308: stack. For the equivalent allocation on the heap you can use @code{list%
                   10309: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   10310: use @code{list% %allocate}). You can get the the size of a list
                   10311: node with @code{list% %size} and its alignment with @code{list%
                   10312: %alignment}.
                   10313: 
                   10314: Note that in ANS Forth the body of a @code{create}d word is
                   10315: @code{aligned} but not necessarily @code{faligned};
                   10316: therefore, if you do a:
1.57      anton    10317: 
                   10318: @example
1.78      anton    10319: create @emph{name} foo% %allot drop
1.57      anton    10320: @end example
                   10321: 
1.78      anton    10322: @noindent
                   10323: then the memory alloted for @code{foo%} is guaranteed to start at the
                   10324: body of @code{@emph{name}} only if @code{foo%} contains only character,
                   10325: cell and double fields.  Therefore, if your structure contains floats,
                   10326: better use
1.57      anton    10327: 
                   10328: @example
1.78      anton    10329: foo% %allot constant @emph{name}
1.57      anton    10330: @end example
                   10331: 
1.78      anton    10332: @cindex structures containing structures
                   10333: You can include a structure @code{foo%} as a field of
                   10334: another structure, like this:
1.65      anton    10335: @example
1.78      anton    10336: struct
                   10337: ...
                   10338:     foo% field ...
                   10339: ...
                   10340: end-struct ...
1.65      anton    10341: @end example
1.52      anton    10342: 
1.78      anton    10343: @cindex structure extension
                   10344: @cindex extended records
                   10345: Instead of starting with an empty structure, you can extend an
                   10346: existing structure. E.g., a plain linked list without data, as defined
                   10347: above, is hardly useful; You can extend it to a linked list of integers,
                   10348: like this:@footnote{This feature is also known as @emph{extended
                   10349: records}. It is the main innovation in the Oberon language; in other
                   10350: words, adding this feature to Modula-2 led Wirth to create a new
                   10351: language, write a new compiler etc.  Adding this feature to Forth just
                   10352: required a few lines of code.}
1.52      anton    10353: 
1.78      anton    10354: @example
                   10355: list%
                   10356:     cell% field intlist-int
                   10357: end-struct intlist%
                   10358: @end example
1.55      anton    10359: 
1.78      anton    10360: @code{intlist%} is a structure with two fields:
                   10361: @code{list-next} and @code{intlist-int}.
1.55      anton    10362: 
1.78      anton    10363: @cindex structures containing arrays
                   10364: You can specify an array type containing @emph{n} elements of
                   10365: type @code{foo%} like this:
1.55      anton    10366: 
                   10367: @example
1.78      anton    10368: foo% @emph{n} *
1.56      anton    10369: @end example
1.55      anton    10370: 
1.78      anton    10371: You can use this array type in any place where you can use a normal
                   10372: type, e.g., when defining a @code{field}, or with
                   10373: @code{%allot}.
                   10374: 
                   10375: @cindex first field optimization
                   10376: The first field is at the base address of a structure and the word for
                   10377: this field (e.g., @code{list-next}) actually does not change the address
                   10378: on the stack. You may be tempted to leave it away in the interest of
                   10379: run-time and space efficiency. This is not necessary, because the
                   10380: structure package optimizes this case: If you compile a first-field
                   10381: words, no code is generated. So, in the interest of readability and
                   10382: maintainability you should include the word for the field when accessing
                   10383: the field.
1.52      anton    10384: 
                   10385: 
1.78      anton    10386: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   10387: @subsection Structure Naming Convention
                   10388: @cindex structure naming convention
1.52      anton    10389: 
1.78      anton    10390: The field names that come to (my) mind are often quite generic, and,
                   10391: if used, would cause frequent name clashes. E.g., many structures
                   10392: probably contain a @code{counter} field. The structure names
                   10393: that come to (my) mind are often also the logical choice for the names
                   10394: of words that create such a structure.
1.52      anton    10395: 
1.78      anton    10396: Therefore, I have adopted the following naming conventions: 
1.52      anton    10397: 
1.78      anton    10398: @itemize @bullet
                   10399: @cindex field naming convention
                   10400: @item
                   10401: The names of fields are of the form
                   10402: @code{@emph{struct}-@emph{field}}, where
                   10403: @code{@emph{struct}} is the basic name of the structure, and
                   10404: @code{@emph{field}} is the basic name of the field. You can
                   10405: think of field words as converting the (address of the)
                   10406: structure into the (address of the) field.
1.52      anton    10407: 
1.78      anton    10408: @cindex structure naming convention
                   10409: @item
                   10410: The names of structures are of the form
                   10411: @code{@emph{struct}%}, where
                   10412: @code{@emph{struct}} is the basic name of the structure.
                   10413: @end itemize
1.52      anton    10414: 
1.78      anton    10415: This naming convention does not work that well for fields of extended
                   10416: structures; e.g., the integer list structure has a field
                   10417: @code{intlist-int}, but has @code{list-next}, not
                   10418: @code{intlist-next}.
1.53      anton    10419: 
1.78      anton    10420: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   10421: @subsection Structure Implementation
                   10422: @cindex structure implementation
                   10423: @cindex implementation of structures
1.52      anton    10424: 
1.78      anton    10425: The central idea in the implementation is to pass the data about the
                   10426: structure being built on the stack, not in some global
                   10427: variable. Everything else falls into place naturally once this design
                   10428: decision is made.
1.53      anton    10429: 
1.78      anton    10430: The type description on the stack is of the form @emph{align
                   10431: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   10432: very simple.
1.53      anton    10433: 
1.78      anton    10434: @code{field} is a defining word that uses @code{Create}
                   10435: and @code{DOES>}. The body of the field contains the offset
                   10436: of the field, and the normal @code{DOES>} action is simply:
1.53      anton    10437: 
                   10438: @example
1.78      anton    10439: @@ +
1.53      anton    10440: @end example
                   10441: 
1.78      anton    10442: @noindent
                   10443: i.e., add the offset to the address, giving the stack effect
                   10444: @i{addr1 -- addr2} for a field.
                   10445: 
                   10446: @cindex first field optimization, implementation
                   10447: This simple structure is slightly complicated by the optimization
                   10448: for fields with offset 0, which requires a different
                   10449: @code{DOES>}-part (because we cannot rely on there being
                   10450: something on the stack if such a field is invoked during
                   10451: compilation). Therefore, we put the different @code{DOES>}-parts
                   10452: in separate words, and decide which one to invoke based on the
                   10453: offset. For a zero offset, the field is basically a noop; it is
                   10454: immediate, and therefore no code is generated when it is compiled.
1.53      anton    10455: 
1.183     anton    10456: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78      anton    10457: @subsection Structure Glossary
                   10458: @cindex structure glossary
1.53      anton    10459: 
1.5       anton    10460: 
1.78      anton    10461: doc-%align
                   10462: doc-%alignment
                   10463: doc-%alloc
                   10464: doc-%allocate
                   10465: doc-%allot
                   10466: doc-cell%
                   10467: doc-char%
                   10468: doc-dfloat%
                   10469: doc-double%
                   10470: doc-end-struct
                   10471: doc-field
                   10472: doc-float%
                   10473: doc-naligned
                   10474: doc-sfloat%
                   10475: doc-%size
                   10476: doc-struct
1.54      anton    10477: 
                   10478: 
1.183     anton    10479: @node Forth200x Structures,  , Structure Glossary, Structures
                   10480: @subsection Forth200x Structures
                   10481: @cindex Structures in Forth200x
                   10482: 
                   10483: The Forth 200x standard defines a slightly less convenient form of
                   10484: structures.  In general (when using @code{field+}, you have to perform
                   10485: the alignment yourself, but there are a number of convenience words
                   10486: (e.g., @code{field:} that perform the alignment for you.
                   10487: 
                   10488: A typical usage example is:
                   10489: 
                   10490: @example
                   10491: 0
                   10492:   field:                   s-a
                   10493:   faligned 2 floats +field s-b
                   10494: constant s-struct
                   10495: @end example
                   10496: 
                   10497: An alternative way of writing this structure is:
                   10498: 
                   10499: @example
                   10500: begin-structure s-struct
                   10501:   field:                   s-a
                   10502:   faligned 2 floats +field s-b
                   10503: end-structure
                   10504: @end example
                   10505: 
                   10506: doc-begin-structure
                   10507: doc-end-structure
                   10508: doc-+field
                   10509: doc-cfield:
                   10510: doc-field:
                   10511: doc-2field:
                   10512: doc-ffield:
                   10513: doc-sffield:
                   10514: doc-dffield:
                   10515: 
1.26      crook    10516: @c -------------------------------------------------------------
1.78      anton    10517: @node Object-oriented Forth, Programming Tools, Structures, Words
                   10518: @section Object-oriented Forth
                   10519: 
                   10520: Gforth comes with three packages for object-oriented programming:
                   10521: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   10522: is preloaded, so you have to @code{include} them before use. The most
                   10523: important differences between these packages (and others) are discussed
                   10524: in @ref{Comparison with other object models}. All packages are written
                   10525: in ANS Forth and can be used with any other ANS Forth.
1.5       anton    10526: 
1.78      anton    10527: @menu
                   10528: * Why object-oriented programming?::  
                   10529: * Object-Oriented Terminology::  
                   10530: * Objects::                     
                   10531: * OOF::                         
                   10532: * Mini-OOF::                    
                   10533: * Comparison with other object models::  
                   10534: @end menu
1.5       anton    10535: 
1.78      anton    10536: @c ----------------------------------------------------------------
                   10537: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   10538: @subsection Why object-oriented programming?
                   10539: @cindex object-oriented programming motivation
                   10540: @cindex motivation for object-oriented programming
1.44      crook    10541: 
1.78      anton    10542: Often we have to deal with several data structures (@emph{objects}),
                   10543: that have to be treated similarly in some respects, but differently in
                   10544: others. Graphical objects are the textbook example: circles, triangles,
                   10545: dinosaurs, icons, and others, and we may want to add more during program
                   10546: development. We want to apply some operations to any graphical object,
                   10547: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   10548: has to do something different for every kind of object.
                   10549: @comment TODO add some other operations eg perimeter, area
                   10550: @comment and tie in to concrete examples later..
1.5       anton    10551: 
1.78      anton    10552: We could implement @code{draw} as a big @code{CASE}
                   10553: control structure that executes the appropriate code depending on the
                   10554: kind of object to be drawn. This would be not be very elegant, and,
                   10555: moreover, we would have to change @code{draw} every time we add
                   10556: a new kind of graphical object (say, a spaceship).
1.44      crook    10557: 
1.78      anton    10558: What we would rather do is: When defining spaceships, we would tell
                   10559: the system: ``Here's how you @code{draw} a spaceship; you figure
                   10560: out the rest''.
1.5       anton    10561: 
1.78      anton    10562: This is the problem that all systems solve that (rightfully) call
                   10563: themselves object-oriented; the object-oriented packages presented here
                   10564: solve this problem (and not much else).
                   10565: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44      crook    10566: 
1.78      anton    10567: @c ------------------------------------------------------------------------
                   10568: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   10569: @subsection Object-Oriented Terminology
                   10570: @cindex object-oriented terminology
                   10571: @cindex terminology for object-oriented programming
1.5       anton    10572: 
1.78      anton    10573: This section is mainly for reference, so you don't have to understand
                   10574: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   10575: short:
1.44      crook    10576: 
1.78      anton    10577: @table @emph
                   10578: @cindex class
                   10579: @item class
                   10580: a data structure definition with some extras.
1.5       anton    10581: 
1.78      anton    10582: @cindex object
                   10583: @item object
                   10584: an instance of the data structure described by the class definition.
1.5       anton    10585: 
1.78      anton    10586: @cindex instance variables
                   10587: @item instance variables
                   10588: fields of the data structure.
1.5       anton    10589: 
1.78      anton    10590: @cindex selector
                   10591: @cindex method selector
                   10592: @cindex virtual function
                   10593: @item selector
                   10594: (or @emph{method selector}) a word (e.g.,
                   10595: @code{draw}) that performs an operation on a variety of data
                   10596: structures (classes). A selector describes @emph{what} operation to
                   10597: perform. In C++ terminology: a (pure) virtual function.
1.5       anton    10598: 
1.78      anton    10599: @cindex method
                   10600: @item method
                   10601: the concrete definition that performs the operation
                   10602: described by the selector for a specific class. A method specifies
                   10603: @emph{how} the operation is performed for a specific class.
1.5       anton    10604: 
1.78      anton    10605: @cindex selector invocation
                   10606: @cindex message send
                   10607: @cindex invoking a selector
                   10608: @item selector invocation
                   10609: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   10610: is used for determining which method is used. In Smalltalk terminology:
                   10611: a message (consisting of the selector and the other arguments) is sent
                   10612: to the object.
1.5       anton    10613: 
1.78      anton    10614: @cindex receiving object
                   10615: @item receiving object
                   10616: the object used for determining the method executed by a selector
                   10617: invocation. In the @file{objects.fs} model, it is the object that is on
                   10618: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   10619: the Smalltalk @emph{message} terminology.)
1.5       anton    10620: 
1.78      anton    10621: @cindex child class
                   10622: @cindex parent class
                   10623: @cindex inheritance
                   10624: @item child class
                   10625: a class that has (@emph{inherits}) all properties (instance variables,
                   10626: selectors, methods) from a @emph{parent class}. In Smalltalk
                   10627: terminology: The subclass inherits from the superclass. In C++
                   10628: terminology: The derived class inherits from the base class.
1.5       anton    10629: 
1.78      anton    10630: @end table
1.5       anton    10631: 
1.78      anton    10632: @c If you wonder about the message sending terminology, it comes from
                   10633: @c a time when each object had it's own task and objects communicated via
                   10634: @c message passing; eventually the Smalltalk developers realized that
                   10635: @c they can do most things through simple (indirect) calls. They kept the
                   10636: @c terminology.
1.5       anton    10637: 
1.78      anton    10638: @c --------------------------------------------------------------
                   10639: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   10640: @subsection The @file{objects.fs} model
                   10641: @cindex objects
                   10642: @cindex object-oriented programming
1.26      crook    10643: 
1.78      anton    10644: @cindex @file{objects.fs}
                   10645: @cindex @file{oof.fs}
1.26      crook    10646: 
1.78      anton    10647: This section describes the @file{objects.fs} package. This material also
                   10648: has been published in M. Anton Ertl,
                   10649: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
                   10650: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
                   10651: 37--43.
                   10652: @c McKewan's and Zsoter's packages
1.26      crook    10653: 
1.78      anton    10654: This section assumes that you have read @ref{Structures}.
1.5       anton    10655: 
1.78      anton    10656: The techniques on which this model is based have been used to implement
                   10657: the parser generator, Gray, and have also been used in Gforth for
                   10658: implementing the various flavours of word lists (hashed or not,
                   10659: case-sensitive or not, special-purpose word lists for locals etc.).
1.5       anton    10660: 
                   10661: 
1.26      crook    10662: @menu
1.78      anton    10663: * Properties of the Objects model::  
                   10664: * Basic Objects Usage::         
                   10665: * The Objects base class::      
                   10666: * Creating objects::            
                   10667: * Object-Oriented Programming Style::  
                   10668: * Class Binding::               
                   10669: * Method conveniences::         
                   10670: * Classes and Scoping::         
                   10671: * Dividing classes::            
                   10672: * Object Interfaces::           
                   10673: * Objects Implementation::      
                   10674: * Objects Glossary::            
1.26      crook    10675: @end menu
1.5       anton    10676: 
1.78      anton    10677: Marcel Hendrix provided helpful comments on this section.
1.5       anton    10678: 
1.78      anton    10679: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   10680: @subsubsection Properties of the @file{objects.fs} model
                   10681: @cindex @file{objects.fs} properties
1.5       anton    10682: 
1.78      anton    10683: @itemize @bullet
                   10684: @item
                   10685: It is straightforward to pass objects on the stack. Passing
                   10686: selectors on the stack is a little less convenient, but possible.
1.44      crook    10687: 
1.78      anton    10688: @item
                   10689: Objects are just data structures in memory, and are referenced by their
                   10690: address. You can create words for objects with normal defining words
                   10691: like @code{constant}. Likewise, there is no difference between instance
                   10692: variables that contain objects and those that contain other data.
1.5       anton    10693: 
1.78      anton    10694: @item
                   10695: Late binding is efficient and easy to use.
1.44      crook    10696: 
1.78      anton    10697: @item
                   10698: It avoids parsing, and thus avoids problems with state-smartness
                   10699: and reduced extensibility; for convenience there are a few parsing
                   10700: words, but they have non-parsing counterparts. There are also a few
                   10701: defining words that parse. This is hard to avoid, because all standard
                   10702: defining words parse (except @code{:noname}); however, such
                   10703: words are not as bad as many other parsing words, because they are not
                   10704: state-smart.
1.5       anton    10705: 
1.78      anton    10706: @item
                   10707: It does not try to incorporate everything. It does a few things and does
                   10708: them well (IMO). In particular, this model was not designed to support
                   10709: information hiding (although it has features that may help); you can use
                   10710: a separate package for achieving this.
1.5       anton    10711: 
1.78      anton    10712: @item
                   10713: It is layered; you don't have to learn and use all features to use this
                   10714: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   10715: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
                   10716: are optional and independent of each other.
1.5       anton    10717: 
1.78      anton    10718: @item
                   10719: An implementation in ANS Forth is available.
1.5       anton    10720: 
1.78      anton    10721: @end itemize
1.5       anton    10722: 
1.44      crook    10723: 
1.78      anton    10724: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   10725: @subsubsection Basic @file{objects.fs} Usage
                   10726: @cindex basic objects usage
                   10727: @cindex objects, basic usage
1.5       anton    10728: 
1.78      anton    10729: You can define a class for graphical objects like this:
1.44      crook    10730: 
1.78      anton    10731: @cindex @code{class} usage
                   10732: @cindex @code{end-class} usage
                   10733: @cindex @code{selector} usage
1.5       anton    10734: @example
1.78      anton    10735: object class \ "object" is the parent class
                   10736:   selector draw ( x y graphical -- )
                   10737: end-class graphical
                   10738: @end example
                   10739: 
                   10740: This code defines a class @code{graphical} with an
                   10741: operation @code{draw}.  We can perform the operation
                   10742: @code{draw} on any @code{graphical} object, e.g.:
                   10743: 
                   10744: @example
                   10745: 100 100 t-rex draw
1.26      crook    10746: @end example
1.5       anton    10747: 
1.78      anton    10748: @noindent
                   10749: where @code{t-rex} is a word (say, a constant) that produces a
                   10750: graphical object.
                   10751: 
                   10752: @comment TODO add a 2nd operation eg perimeter.. and use for
                   10753: @comment a concrete example
1.5       anton    10754: 
1.78      anton    10755: @cindex abstract class
                   10756: How do we create a graphical object? With the present definitions,
                   10757: we cannot create a useful graphical object. The class
                   10758: @code{graphical} describes graphical objects in general, but not
                   10759: any concrete graphical object type (C++ users would call it an
                   10760: @emph{abstract class}); e.g., there is no method for the selector
                   10761: @code{draw} in the class @code{graphical}.
1.5       anton    10762: 
1.78      anton    10763: For concrete graphical objects, we define child classes of the
                   10764: class @code{graphical}, e.g.:
1.5       anton    10765: 
1.78      anton    10766: @cindex @code{overrides} usage
                   10767: @cindex @code{field} usage in class definition
1.26      crook    10768: @example
1.78      anton    10769: graphical class \ "graphical" is the parent class
                   10770:   cell% field circle-radius
1.5       anton    10771: 
1.78      anton    10772: :noname ( x y circle -- )
                   10773:   circle-radius @@ draw-circle ;
                   10774: overrides draw
1.5       anton    10775: 
1.78      anton    10776: :noname ( n-radius circle -- )
                   10777:   circle-radius ! ;
                   10778: overrides construct
1.5       anton    10779: 
1.78      anton    10780: end-class circle
                   10781: @end example
1.44      crook    10782: 
1.78      anton    10783: Here we define a class @code{circle} as a child of @code{graphical},
                   10784: with field @code{circle-radius} (which behaves just like a field
                   10785: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   10786: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   10787: defined in @code{object}, the parent class of @code{graphical}).
1.5       anton    10788: 
1.78      anton    10789: Now we can create a circle on the heap (i.e.,
                   10790: @code{allocate}d memory) with:
1.44      crook    10791: 
1.78      anton    10792: @cindex @code{heap-new} usage
1.5       anton    10793: @example
1.78      anton    10794: 50 circle heap-new constant my-circle
1.5       anton    10795: @end example
                   10796: 
1.78      anton    10797: @noindent
                   10798: @code{heap-new} invokes @code{construct}, thus
                   10799: initializing the field @code{circle-radius} with 50. We can draw
                   10800: this new circle at (100,100) with:
1.5       anton    10801: 
                   10802: @example
1.78      anton    10803: 100 100 my-circle draw
1.5       anton    10804: @end example
                   10805: 
1.78      anton    10806: @cindex selector invocation, restrictions
                   10807: @cindex class definition, restrictions
                   10808: Note: You can only invoke a selector if the object on the TOS
                   10809: (the receiving object) belongs to the class where the selector was
                   10810: defined or one of its descendents; e.g., you can invoke
                   10811: @code{draw} only for objects belonging to @code{graphical}
                   10812: or its descendents (e.g., @code{circle}).  Immediately before
                   10813: @code{end-class}, the search order has to be the same as
                   10814: immediately after @code{class}.
                   10815: 
                   10816: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   10817: @subsubsection The @file{object.fs} base class
                   10818: @cindex @code{object} class
                   10819: 
                   10820: When you define a class, you have to specify a parent class.  So how do
                   10821: you start defining classes? There is one class available from the start:
                   10822: @code{object}. It is ancestor for all classes and so is the
                   10823: only class that has no parent. It has two selectors: @code{construct}
                   10824: and @code{print}.
                   10825: 
                   10826: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   10827: @subsubsection Creating objects
                   10828: @cindex creating objects
                   10829: @cindex object creation
                   10830: @cindex object allocation options
                   10831: 
                   10832: @cindex @code{heap-new} discussion
                   10833: @cindex @code{dict-new} discussion
                   10834: @cindex @code{construct} discussion
                   10835: You can create and initialize an object of a class on the heap with
                   10836: @code{heap-new} ( ... class -- object ) and in the dictionary
                   10837: (allocation with @code{allot}) with @code{dict-new} (
                   10838: ... class -- object ). Both words invoke @code{construct}, which
                   10839: consumes the stack items indicated by "..." above.
                   10840: 
                   10841: @cindex @code{init-object} discussion
                   10842: @cindex @code{class-inst-size} discussion
                   10843: If you want to allocate memory for an object yourself, you can get its
                   10844: alignment and size with @code{class-inst-size 2@@} ( class --
                   10845: align size ). Once you have memory for an object, you can initialize
                   10846: it with @code{init-object} ( ... class object -- );
                   10847: @code{construct} does only a part of the necessary work.
                   10848: 
                   10849: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   10850: @subsubsection Object-Oriented Programming Style
                   10851: @cindex object-oriented programming style
                   10852: @cindex programming style, object-oriented
1.5       anton    10853: 
1.78      anton    10854: This section is not exhaustive.
1.5       anton    10855: 
1.78      anton    10856: @cindex stack effects of selectors
                   10857: @cindex selectors and stack effects
                   10858: In general, it is a good idea to ensure that all methods for the
                   10859: same selector have the same stack effect: when you invoke a selector,
                   10860: you often have no idea which method will be invoked, so, unless all
                   10861: methods have the same stack effect, you will not know the stack effect
                   10862: of the selector invocation.
1.5       anton    10863: 
1.78      anton    10864: One exception to this rule is methods for the selector
                   10865: @code{construct}. We know which method is invoked, because we
                   10866: specify the class to be constructed at the same place. Actually, I
                   10867: defined @code{construct} as a selector only to give the users a
                   10868: convenient way to specify initialization. The way it is used, a
                   10869: mechanism different from selector invocation would be more natural
                   10870: (but probably would take more code and more space to explain).
1.5       anton    10871: 
1.78      anton    10872: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   10873: @subsubsection Class Binding
                   10874: @cindex class binding
                   10875: @cindex early binding
1.5       anton    10876: 
1.78      anton    10877: @cindex late binding
                   10878: Normal selector invocations determine the method at run-time depending
                   10879: on the class of the receiving object. This run-time selection is called
                   10880: @i{late binding}.
1.5       anton    10881: 
1.78      anton    10882: Sometimes it's preferable to invoke a different method. For example,
                   10883: you might want to use the simple method for @code{print}ing
                   10884: @code{object}s instead of the possibly long-winded @code{print} method
                   10885: of the receiver class. You can achieve this by replacing the invocation
                   10886: of @code{print} with:
1.5       anton    10887: 
1.78      anton    10888: @cindex @code{[bind]} usage
1.5       anton    10889: @example
1.78      anton    10890: [bind] object print
1.5       anton    10891: @end example
                   10892: 
1.78      anton    10893: @noindent
                   10894: in compiled code or:
                   10895: 
                   10896: @cindex @code{bind} usage
1.5       anton    10897: @example
1.78      anton    10898: bind object print
1.5       anton    10899: @end example
                   10900: 
1.78      anton    10901: @cindex class binding, alternative to
                   10902: @noindent
                   10903: in interpreted code. Alternatively, you can define the method with a
                   10904: name (e.g., @code{print-object}), and then invoke it through the
                   10905: name. Class binding is just a (often more convenient) way to achieve
                   10906: the same effect; it avoids name clutter and allows you to invoke
                   10907: methods directly without naming them first.
1.5       anton    10908: 
1.78      anton    10909: @cindex superclass binding
                   10910: @cindex parent class binding
                   10911: A frequent use of class binding is this: When we define a method
                   10912: for a selector, we often want the method to do what the selector does
                   10913: in the parent class, and a little more. There is a special word for
                   10914: this purpose: @code{[parent]}; @code{[parent]
                   10915: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   10916: selector}}, where @code{@emph{parent}} is the parent
                   10917: class of the current class. E.g., a method definition might look like:
1.44      crook    10918: 
1.78      anton    10919: @cindex @code{[parent]} usage
                   10920: @example
                   10921: :noname
                   10922:   dup [parent] foo \ do parent's foo on the receiving object
                   10923:   ... \ do some more
                   10924: ; overrides foo
                   10925: @end example
1.6       pazsan   10926: 
1.78      anton    10927: @cindex class binding as optimization
                   10928: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10929: March 1997), Andrew McKewan presents class binding as an optimization
                   10930: technique. I recommend not using it for this purpose unless you are in
                   10931: an emergency. Late binding is pretty fast with this model anyway, so the
                   10932: benefit of using class binding is small; the cost of using class binding
                   10933: where it is not appropriate is reduced maintainability.
1.44      crook    10934: 
1.78      anton    10935: While we are at programming style questions: You should bind
                   10936: selectors only to ancestor classes of the receiving object. E.g., say,
                   10937: you know that the receiving object is of class @code{foo} or its
                   10938: descendents; then you should bind only to @code{foo} and its
                   10939: ancestors.
1.12      anton    10940: 
1.78      anton    10941: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10942: @subsubsection Method conveniences
                   10943: @cindex method conveniences
1.44      crook    10944: 
1.78      anton    10945: In a method you usually access the receiving object pretty often.  If
                   10946: you define the method as a plain colon definition (e.g., with
                   10947: @code{:noname}), you may have to do a lot of stack
                   10948: gymnastics. To avoid this, you can define the method with @code{m:
                   10949: ... ;m}. E.g., you could define the method for
                   10950: @code{draw}ing a @code{circle} with
1.6       pazsan   10951: 
1.78      anton    10952: @cindex @code{this} usage
                   10953: @cindex @code{m:} usage
                   10954: @cindex @code{;m} usage
                   10955: @example
                   10956: m: ( x y circle -- )
                   10957:   ( x y ) this circle-radius @@ draw-circle ;m
                   10958: @end example
1.6       pazsan   10959: 
1.78      anton    10960: @cindex @code{exit} in @code{m: ... ;m}
                   10961: @cindex @code{exitm} discussion
                   10962: @cindex @code{catch} in @code{m: ... ;m}
                   10963: When this method is executed, the receiver object is removed from the
                   10964: stack; you can access it with @code{this} (admittedly, in this
                   10965: example the use of @code{m: ... ;m} offers no advantage). Note
                   10966: that I specify the stack effect for the whole method (i.e. including
                   10967: the receiver object), not just for the code between @code{m:}
                   10968: and @code{;m}. You cannot use @code{exit} in
                   10969: @code{m:...;m}; instead, use
                   10970: @code{exitm}.@footnote{Moreover, for any word that calls
                   10971: @code{catch} and was defined before loading
                   10972: @code{objects.fs}, you have to redefine it like I redefined
                   10973: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12      anton    10974: 
1.78      anton    10975: @cindex @code{inst-var} usage
                   10976: You will frequently use sequences of the form @code{this
                   10977: @emph{field}} (in the example above: @code{this
                   10978: circle-radius}). If you use the field only in this way, you can
                   10979: define it with @code{inst-var} and eliminate the
                   10980: @code{this} before the field name. E.g., the @code{circle}
                   10981: class above could also be defined with:
1.6       pazsan   10982: 
1.78      anton    10983: @example
                   10984: graphical class
                   10985:   cell% inst-var radius
1.6       pazsan   10986: 
1.78      anton    10987: m: ( x y circle -- )
                   10988:   radius @@ draw-circle ;m
                   10989: overrides draw
1.6       pazsan   10990: 
1.78      anton    10991: m: ( n-radius circle -- )
                   10992:   radius ! ;m
                   10993: overrides construct
1.6       pazsan   10994: 
1.78      anton    10995: end-class circle
                   10996: @end example
1.6       pazsan   10997: 
1.78      anton    10998: @code{radius} can only be used in @code{circle} and its
                   10999: descendent classes and inside @code{m:...;m}.
1.6       pazsan   11000: 
1.78      anton    11001: @cindex @code{inst-value} usage
                   11002: You can also define fields with @code{inst-value}, which is
                   11003: to @code{inst-var} what @code{value} is to
                   11004: @code{variable}.  You can change the value of such a field with
                   11005: @code{[to-inst]}.  E.g., we could also define the class
                   11006: @code{circle} like this:
1.44      crook    11007: 
1.78      anton    11008: @example
                   11009: graphical class
                   11010:   inst-value radius
1.6       pazsan   11011: 
1.78      anton    11012: m: ( x y circle -- )
                   11013:   radius draw-circle ;m
                   11014: overrides draw
1.44      crook    11015: 
1.78      anton    11016: m: ( n-radius circle -- )
                   11017:   [to-inst] radius ;m
                   11018: overrides construct
1.6       pazsan   11019: 
1.78      anton    11020: end-class circle
                   11021: @end example
1.6       pazsan   11022: 
1.78      anton    11023: @c !! :m is easy to confuse with m:.  Another name would be better.
1.6       pazsan   11024: 
1.78      anton    11025: @c Finally, you can define named methods with @code{:m}.  One use of this
                   11026: @c feature is the definition of words that occur only in one class and are
                   11027: @c not intended to be overridden, but which still need method context
                   11028: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   11029: @c would be bound frequently, if defined anonymously.
1.6       pazsan   11030: 
                   11031: 
1.78      anton    11032: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
                   11033: @subsubsection Classes and Scoping
                   11034: @cindex classes and scoping
                   11035: @cindex scoping and classes
1.6       pazsan   11036: 
1.78      anton    11037: Inheritance is frequent, unlike structure extension. This exacerbates
                   11038: the problem with the field name convention (@pxref{Structure Naming
                   11039: Convention}): One always has to remember in which class the field was
                   11040: originally defined; changing a part of the class structure would require
                   11041: changes for renaming in otherwise unaffected code.
1.6       pazsan   11042: 
1.78      anton    11043: @cindex @code{inst-var} visibility
                   11044: @cindex @code{inst-value} visibility
                   11045: To solve this problem, I added a scoping mechanism (which was not in my
                   11046: original charter): A field defined with @code{inst-var} (or
                   11047: @code{inst-value}) is visible only in the class where it is defined and in
                   11048: the descendent classes of this class.  Using such fields only makes
                   11049: sense in @code{m:}-defined methods in these classes anyway.
1.6       pazsan   11050: 
1.78      anton    11051: This scoping mechanism allows us to use the unadorned field name,
                   11052: because name clashes with unrelated words become much less likely.
1.6       pazsan   11053: 
1.78      anton    11054: @cindex @code{protected} discussion
                   11055: @cindex @code{private} discussion
                   11056: Once we have this mechanism, we can also use it for controlling the
                   11057: visibility of other words: All words defined after
                   11058: @code{protected} are visible only in the current class and its
                   11059: descendents. @code{public} restores the compilation
                   11060: (i.e. @code{current}) word list that was in effect before. If you
                   11061: have several @code{protected}s without an intervening
                   11062: @code{public} or @code{set-current}, @code{public}
                   11063: will restore the compilation word list in effect before the first of
                   11064: these @code{protected}s.
1.6       pazsan   11065: 
1.78      anton    11066: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   11067: @subsubsection Dividing classes
                   11068: @cindex Dividing classes
                   11069: @cindex @code{methods}...@code{end-methods}
1.6       pazsan   11070: 
1.78      anton    11071: You may want to do the definition of methods separate from the
                   11072: definition of the class, its selectors, fields, and instance variables,
                   11073: i.e., separate the implementation from the definition.  You can do this
                   11074: in the following way:
1.6       pazsan   11075: 
1.78      anton    11076: @example
                   11077: graphical class
                   11078:   inst-value radius
                   11079: end-class circle
1.6       pazsan   11080: 
1.78      anton    11081: ... \ do some other stuff
1.6       pazsan   11082: 
1.78      anton    11083: circle methods \ now we are ready
1.44      crook    11084: 
1.78      anton    11085: m: ( x y circle -- )
                   11086:   radius draw-circle ;m
                   11087: overrides draw
1.6       pazsan   11088: 
1.78      anton    11089: m: ( n-radius circle -- )
                   11090:   [to-inst] radius ;m
                   11091: overrides construct
1.44      crook    11092: 
1.78      anton    11093: end-methods
                   11094: @end example
1.7       pazsan   11095: 
1.78      anton    11096: You can use several @code{methods}...@code{end-methods} sections.  The
                   11097: only things you can do to the class in these sections are: defining
                   11098: methods, and overriding the class's selectors.  You must not define new
                   11099: selectors or fields.
1.7       pazsan   11100: 
1.78      anton    11101: Note that you often have to override a selector before using it.  In
                   11102: particular, you usually have to override @code{construct} with a new
                   11103: method before you can invoke @code{heap-new} and friends.  E.g., you
                   11104: must not create a circle before the @code{overrides construct} sequence
                   11105: in the example above.
1.7       pazsan   11106: 
1.78      anton    11107: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
                   11108: @subsubsection Object Interfaces
                   11109: @cindex object interfaces
                   11110: @cindex interfaces for objects
1.7       pazsan   11111: 
1.78      anton    11112: In this model you can only call selectors defined in the class of the
                   11113: receiving objects or in one of its ancestors. If you call a selector
                   11114: with a receiving object that is not in one of these classes, the
                   11115: result is undefined; if you are lucky, the program crashes
                   11116: immediately.
1.7       pazsan   11117: 
1.78      anton    11118: @cindex selectors common to hardly-related classes
                   11119: Now consider the case when you want to have a selector (or several)
                   11120: available in two classes: You would have to add the selector to a
                   11121: common ancestor class, in the worst case to @code{object}. You
                   11122: may not want to do this, e.g., because someone else is responsible for
                   11123: this ancestor class.
1.7       pazsan   11124: 
1.78      anton    11125: The solution for this problem is interfaces. An interface is a
                   11126: collection of selectors. If a class implements an interface, the
                   11127: selectors become available to the class and its descendents. A class
                   11128: can implement an unlimited number of interfaces. For the problem
                   11129: discussed above, we would define an interface for the selector(s), and
                   11130: both classes would implement the interface.
1.7       pazsan   11131: 
1.78      anton    11132: As an example, consider an interface @code{storage} for
                   11133: writing objects to disk and getting them back, and a class
                   11134: @code{foo} that implements it. The code would look like this:
1.7       pazsan   11135: 
1.78      anton    11136: @cindex @code{interface} usage
                   11137: @cindex @code{end-interface} usage
                   11138: @cindex @code{implementation} usage
                   11139: @example
                   11140: interface
                   11141:   selector write ( file object -- )
                   11142:   selector read1 ( file object -- )
                   11143: end-interface storage
1.13      pazsan   11144: 
1.78      anton    11145: bar class
                   11146:   storage implementation
1.13      pazsan   11147: 
1.78      anton    11148: ... overrides write
                   11149: ... overrides read1
                   11150: ...
                   11151: end-class foo
                   11152: @end example
1.13      pazsan   11153: 
1.78      anton    11154: @noindent
                   11155: (I would add a word @code{read} @i{( file -- object )} that uses
                   11156: @code{read1} internally, but that's beyond the point illustrated
                   11157: here.)
1.13      pazsan   11158: 
1.78      anton    11159: Note that you cannot use @code{protected} in an interface; and
                   11160: of course you cannot define fields.
1.13      pazsan   11161: 
1.78      anton    11162: In the Neon model, all selectors are available for all classes;
                   11163: therefore it does not need interfaces. The price you pay in this model
                   11164: is slower late binding, and therefore, added complexity to avoid late
                   11165: binding.
1.13      pazsan   11166: 
1.78      anton    11167: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   11168: @subsubsection @file{objects.fs} Implementation
                   11169: @cindex @file{objects.fs} implementation
1.13      pazsan   11170: 
1.78      anton    11171: @cindex @code{object-map} discussion
                   11172: An object is a piece of memory, like one of the data structures
                   11173: described with @code{struct...end-struct}. It has a field
                   11174: @code{object-map} that points to the method map for the object's
                   11175: class.
1.13      pazsan   11176: 
1.78      anton    11177: @cindex method map
                   11178: @cindex virtual function table
                   11179: The @emph{method map}@footnote{This is Self terminology; in C++
                   11180: terminology: virtual function table.} is an array that contains the
                   11181: execution tokens (@i{xt}s) of the methods for the object's class. Each
                   11182: selector contains an offset into a method map.
1.13      pazsan   11183: 
1.78      anton    11184: @cindex @code{selector} implementation, class
                   11185: @code{selector} is a defining word that uses
                   11186: @code{CREATE} and @code{DOES>}. The body of the
                   11187: selector contains the offset; the @code{DOES>} action for a
                   11188: class selector is, basically:
1.8       pazsan   11189: 
                   11190: @example
1.78      anton    11191: ( object addr ) @@ over object-map @@ + @@ execute
1.13      pazsan   11192: @end example
                   11193: 
1.78      anton    11194: Since @code{object-map} is the first field of the object, it
                   11195: does not generate any code. As you can see, calling a selector has a
                   11196: small, constant cost.
1.26      crook    11197: 
1.78      anton    11198: @cindex @code{current-interface} discussion
                   11199: @cindex class implementation and representation
                   11200: A class is basically a @code{struct} combined with a method
                   11201: map. During the class definition the alignment and size of the class
                   11202: are passed on the stack, just as with @code{struct}s, so
                   11203: @code{field} can also be used for defining class
                   11204: fields. However, passing more items on the stack would be
                   11205: inconvenient, so @code{class} builds a data structure in memory,
                   11206: which is accessed through the variable
                   11207: @code{current-interface}. After its definition is complete, the
                   11208: class is represented on the stack by a pointer (e.g., as parameter for
                   11209: a child class definition).
1.26      crook    11210: 
1.78      anton    11211: A new class starts off with the alignment and size of its parent,
                   11212: and a copy of the parent's method map. Defining new fields extends the
                   11213: size and alignment; likewise, defining new selectors extends the
                   11214: method map. @code{overrides} just stores a new @i{xt} in the method
                   11215: map at the offset given by the selector.
1.13      pazsan   11216: 
1.78      anton    11217: @cindex class binding, implementation
                   11218: Class binding just gets the @i{xt} at the offset given by the selector
                   11219: from the class's method map and @code{compile,}s (in the case of
                   11220: @code{[bind]}) it.
1.13      pazsan   11221: 
1.78      anton    11222: @cindex @code{this} implementation
                   11223: @cindex @code{catch} and @code{this}
                   11224: @cindex @code{this} and @code{catch}
                   11225: I implemented @code{this} as a @code{value}. At the
                   11226: start of an @code{m:...;m} method the old @code{this} is
                   11227: stored to the return stack and restored at the end; and the object on
                   11228: the TOS is stored @code{TO this}. This technique has one
                   11229: disadvantage: If the user does not leave the method via
                   11230: @code{;m}, but via @code{throw} or @code{exit},
                   11231: @code{this} is not restored (and @code{exit} may
                   11232: crash). To deal with the @code{throw} problem, I have redefined
                   11233: @code{catch} to save and restore @code{this}; the same
                   11234: should be done with any word that can catch an exception. As for
                   11235: @code{exit}, I simply forbid it (as a replacement, there is
                   11236: @code{exitm}).
1.13      pazsan   11237: 
1.78      anton    11238: @cindex @code{inst-var} implementation
                   11239: @code{inst-var} is just the same as @code{field}, with
                   11240: a different @code{DOES>} action:
1.13      pazsan   11241: @example
1.78      anton    11242: @@ this +
1.8       pazsan   11243: @end example
1.78      anton    11244: Similar for @code{inst-value}.
1.8       pazsan   11245: 
1.78      anton    11246: @cindex class scoping implementation
                   11247: Each class also has a word list that contains the words defined with
                   11248: @code{inst-var} and @code{inst-value}, and its protected
                   11249: words. It also has a pointer to its parent. @code{class} pushes
                   11250: the word lists of the class and all its ancestors onto the search order stack,
                   11251: and @code{end-class} drops them.
1.20      pazsan   11252: 
1.78      anton    11253: @cindex interface implementation
                   11254: An interface is like a class without fields, parent and protected
                   11255: words; i.e., it just has a method map. If a class implements an
                   11256: interface, its method map contains a pointer to the method map of the
                   11257: interface. The positive offsets in the map are reserved for class
                   11258: methods, therefore interface map pointers have negative
                   11259: offsets. Interfaces have offsets that are unique throughout the
                   11260: system, unlike class selectors, whose offsets are only unique for the
                   11261: classes where the selector is available (invokable).
1.20      pazsan   11262: 
1.78      anton    11263: This structure means that interface selectors have to perform one
                   11264: indirection more than class selectors to find their method. Their body
                   11265: contains the interface map pointer offset in the class method map, and
                   11266: the method offset in the interface method map. The
                   11267: @code{does>} action for an interface selector is, basically:
1.20      pazsan   11268: 
                   11269: @example
1.78      anton    11270: ( object selector-body )
                   11271: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   11272: swap object-map @@ + @@ ( object selector-body map )
                   11273: swap selector-offset @@ + @@ execute
1.20      pazsan   11274: @end example
                   11275: 
1.78      anton    11276: where @code{object-map} and @code{selector-offset} are
                   11277: first fields and generate no code.
1.20      pazsan   11278: 
1.78      anton    11279: As a concrete example, consider the following code:
1.20      pazsan   11280: 
                   11281: @example
1.78      anton    11282: interface
                   11283:   selector if1sel1
                   11284:   selector if1sel2
                   11285: end-interface if1
1.20      pazsan   11286: 
1.78      anton    11287: object class
                   11288:   if1 implementation
                   11289:   selector cl1sel1
                   11290:   cell% inst-var cl1iv1
1.20      pazsan   11291: 
1.78      anton    11292: ' m1 overrides construct
                   11293: ' m2 overrides if1sel1
                   11294: ' m3 overrides if1sel2
                   11295: ' m4 overrides cl1sel2
                   11296: end-class cl1
1.20      pazsan   11297: 
1.78      anton    11298: create obj1 object dict-new drop
                   11299: create obj2 cl1    dict-new drop
                   11300: @end example
1.20      pazsan   11301: 
1.78      anton    11302: The data structure created by this code (including the data structure
                   11303: for @code{object}) is shown in the
                   11304: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
                   11305: @comment TODO add this diagram..
1.20      pazsan   11306: 
1.78      anton    11307: @node Objects Glossary,  , Objects Implementation, Objects
                   11308: @subsubsection @file{objects.fs} Glossary
                   11309: @cindex @file{objects.fs} Glossary
1.20      pazsan   11310: 
                   11311: 
1.78      anton    11312: doc---objects-bind
                   11313: doc---objects-<bind>
                   11314: doc---objects-bind'
                   11315: doc---objects-[bind]
                   11316: doc---objects-class
                   11317: doc---objects-class->map
                   11318: doc---objects-class-inst-size
                   11319: doc---objects-class-override!
1.79      anton    11320: doc---objects-class-previous
                   11321: doc---objects-class>order
1.78      anton    11322: doc---objects-construct
                   11323: doc---objects-current'
                   11324: doc---objects-[current]
                   11325: doc---objects-current-interface
                   11326: doc---objects-dict-new
                   11327: doc---objects-end-class
                   11328: doc---objects-end-class-noname
                   11329: doc---objects-end-interface
                   11330: doc---objects-end-interface-noname
                   11331: doc---objects-end-methods
                   11332: doc---objects-exitm
                   11333: doc---objects-heap-new
                   11334: doc---objects-implementation
                   11335: doc---objects-init-object
                   11336: doc---objects-inst-value
                   11337: doc---objects-inst-var
                   11338: doc---objects-interface
                   11339: doc---objects-m:
                   11340: doc---objects-:m
                   11341: doc---objects-;m
                   11342: doc---objects-method
                   11343: doc---objects-methods
                   11344: doc---objects-object
                   11345: doc---objects-overrides
                   11346: doc---objects-[parent]
                   11347: doc---objects-print
                   11348: doc---objects-protected
                   11349: doc---objects-public
                   11350: doc---objects-selector
                   11351: doc---objects-this
                   11352: doc---objects-<to-inst>
                   11353: doc---objects-[to-inst]
                   11354: doc---objects-to-this
                   11355: doc---objects-xt-new
1.20      pazsan   11356: 
                   11357: 
1.78      anton    11358: @c -------------------------------------------------------------
                   11359: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   11360: @subsection The @file{oof.fs} model
                   11361: @cindex oof
                   11362: @cindex object-oriented programming
1.20      pazsan   11363: 
1.78      anton    11364: @cindex @file{objects.fs}
                   11365: @cindex @file{oof.fs}
1.20      pazsan   11366: 
1.78      anton    11367: This section describes the @file{oof.fs} package.
1.20      pazsan   11368: 
1.78      anton    11369: The package described in this section has been used in bigFORTH since 1991, and
                   11370: used for two large applications: a chromatographic system used to
                   11371: create new medicaments, and a graphic user interface library (MINOS).
1.20      pazsan   11372: 
1.78      anton    11373: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   11374: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   11375: 10(2), 1994.
1.20      pazsan   11376: 
1.78      anton    11377: @menu
                   11378: * Properties of the OOF model::  
                   11379: * Basic OOF Usage::             
                   11380: * The OOF base class::          
                   11381: * Class Declaration::           
                   11382: * Class Implementation::        
                   11383: @end menu
1.20      pazsan   11384: 
1.78      anton    11385: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   11386: @subsubsection Properties of the @file{oof.fs} model
                   11387: @cindex @file{oof.fs} properties
1.20      pazsan   11388: 
1.78      anton    11389: @itemize @bullet
                   11390: @item
                   11391: This model combines object oriented programming with information
                   11392: hiding. It helps you writing large application, where scoping is
                   11393: necessary, because it provides class-oriented scoping.
1.20      pazsan   11394: 
1.78      anton    11395: @item
                   11396: Named objects, object pointers, and object arrays can be created,
                   11397: selector invocation uses the ``object selector'' syntax. Selector invocation
                   11398: to objects and/or selectors on the stack is a bit less convenient, but
                   11399: possible.
1.44      crook    11400: 
1.78      anton    11401: @item
                   11402: Selector invocation and instance variable usage of the active object is
                   11403: straightforward, since both make use of the active object.
1.44      crook    11404: 
1.78      anton    11405: @item
                   11406: Late binding is efficient and easy to use.
1.20      pazsan   11407: 
1.78      anton    11408: @item
                   11409: State-smart objects parse selectors. However, extensibility is provided
                   11410: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20      pazsan   11411: 
1.78      anton    11412: @item
                   11413: An implementation in ANS Forth is available.
1.20      pazsan   11414: 
1.78      anton    11415: @end itemize
1.23      crook    11416: 
                   11417: 
1.78      anton    11418: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   11419: @subsubsection Basic @file{oof.fs} Usage
                   11420: @cindex @file{oof.fs} usage
1.23      crook    11421: 
1.78      anton    11422: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23      crook    11423: 
1.78      anton    11424: You can define a class for graphical objects like this:
1.23      crook    11425: 
1.78      anton    11426: @cindex @code{class} usage
                   11427: @cindex @code{class;} usage
                   11428: @cindex @code{method} usage
                   11429: @example
                   11430: object class graphical \ "object" is the parent class
1.139     pazsan   11431:   method draw ( x y -- )
1.78      anton    11432: class;
                   11433: @end example
1.23      crook    11434: 
1.78      anton    11435: This code defines a class @code{graphical} with an
                   11436: operation @code{draw}.  We can perform the operation
                   11437: @code{draw} on any @code{graphical} object, e.g.:
1.23      crook    11438: 
1.78      anton    11439: @example
                   11440: 100 100 t-rex draw
                   11441: @end example
1.23      crook    11442: 
1.78      anton    11443: @noindent
                   11444: where @code{t-rex} is an object or object pointer, created with e.g.
                   11445: @code{graphical : t-rex}.
1.23      crook    11446: 
1.78      anton    11447: @cindex abstract class
                   11448: How do we create a graphical object? With the present definitions,
                   11449: we cannot create a useful graphical object. The class
                   11450: @code{graphical} describes graphical objects in general, but not
                   11451: any concrete graphical object type (C++ users would call it an
                   11452: @emph{abstract class}); e.g., there is no method for the selector
                   11453: @code{draw} in the class @code{graphical}.
1.23      crook    11454: 
1.78      anton    11455: For concrete graphical objects, we define child classes of the
                   11456: class @code{graphical}, e.g.:
1.23      crook    11457: 
1.78      anton    11458: @example
                   11459: graphical class circle \ "graphical" is the parent class
                   11460:   cell var circle-radius
                   11461: how:
                   11462:   : draw ( x y -- )
                   11463:     circle-radius @@ draw-circle ;
1.23      crook    11464: 
1.139     pazsan   11465:   : init ( n-radius -- )
1.78      anton    11466:     circle-radius ! ;
                   11467: class;
                   11468: @end example
1.1       anton    11469: 
1.78      anton    11470: Here we define a class @code{circle} as a child of @code{graphical},
                   11471: with a field @code{circle-radius}; it defines new methods for the
                   11472: selectors @code{draw} and @code{init} (@code{init} is defined in
                   11473: @code{object}, the parent class of @code{graphical}).
1.1       anton    11474: 
1.78      anton    11475: Now we can create a circle in the dictionary with:
1.1       anton    11476: 
1.78      anton    11477: @example
                   11478: 50 circle : my-circle
                   11479: @end example
1.21      crook    11480: 
1.78      anton    11481: @noindent
                   11482: @code{:} invokes @code{init}, thus initializing the field
                   11483: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   11484: with:
1.1       anton    11485: 
1.78      anton    11486: @example
                   11487: 100 100 my-circle draw
                   11488: @end example
1.1       anton    11489: 
1.78      anton    11490: @cindex selector invocation, restrictions
                   11491: @cindex class definition, restrictions
                   11492: Note: You can only invoke a selector if the receiving object belongs to
                   11493: the class where the selector was defined or one of its descendents;
                   11494: e.g., you can invoke @code{draw} only for objects belonging to
                   11495: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   11496: mechanism will check if you try to invoke a selector that is not
                   11497: defined in this class hierarchy, so you'll get an error at compilation
                   11498: time.
1.1       anton    11499: 
                   11500: 
1.78      anton    11501: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   11502: @subsubsection The @file{oof.fs} base class
                   11503: @cindex @file{oof.fs} base class
1.1       anton    11504: 
1.78      anton    11505: When you define a class, you have to specify a parent class.  So how do
                   11506: you start defining classes? There is one class available from the start:
                   11507: @code{object}. You have to use it as ancestor for all classes. It is the
                   11508: only class that has no parent. Classes are also objects, except that
                   11509: they don't have instance variables; class manipulation such as
                   11510: inheritance or changing definitions of a class is handled through
                   11511: selectors of the class @code{object}.
1.1       anton    11512: 
1.78      anton    11513: @code{object} provides a number of selectors:
1.1       anton    11514: 
1.78      anton    11515: @itemize @bullet
                   11516: @item
                   11517: @code{class} for subclassing, @code{definitions} to add definitions
                   11518: later on, and @code{class?} to get type informations (is the class a
                   11519: subclass of the class passed on the stack?).
1.1       anton    11520: 
1.78      anton    11521: doc---object-class
                   11522: doc---object-definitions
                   11523: doc---object-class?
1.1       anton    11524: 
                   11525: 
1.26      crook    11526: @item
1.78      anton    11527: @code{init} and @code{dispose} as constructor and destructor of the
                   11528: object. @code{init} is invocated after the object's memory is allocated,
                   11529: while @code{dispose} also handles deallocation. Thus if you redefine
                   11530: @code{dispose}, you have to call the parent's dispose with @code{super
                   11531: dispose}, too.
                   11532: 
                   11533: doc---object-init
                   11534: doc---object-dispose
                   11535: 
1.1       anton    11536: 
1.26      crook    11537: @item
1.78      anton    11538: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   11539: @code{[]} to create named and unnamed objects and object arrays or
                   11540: object pointers.
                   11541: 
                   11542: doc---object-new
                   11543: doc---object-new[]
                   11544: doc---object-:
                   11545: doc---object-ptr
                   11546: doc---object-asptr
                   11547: doc---object-[]
                   11548: 
1.1       anton    11549: 
1.26      crook    11550: @item
1.78      anton    11551: @code{::} and @code{super} for explicit scoping. You should use explicit
                   11552: scoping only for super classes or classes with the same set of instance
                   11553: variables. Explicitly-scoped selectors use early binding.
1.21      crook    11554: 
1.78      anton    11555: doc---object-::
                   11556: doc---object-super
1.21      crook    11557: 
                   11558: 
1.26      crook    11559: @item
1.78      anton    11560: @code{self} to get the address of the object
1.21      crook    11561: 
1.78      anton    11562: doc---object-self
1.21      crook    11563: 
                   11564: 
1.78      anton    11565: @item
                   11566: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   11567: pointers and instance defers.
1.21      crook    11568: 
1.78      anton    11569: doc---object-bind
                   11570: doc---object-bound
                   11571: doc---object-link
                   11572: doc---object-is
1.21      crook    11573: 
                   11574: 
1.78      anton    11575: @item
                   11576: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   11577: form the stack, and @code{postpone} to generate selector invocation code.
1.21      crook    11578: 
1.78      anton    11579: doc---object-'
                   11580: doc---object-postpone
1.21      crook    11581: 
                   11582: 
1.78      anton    11583: @item
                   11584: @code{with} and @code{endwith} to select the active object from the
                   11585: stack, and enable its scope. Using @code{with} and @code{endwith}
                   11586: also allows you to create code using selector @code{postpone} without being
                   11587: trapped by the state-smart objects.
1.21      crook    11588: 
1.78      anton    11589: doc---object-with
                   11590: doc---object-endwith
1.21      crook    11591: 
                   11592: 
1.78      anton    11593: @end itemize
1.21      crook    11594: 
1.78      anton    11595: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   11596: @subsubsection Class Declaration
                   11597: @cindex class declaration
1.21      crook    11598: 
1.78      anton    11599: @itemize @bullet
                   11600: @item
                   11601: Instance variables
1.21      crook    11602: 
1.78      anton    11603: doc---oof-var
1.21      crook    11604: 
                   11605: 
1.78      anton    11606: @item
                   11607: Object pointers
1.21      crook    11608: 
1.78      anton    11609: doc---oof-ptr
                   11610: doc---oof-asptr
1.21      crook    11611: 
                   11612: 
1.78      anton    11613: @item
                   11614: Instance defers
1.21      crook    11615: 
1.78      anton    11616: doc---oof-defer
1.21      crook    11617: 
                   11618: 
1.78      anton    11619: @item
                   11620: Method selectors
1.21      crook    11621: 
1.78      anton    11622: doc---oof-early
                   11623: doc---oof-method
1.21      crook    11624: 
                   11625: 
1.78      anton    11626: @item
                   11627: Class-wide variables
1.21      crook    11628: 
1.78      anton    11629: doc---oof-static
1.21      crook    11630: 
                   11631: 
1.78      anton    11632: @item
                   11633: End declaration
1.1       anton    11634: 
1.78      anton    11635: doc---oof-how:
                   11636: doc---oof-class;
1.21      crook    11637: 
                   11638: 
1.78      anton    11639: @end itemize
1.21      crook    11640: 
1.78      anton    11641: @c -------------------------------------------------------------
                   11642: @node Class Implementation,  , Class Declaration, OOF
                   11643: @subsubsection Class Implementation
                   11644: @cindex class implementation
1.21      crook    11645: 
1.78      anton    11646: @c -------------------------------------------------------------
                   11647: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   11648: @subsection The @file{mini-oof.fs} model
                   11649: @cindex mini-oof
1.21      crook    11650: 
1.78      anton    11651: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79      anton    11652: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78      anton    11653: and reduces to the bare minimum of features. This is based on a posting
                   11654: of Bernd Paysan in comp.lang.forth.
1.21      crook    11655: 
1.78      anton    11656: @menu
                   11657: * Basic Mini-OOF Usage::        
                   11658: * Mini-OOF Example::            
                   11659: * Mini-OOF Implementation::     
                   11660: @end menu
1.21      crook    11661: 
1.78      anton    11662: @c -------------------------------------------------------------
                   11663: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
                   11664: @subsubsection Basic @file{mini-oof.fs} Usage
                   11665: @cindex mini-oof usage
1.21      crook    11666: 
1.78      anton    11667: There is a base class (@code{class}, which allocates one cell for the
                   11668: object pointer) plus seven other words: to define a method, a variable,
                   11669: a class; to end a class, to resolve binding, to allocate an object and
                   11670: to compile a class method.
                   11671: @comment TODO better description of the last one
1.26      crook    11672: 
1.21      crook    11673: 
1.78      anton    11674: doc-object
                   11675: doc-method
                   11676: doc-var
                   11677: doc-class
                   11678: doc-end-class
                   11679: doc-defines
                   11680: doc-new
                   11681: doc-::
1.21      crook    11682: 
                   11683: 
                   11684: 
1.78      anton    11685: @c -------------------------------------------------------------
                   11686: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   11687: @subsubsection Mini-OOF Example
                   11688: @cindex mini-oof example
1.1       anton    11689: 
1.78      anton    11690: A short example shows how to use this package. This example, in slightly
                   11691: extended form, is supplied as @file{moof-exm.fs}
                   11692: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20      pazsan   11693: 
1.26      crook    11694: @example
1.78      anton    11695: object class
                   11696:   method init
                   11697:   method draw
                   11698: end-class graphical
1.26      crook    11699: @end example
1.20      pazsan   11700: 
1.78      anton    11701: This code defines a class @code{graphical} with an
                   11702: operation @code{draw}.  We can perform the operation
                   11703: @code{draw} on any @code{graphical} object, e.g.:
1.20      pazsan   11704: 
1.26      crook    11705: @example
1.78      anton    11706: 100 100 t-rex draw
1.26      crook    11707: @end example
1.12      anton    11708: 
1.78      anton    11709: where @code{t-rex} is an object or object pointer, created with e.g.
                   11710: @code{graphical new Constant t-rex}.
1.12      anton    11711: 
1.78      anton    11712: For concrete graphical objects, we define child classes of the
                   11713: class @code{graphical}, e.g.:
1.12      anton    11714: 
1.26      crook    11715: @example
                   11716: graphical class
1.78      anton    11717:   cell var circle-radius
                   11718: end-class circle \ "graphical" is the parent class
1.12      anton    11719: 
1.78      anton    11720: :noname ( x y -- )
                   11721:   circle-radius @@ draw-circle ; circle defines draw
                   11722: :noname ( r -- )
                   11723:   circle-radius ! ; circle defines init
                   11724: @end example
1.12      anton    11725: 
1.78      anton    11726: There is no implicit init method, so we have to define one. The creation
                   11727: code of the object now has to call init explicitely.
1.21      crook    11728: 
1.78      anton    11729: @example
                   11730: circle new Constant my-circle
                   11731: 50 my-circle init
1.12      anton    11732: @end example
                   11733: 
1.78      anton    11734: It is also possible to add a function to create named objects with
                   11735: automatic call of @code{init}, given that all objects have @code{init}
                   11736: on the same place:
1.38      anton    11737: 
1.78      anton    11738: @example
                   11739: : new: ( .. o "name" -- )
                   11740:     new dup Constant init ;
                   11741: 80 circle new: large-circle
                   11742: @end example
1.12      anton    11743: 
1.78      anton    11744: We can draw this new circle at (100,100) with:
1.12      anton    11745: 
1.78      anton    11746: @example
                   11747: 100 100 my-circle draw
                   11748: @end example
1.12      anton    11749: 
1.78      anton    11750: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
                   11751: @subsubsection @file{mini-oof.fs} Implementation
1.12      anton    11752: 
1.78      anton    11753: Object-oriented systems with late binding typically use a
                   11754: ``vtable''-approach: the first variable in each object is a pointer to a
                   11755: table, which contains the methods as function pointers. The vtable
                   11756: may also contain other information.
1.12      anton    11757: 
1.79      anton    11758: So first, let's declare selectors:
1.37      anton    11759: 
                   11760: @example
1.79      anton    11761: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
1.78      anton    11762:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
                   11763: @end example
1.37      anton    11764: 
1.79      anton    11765: During selector declaration, the number of selectors and instance
                   11766: variables is on the stack (in address units). @code{method} creates one
                   11767: selector and increments the selector number. To execute a selector, it
1.78      anton    11768: takes the object, fetches the vtable pointer, adds the offset, and
1.79      anton    11769: executes the method @i{xt} stored there. Each selector takes the object
                   11770: it is invoked with as top of stack parameter; it passes the parameters
                   11771: (including the object) unchanged to the appropriate method which should
1.78      anton    11772: consume that object.
1.37      anton    11773: 
1.78      anton    11774: Now, we also have to declare instance variables
1.37      anton    11775: 
1.78      anton    11776: @example
1.79      anton    11777: : var ( m v size "name" -- m v' ) Create  over , +
1.78      anton    11778:   DOES> ( o -- addr ) @@ + ;
1.37      anton    11779: @end example
                   11780: 
1.78      anton    11781: As before, a word is created with the current offset. Instance
                   11782: variables can have different sizes (cells, floats, doubles, chars), so
                   11783: all we do is take the size and add it to the offset. If your machine
                   11784: has alignment restrictions, put the proper @code{aligned} or
                   11785: @code{faligned} before the variable, to adjust the variable
                   11786: offset. That's why it is on the top of stack.
1.37      anton    11787: 
1.78      anton    11788: We need a starting point (the base object) and some syntactic sugar:
1.37      anton    11789: 
1.78      anton    11790: @example
                   11791: Create object  1 cells , 2 cells ,
1.79      anton    11792: : class ( class -- class selectors vars ) dup 2@@ ;
1.78      anton    11793: @end example
1.12      anton    11794: 
1.78      anton    11795: For inheritance, the vtable of the parent object has to be
                   11796: copied when a new, derived class is declared. This gives all the
                   11797: methods of the parent class, which can be overridden, though.
1.12      anton    11798: 
1.78      anton    11799: @example
1.79      anton    11800: : end-class  ( class selectors vars "name" -- )
1.78      anton    11801:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   11802:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
                   11803: @end example
1.12      anton    11804: 
1.78      anton    11805: The first line creates the vtable, initialized with
                   11806: @code{noop}s. The second line is the inheritance mechanism, it
                   11807: copies the xts from the parent vtable.
1.12      anton    11808: 
1.78      anton    11809: We still have no way to define new methods, let's do that now:
1.12      anton    11810: 
1.26      crook    11811: @example
1.79      anton    11812: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78      anton    11813: @end example
1.12      anton    11814: 
1.78      anton    11815: To allocate a new object, we need a word, too:
1.12      anton    11816: 
1.78      anton    11817: @example
                   11818: : new ( class -- o )  here over @@ allot swap over ! ;
1.12      anton    11819: @end example
                   11820: 
1.78      anton    11821: Sometimes derived classes want to access the method of the
                   11822: parent object. There are two ways to achieve this with Mini-OOF:
                   11823: first, you could use named words, and second, you could look up the
                   11824: vtable of the parent object.
1.12      anton    11825: 
1.78      anton    11826: @example
                   11827: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
                   11828: @end example
1.12      anton    11829: 
                   11830: 
1.78      anton    11831: Nothing can be more confusing than a good example, so here is
                   11832: one. First let's declare a text object (called
                   11833: @code{button}), that stores text and position:
1.12      anton    11834: 
1.78      anton    11835: @example
                   11836: object class
                   11837:   cell var text
                   11838:   cell var len
                   11839:   cell var x
                   11840:   cell var y
                   11841:   method init
                   11842:   method draw
                   11843: end-class button
                   11844: @end example
1.12      anton    11845: 
1.78      anton    11846: @noindent
                   11847: Now, implement the two methods, @code{draw} and @code{init}:
1.21      crook    11848: 
1.26      crook    11849: @example
1.78      anton    11850: :noname ( o -- )
                   11851:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
                   11852:  button defines draw
                   11853: :noname ( addr u o -- )
                   11854:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
                   11855:  button defines init
1.26      crook    11856: @end example
1.12      anton    11857: 
1.78      anton    11858: @noindent
                   11859: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79      anton    11860: new data and no new selectors:
1.78      anton    11861: 
                   11862: @example
                   11863: button class
                   11864: end-class bold-button
1.12      anton    11865: 
1.78      anton    11866: : bold   27 emit ." [1m" ;
                   11867: : normal 27 emit ." [0m" ;
                   11868: @end example
1.1       anton    11869: 
1.78      anton    11870: @noindent
                   11871: The class @code{bold-button} has a different draw method to
                   11872: @code{button}, but the new method is defined in terms of the draw method
                   11873: for @code{button}:
1.20      pazsan   11874: 
1.78      anton    11875: @example
                   11876: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   11877: @end example
1.21      crook    11878: 
1.78      anton    11879: @noindent
1.79      anton    11880: Finally, create two objects and apply selectors:
1.21      crook    11881: 
1.26      crook    11882: @example
1.78      anton    11883: button new Constant foo
                   11884: s" thin foo" foo init
                   11885: page
                   11886: foo draw
                   11887: bold-button new Constant bar
                   11888: s" fat bar" bar init
                   11889: 1 bar y !
                   11890: bar draw
1.26      crook    11891: @end example
1.21      crook    11892: 
                   11893: 
1.78      anton    11894: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   11895: @subsection Comparison with other object models
                   11896: @cindex comparison of object models
                   11897: @cindex object models, comparison
                   11898: 
                   11899: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   11900: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   11901: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   11902: relation of the object models described here to two well-known and two
                   11903: closely-related (by the use of method maps) models.  Andras Zsoter
                   11904: helped us with this section.
                   11905: 
                   11906: @cindex Neon model
                   11907: The most popular model currently seems to be the Neon model (see
                   11908: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   11909: 1997) by Andrew McKewan) but this model has a number of limitations
                   11910: @footnote{A longer version of this critique can be
                   11911: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   11912: Dimensions, May 1997) by Anton Ertl.}:
                   11913: 
                   11914: @itemize @bullet
                   11915: @item
                   11916: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11917: to pass objects on the stack.
1.21      crook    11918: 
1.78      anton    11919: @item
                   11920: It requires that the selector parses the input stream (at
1.79      anton    11921: compile time); this leads to reduced extensibility and to bugs that are
1.78      anton    11922: hard to find.
1.21      crook    11923: 
1.78      anton    11924: @item
1.79      anton    11925: It allows using every selector on every object; this eliminates the
                   11926: need for interfaces, but makes it harder to create efficient
                   11927: implementations.
1.78      anton    11928: @end itemize
1.21      crook    11929: 
1.78      anton    11930: @cindex Pountain's object-oriented model
                   11931: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11932: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11933: object-oriented programming, because it hardly deals with late
                   11934: binding. Instead, it focuses on features like information hiding and
                   11935: overloading that are characteristic of modular languages like Ada (83).
1.26      crook    11936: 
1.78      anton    11937: @cindex Zsoter's object-oriented model
1.79      anton    11938: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
                   11939: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
                   11940: describes a model that makes heavy use of an active object (like
                   11941: @code{this} in @file{objects.fs}): The active object is not only used
                   11942: for accessing all fields, but also specifies the receiving object of
                   11943: every selector invocation; you have to change the active object
                   11944: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   11945: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   11946: the method entry point is unnecessary with Zsoter's model, because the
                   11947: receiving object is the active object already. On the other hand, the
                   11948: explicit change is absolutely necessary in that model, because otherwise
                   11949: no one could ever change the active object. An ANS Forth implementation
                   11950: of this model is available through
                   11951: @uref{http://www.forth.org/oopf.html}.
1.21      crook    11952: 
1.78      anton    11953: @cindex @file{oof.fs}, differences to other models
                   11954: The @file{oof.fs} model combines information hiding and overloading
                   11955: resolution (by keeping names in various word lists) with object-oriented
                   11956: programming. It sets the active object implicitly on method entry, but
                   11957: also allows explicit changing (with @code{>o...o>} or with
                   11958: @code{with...endwith}). It uses parsing and state-smart objects and
                   11959: classes for resolving overloading and for early binding: the object or
                   11960: class parses the selector and determines the method from this. If the
                   11961: selector is not parsed by an object or class, it performs a call to the
                   11962: selector for the active object (late binding), like Zsoter's model.
                   11963: Fields are always accessed through the active object. The big
                   11964: disadvantage of this model is the parsing and the state-smartness, which
                   11965: reduces extensibility and increases the opportunities for subtle bugs;
                   11966: essentially, you are only safe if you never tick or @code{postpone} an
                   11967: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21      crook    11968: 
1.78      anton    11969: @cindex @file{mini-oof.fs}, differences to other models
                   11970: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11971: version of the @file{objects.fs} model, but syntactically it is a
                   11972: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21      crook    11973: 
                   11974: 
1.78      anton    11975: @c -------------------------------------------------------------
1.150     anton    11976: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78      anton    11977: @section Programming Tools
                   11978: @cindex programming tools
1.21      crook    11979: 
1.78      anton    11980: @c !! move this and assembler down below OO stuff.
1.21      crook    11981: 
1.78      anton    11982: @menu
1.150     anton    11983: * Examining::                   Data and Code.
                   11984: * Forgetting words::            Usually before reloading.
1.78      anton    11985: * Debugging::                   Simple and quick.
                   11986: * Assertions::                  Making your programs self-checking.
                   11987: * Singlestep Debugger::         Executing your program word by word.
                   11988: @end menu
1.21      crook    11989: 
1.78      anton    11990: @node Examining, Forgetting words, Programming Tools, Programming Tools
                   11991: @subsection Examining data and code
                   11992: @cindex examining data and code
                   11993: @cindex data examination
                   11994: @cindex code examination
1.44      crook    11995: 
1.78      anton    11996: The following words inspect the stack non-destructively:
1.21      crook    11997: 
1.78      anton    11998: doc-.s
                   11999: doc-f.s
1.158     anton    12000: doc-maxdepth-.s
1.44      crook    12001: 
1.78      anton    12002: There is a word @code{.r} but it does @i{not} display the return stack!
                   12003: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21      crook    12004: 
1.78      anton    12005: doc-depth
                   12006: doc-fdepth
                   12007: doc-clearstack
1.124     anton    12008: doc-clearstacks
1.21      crook    12009: 
1.78      anton    12010: The following words inspect memory.
1.21      crook    12011: 
1.78      anton    12012: doc-?
                   12013: doc-dump
1.21      crook    12014: 
1.78      anton    12015: And finally, @code{see} allows to inspect code:
1.21      crook    12016: 
1.78      anton    12017: doc-see
                   12018: doc-xt-see
1.111     anton    12019: doc-simple-see
                   12020: doc-simple-see-range
1.182     anton    12021: doc-see-code
                   12022: doc-see-code-range
1.21      crook    12023: 
1.78      anton    12024: @node Forgetting words, Debugging, Examining, Programming Tools
                   12025: @subsection Forgetting words
                   12026: @cindex words, forgetting
                   12027: @cindex forgeting words
1.21      crook    12028: 
1.78      anton    12029: @c  anton: other, maybe better places for this subsection: Defining Words;
                   12030: @c  Dictionary allocation.  At least a reference should be there.
1.21      crook    12031: 
1.78      anton    12032: Forth allows you to forget words (and everything that was alloted in the
                   12033: dictonary after them) in a LIFO manner.
1.21      crook    12034: 
1.78      anton    12035: doc-marker
1.21      crook    12036: 
1.78      anton    12037: The most common use of this feature is during progam development: when
                   12038: you change a source file, forget all the words it defined and load it
                   12039: again (since you also forget everything defined after the source file
                   12040: was loaded, you have to reload that, too).  Note that effects like
                   12041: storing to variables and destroyed system words are not undone when you
                   12042: forget words.  With a system like Gforth, that is fast enough at
                   12043: starting up and compiling, I find it more convenient to exit and restart
                   12044: Gforth, as this gives me a clean slate.
1.21      crook    12045: 
1.78      anton    12046: Here's an example of using @code{marker} at the start of a source file
                   12047: that you are debugging; it ensures that you only ever have one copy of
                   12048: the file's definitions compiled at any time:
1.21      crook    12049: 
1.78      anton    12050: @example
                   12051: [IFDEF] my-code
                   12052:     my-code
                   12053: [ENDIF]
1.26      crook    12054: 
1.78      anton    12055: marker my-code
                   12056: init-included-files
1.21      crook    12057: 
1.78      anton    12058: \ .. definitions start here
                   12059: \ .
                   12060: \ .
                   12061: \ end
                   12062: @end example
1.21      crook    12063: 
1.26      crook    12064: 
1.78      anton    12065: @node Debugging, Assertions, Forgetting words, Programming Tools
                   12066: @subsection Debugging
                   12067: @cindex debugging
1.21      crook    12068: 
1.78      anton    12069: Languages with a slow edit/compile/link/test development loop tend to
                   12070: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21      crook    12071: 
1.78      anton    12072: A much better (faster) way in fast-compiling languages is to add
                   12073: printing code at well-selected places, let the program run, look at
                   12074: the output, see where things went wrong, add more printing code, etc.,
                   12075: until the bug is found.
1.21      crook    12076: 
1.78      anton    12077: The simple debugging aids provided in @file{debugs.fs}
                   12078: are meant to support this style of debugging.
1.21      crook    12079: 
1.78      anton    12080: The word @code{~~} prints debugging information (by default the source
                   12081: location and the stack contents). It is easy to insert. If you use Emacs
                   12082: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   12083: query-replace them with nothing). The deferred words
1.101     anton    12084: @code{printdebugdata} and @code{.debugline} control the output of
1.78      anton    12085: @code{~~}. The default source location output format works well with
                   12086: Emacs' compilation mode, so you can step through the program at the
                   12087: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   12088: is that you can step in any direction and you know where the crash has
                   12089: happened or where the strange data has occurred).
1.21      crook    12090: 
1.78      anton    12091: doc-~~
                   12092: doc-printdebugdata
1.101     anton    12093: doc-.debugline
1.203     anton    12094: doc-debug-fid
1.21      crook    12095: 
1.106     anton    12096: @cindex filenames in @code{~~} output
                   12097: @code{~~} (and assertions) will usually print the wrong file name if a
                   12098: marker is executed in the same file after their occurance.  They will
                   12099: print @samp{*somewhere*} as file name if a marker is executed in the
                   12100: same file before their occurance.
                   12101: 
                   12102: 
1.78      anton    12103: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   12104: @subsection Assertions
                   12105: @cindex assertions
1.21      crook    12106: 
1.78      anton    12107: It is a good idea to make your programs self-checking, especially if you
                   12108: make an assumption that may become invalid during maintenance (for
                   12109: example, that a certain field of a data structure is never zero). Gforth
                   12110: supports @dfn{assertions} for this purpose. They are used like this:
1.21      crook    12111: 
                   12112: @example
1.78      anton    12113: assert( @i{flag} )
1.26      crook    12114: @end example
                   12115: 
1.78      anton    12116: The code between @code{assert(} and @code{)} should compute a flag, that
                   12117: should be true if everything is alright and false otherwise. It should
                   12118: not change anything else on the stack. The overall stack effect of the
                   12119: assertion is @code{( -- )}. E.g.
1.21      crook    12120: 
1.26      crook    12121: @example
1.78      anton    12122: assert( 1 1 + 2 = ) \ what we learn in school
                   12123: assert( dup 0<> ) \ assert that the top of stack is not zero
                   12124: assert( false ) \ this code should not be reached
1.21      crook    12125: @end example
                   12126: 
1.78      anton    12127: The need for assertions is different at different times. During
                   12128: debugging, we want more checking, in production we sometimes care more
                   12129: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   12130: becomes a comment. Depending on the importance of an assertion and the
                   12131: time it takes to check it, you may want to turn off some assertions and
                   12132: keep others turned on. Gforth provides several levels of assertions for
                   12133: this purpose:
                   12134: 
                   12135: 
                   12136: doc-assert0(
                   12137: doc-assert1(
                   12138: doc-assert2(
                   12139: doc-assert3(
                   12140: doc-assert(
                   12141: doc-)
1.21      crook    12142: 
                   12143: 
1.78      anton    12144: The variable @code{assert-level} specifies the highest assertions that
                   12145: are turned on. I.e., at the default @code{assert-level} of one,
                   12146: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   12147: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26      crook    12148: 
1.78      anton    12149: The value of @code{assert-level} is evaluated at compile-time, not at
                   12150: run-time. Therefore you cannot turn assertions on or off at run-time;
                   12151: you have to set the @code{assert-level} appropriately before compiling a
                   12152: piece of code. You can compile different pieces of code at different
                   12153: @code{assert-level}s (e.g., a trusted library at level 1 and
                   12154: newly-written code at level 3).
1.26      crook    12155: 
                   12156: 
1.78      anton    12157: doc-assert-level
1.26      crook    12158: 
                   12159: 
1.78      anton    12160: If an assertion fails, a message compatible with Emacs' compilation mode
                   12161: is produced and the execution is aborted (currently with @code{ABORT"}.
                   12162: If there is interest, we will introduce a special throw code. But if you
                   12163: intend to @code{catch} a specific condition, using @code{throw} is
                   12164: probably more appropriate than an assertion).
1.106     anton    12165: 
                   12166: @cindex filenames in assertion output
                   12167: Assertions (and @code{~~}) will usually print the wrong file name if a
                   12168: marker is executed in the same file after their occurance.  They will
                   12169: print @samp{*somewhere*} as file name if a marker is executed in the
                   12170: same file before their occurance.
1.44      crook    12171: 
1.78      anton    12172: Definitions in ANS Forth for these assertion words are provided
                   12173: in @file{compat/assert.fs}.
1.26      crook    12174: 
1.44      crook    12175: 
1.78      anton    12176: @node Singlestep Debugger,  , Assertions, Programming Tools
                   12177: @subsection Singlestep Debugger
                   12178: @cindex singlestep Debugger
                   12179: @cindex debugging Singlestep
1.44      crook    12180: 
1.189     anton    12181: The singlestep debugger works only with the engine @code{gforth-itc}.
1.112     anton    12182: 
1.78      anton    12183: When you create a new word there's often the need to check whether it
                   12184: behaves correctly or not. You can do this by typing @code{dbg
                   12185: badword}. A debug session might look like this:
1.26      crook    12186: 
1.78      anton    12187: @example
                   12188: : badword 0 DO i . LOOP ;  ok
                   12189: 2 dbg badword 
                   12190: : badword  
                   12191: Scanning code...
1.44      crook    12192: 
1.78      anton    12193: Nesting debugger ready!
1.44      crook    12194: 
1.78      anton    12195: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   12196: 400D4740  8049F68 DO             -> [ 0 ] 
                   12197: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   12198: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   12199: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   12200: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   12201: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   12202: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   12203: 400D4758  804B384 ;              ->  ok
                   12204: @end example
1.21      crook    12205: 
1.78      anton    12206: Each line displayed is one step. You always have to hit return to
                   12207: execute the next word that is displayed. If you don't want to execute
                   12208: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   12209: an overview what keys are available:
1.44      crook    12210: 
1.78      anton    12211: @table @i
1.44      crook    12212: 
1.78      anton    12213: @item @key{RET}
                   12214: Next; Execute the next word.
1.21      crook    12215: 
1.78      anton    12216: @item n
                   12217: Nest; Single step through next word.
1.44      crook    12218: 
1.78      anton    12219: @item u
                   12220: Unnest; Stop debugging and execute rest of word. If we got to this word
                   12221: with nest, continue debugging with the calling word.
1.44      crook    12222: 
1.78      anton    12223: @item d
                   12224: Done; Stop debugging and execute rest.
1.21      crook    12225: 
1.78      anton    12226: @item s
                   12227: Stop; Abort immediately.
1.44      crook    12228: 
1.78      anton    12229: @end table
1.44      crook    12230: 
1.78      anton    12231: Debugging large application with this mechanism is very difficult, because
                   12232: you have to nest very deeply into the program before the interesting part
                   12233: begins. This takes a lot of time. 
1.26      crook    12234: 
1.78      anton    12235: To do it more directly put a @code{BREAK:} command into your source code.
                   12236: When program execution reaches @code{BREAK:} the single step debugger is
                   12237: invoked and you have all the features described above.
1.44      crook    12238: 
1.78      anton    12239: If you have more than one part to debug it is useful to know where the
                   12240: program has stopped at the moment. You can do this by the 
                   12241: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   12242: string is typed out when the ``breakpoint'' is reached.
1.44      crook    12243: 
1.26      crook    12244: 
1.78      anton    12245: doc-dbg
                   12246: doc-break:
                   12247: doc-break"
1.44      crook    12248: 
1.150     anton    12249: @c ------------------------------------------------------------
                   12250: @node C Interface, Assembler and Code Words, Programming Tools, Words
                   12251: @section C Interface
                   12252: @cindex C interface
                   12253: @cindex foreign language interface
                   12254: @cindex interface to C functions
                   12255: 
1.178     anton    12256: Note that the C interface is not yet complete; callbacks are missing,
                   12257: as well as a way of declaring structs, unions, and their fields.
1.150     anton    12258: 
                   12259: @menu
                   12260: * Calling C Functions::         
                   12261: * Declaring C Functions::       
1.180     anton    12262: * Calling C function pointers::  
1.196     anton    12263: * Defining library interfaces::  
                   12264: * Declaring OS-level libraries::  
1.150     anton    12265: * Callbacks::                   
1.178     anton    12266: * C interface internals::       
1.155     anton    12267: * Low-Level C Interface Words::  
1.150     anton    12268: @end menu
                   12269: 
1.151     pazsan   12270: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150     anton    12271: @subsection Calling C functions
1.155     anton    12272: @cindex C functions, calls to
                   12273: @cindex calling C functions
1.150     anton    12274: 
1.151     pazsan   12275: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150     anton    12276: can call it as follows: You push the arguments on the stack(s), and
                   12277: then call the word for the C function.  The arguments have to be
                   12278: pushed in the same order as the arguments appear in the C
                   12279: documentation (i.e., the first argument is deepest on the stack).
                   12280: Integer and pointer arguments have to be pushed on the data stack,
                   12281: floating-point arguments on the FP stack; these arguments are consumed
1.155     anton    12282: by the called C function.
1.150     anton    12283: 
1.155     anton    12284: On returning from the C function, the return value, if any, resides on
                   12285: the appropriate stack: an integer return value is pushed on the data
                   12286: stack, an FP return value on the FP stack, and a void return value
                   12287: results in not pushing anything.  Note that most C functions have a
                   12288: return value, even if that is often not used in C; in Forth, you have
                   12289: to @code{drop} this return value explicitly if you do not use it.
1.150     anton    12290: 
1.177     anton    12291: The C interface automatically converts between the C type and the
                   12292: Forth type as necessary, on a best-effort basis (in some cases, there
                   12293: may be some loss).
1.150     anton    12294: 
                   12295: As an example, consider the POSIX function @code{lseek()}:
                   12296: 
                   12297: @example
                   12298: off_t lseek(int fd, off_t offset, int whence);
                   12299: @end example
                   12300: 
                   12301: This function takes three integer arguments, and returns an integer
                   12302: argument, so a Forth call for setting the current file offset to the
                   12303: start of the file could look like this:
                   12304: 
                   12305: @example
                   12306: fd @@ 0 SEEK_SET lseek -1 = if
                   12307:   ... \ error handling
                   12308: then
                   12309: @end example
                   12310: 
                   12311: You might be worried that an @code{off_t} does not fit into a cell, so
                   12312: you could not pass larger offsets to lseek, and might get only a part
1.155     anton    12313: of the return values.  In that case, in your declaration of the
                   12314: function (@pxref{Declaring C Functions}) you should declare it to use
                   12315: double-cells for the off_t argument and return value, and maybe give
                   12316: the resulting Forth word a different name, like @code{dlseek}; the
                   12317: result could be called like this:
1.150     anton    12318: 
                   12319: @example
                   12320: fd @@ 0. SEEK_SET dlseek -1. d= if
                   12321:   ... \ error handling
                   12322: then
                   12323: @end example
                   12324: 
                   12325: Passing and returning structs or unions is currently not supported by
                   12326: our interface@footnote{If you know the calling convention of your C
                   12327: compiler, you usually can call such functions in some way, but that
                   12328: way is usually not portable between platforms, and sometimes not even
                   12329: between C compilers.}.
                   12330: 
1.177     anton    12331: Calling functions with a variable number of arguments (@emph{variadic}
                   12332: functions, e.g., @code{printf()}) is only supported by having you
                   12333: declare one function-calling word for each argument pattern, and
                   12334: calling the appropriate word for the desired pattern.
                   12335: 
1.150     anton    12336: 
1.155     anton    12337: 
1.180     anton    12338: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150     anton    12339: @subsection Declaring C Functions
1.155     anton    12340: @cindex C functions, declarations
                   12341: @cindex declaring C functions
1.150     anton    12342: 
                   12343: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177     anton    12344: it.  The declaration consists of two parts: 
                   12345: 
                   12346: @table @b
                   12347: 
                   12348: @item The C part
1.179     anton    12349: is the C declaration of the function, or more typically and portably,
                   12350: a C-style @code{#include} of a file that contains the declaration of
                   12351: the C function.
1.177     anton    12352: 
                   12353: @item The Forth part
                   12354: declares the Forth types of the parameters and the Forth word name
                   12355: corresponding to the C function.
                   12356: 
                   12357: @end table
                   12358: 
                   12359: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
                   12360: declarations are:
                   12361: 
                   12362: @example
                   12363: \c #define _FILE_OFFSET_BITS 64
                   12364: \c #include <sys/types.h>
                   12365: \c #include <unistd.h>
                   12366: c-function lseek lseek n n n -- n
                   12367: c-function dlseek lseek n d n -- d
                   12368: @end example
                   12369: 
1.178     anton    12370: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177     anton    12371: of the line is ordinary C code.  You can use as many lines of C
                   12372: declarations as you like, and they are visible for all further
                   12373: function declarations.
                   12374: 
                   12375: The Forth part declares each interface word with @code{c-function},
                   12376: followed by the Forth name of the word, the C name of the called
                   12377: function, and the stack effect of the word.  The stack effect contains
1.178     anton    12378: an arbitrary number of types of parameters, then @code{--}, and then
1.177     anton    12379: exactly one type for the return value.  The possible types are:
                   12380: 
                   12381: @table @code
                   12382: 
                   12383: @item n
                   12384: single-cell integer
                   12385: 
                   12386: @item a
                   12387: address (single-cell)
                   12388: 
                   12389: @item d
                   12390: double-cell integer
                   12391: 
                   12392: @item r
                   12393: floating-point value
                   12394: 
                   12395: @item func
                   12396: C function pointer
                   12397: 
                   12398: @item void
                   12399: no value (used as return type for void functions)
                   12400: 
                   12401: @end table
                   12402: 
                   12403: @cindex variadic C functions
                   12404: 
                   12405: To deal with variadic C functions, you can declare one Forth word for
                   12406: every pattern you want to use, e.g.:
                   12407: 
                   12408: @example
                   12409: \c #include <stdio.h>
                   12410: c-function printf-nr printf a n r -- n
                   12411: c-function printf-rn printf a r n -- n
                   12412: @end example
                   12413: 
                   12414: Note that with C functions declared as variadic (or if you don't
                   12415: provide a prototype), the C interface has no C type to convert to, so
                   12416: no automatic conversion happens, which may lead to portability
                   12417: problems in some cases.  In such cases you can perform the conversion
                   12418: explicitly on the C level, e.g., as follows:
                   12419: 
                   12420: @example
1.178     anton    12421: \c #define printfll(s,ll) printf(s,(long long)ll)
                   12422: c-function printfll printfll a n -- n
1.177     anton    12423: @end example
                   12424: 
                   12425: Here, instead of calling @code{printf()} directly, we define a macro
1.178     anton    12426: that casts (converts) the Forth single-cell integer into a
                   12427: C @code{long long} before calling @code{printf()}.
1.177     anton    12428: 
                   12429: doc-\c
                   12430: doc-c-function
1.207     pazsan   12431: doc-c-value
                   12432: doc-c-variable
1.177     anton    12433: 
                   12434: In order to work, this C interface invokes GCC at run-time and uses
1.178     anton    12435: dynamic linking.  If these features are not available, there are
                   12436: other, less convenient and less portable C interfaces in @file{lib.fs}
                   12437: and @file{oldlib.fs}.  These interfaces are mostly undocumented and
                   12438: mostly incompatible with each other and with the documented C
                   12439: interface; you can find some examples for the @file{lib.fs} interface
                   12440: in @file{lib.fs}.
1.177     anton    12441: 
                   12442: 
1.196     anton    12443: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
1.180     anton    12444: @subsection Calling C function pointers from Forth
                   12445: @cindex C function pointers, calling from Forth
1.177     anton    12446: 
1.180     anton    12447: If you come across a C function pointer (e.g., in some C-constructed
                   12448: structure) and want to call it from your Forth program, you can also
                   12449: use the features explained until now to achieve that, as follows:
1.150     anton    12450: 
1.180     anton    12451: Let us assume that there is a C function pointer type @code{func1}
                   12452: defined in some header file @file{func1.h}, and you know that these
                   12453: functions take one integer argument and return an integer result; and
                   12454: you want to call functions through such pointers.  Just define
1.155     anton    12455: 
1.180     anton    12456: @example
                   12457: \c #include <func1.h>
                   12458: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
                   12459: c-function call-func1 call_func1 n func -- n
                   12460: @end example
                   12461: 
                   12462: and then you can call a function pointed to by, say @code{func1a} as
                   12463: follows:
                   12464: 
                   12465: @example
                   12466: -5 func1a call-func1 .
                   12467: @end example
                   12468: 
                   12469: In the C part, @code{call_func} is defined as a macro to avoid having
                   12470: to declare the exact parameter and return types, so the C compiler
                   12471: knows them from the declaration of @code{func1}.
                   12472: 
                   12473: The Forth word @code{call-func1} is similar to @code{execute}, except
                   12474: that it takes a C @code{func1} pointer instead of a Forth execution
                   12475: token, and it is specific to @code{func1} pointers.  For each type of
                   12476: function pointer you want to call from Forth, you have to define
                   12477: a separate calling word.
                   12478: 
                   12479: 
1.196     anton    12480: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
                   12481: @subsection Defining library interfaces
                   12482: @cindex giving a name to a library interface
                   12483: @cindex library interface names
                   12484: 
                   12485: You can give a name to a bunch of C function declarations (a library
                   12486: interface), as follows:
                   12487: 
                   12488: @example
                   12489: c-library lseek-lib
                   12490: \c #define _FILE_OFFSET_BITS 64
                   12491: ...
                   12492: end-c-library
                   12493: @end example
                   12494: 
1.202     anton    12495: The effect of giving such a name to the interface is that the names of
                   12496: the generated files will contain that name, and when you use the
                   12497: interface a second time, it will use the existing files instead of
                   12498: generating and compiling them again, saving you time.  Note that even
                   12499: if you change the declarations, the old (stale) files will be used,
                   12500: probably leading to errors.  So, during development of the
                   12501: declarations we recommend not using @code{c-library}.  Normally these
                   12502: files are cached in @file{$HOME/.gforth/libcc-named}, so by deleting
                   12503: that directory you can get rid of stale files.
                   12504: 
                   12505: Note that you should use @code{c-library} before everything else
                   12506: having anything to do with that library, as it resets some setup
                   12507: stuff.  The idea is that the typical use is to put each
                   12508: @code{c-library}...@code{end-library} unit in its own file, and to be
                   12509: able to include these files in any order.
1.196     anton    12510: 
                   12511: Note that the library name is not allocated in the dictionary and
                   12512: therefore does not shadow dictionary names.  It is used in the file
                   12513: system, so you have to use naming conventions appropriate for file
                   12514: systems.  Also, you must not call a function you declare after
                   12515: @code{c-library} before you perform @code{end-c-library}.
                   12516: 
                   12517: A major benefit of these named library interfaces is that, once they
                   12518: are generated, the tools used to generated them (in particular, the C
                   12519: compiler and libtool) are no longer needed, so the interface can be
                   12520: used even on machines that do not have the tools installed.
                   12521: 
                   12522: doc-c-library-name
                   12523: doc-c-library
                   12524: doc-end-c-library
                   12525: 
                   12526: 
                   12527: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
                   12528: @subsection Declaring OS-level libraries
1.195     anton    12529: @cindex Shared libraries in C interface
                   12530: @cindex Dynamically linked libraries in C interface
                   12531: @cindex Libraries in C interface
                   12532: 
1.196     anton    12533: For calling some C functions, you need to link with a specific
                   12534: OS-level library that contains that function.  E.g., the @code{sin}
                   12535: function requires linking a special library by using the command line
                   12536: switch @code{-lm}.  In our C iterface you do the equivalent thing by
                   12537: calling @code{add-lib} as follows:
1.195     anton    12538: 
                   12539: @example
                   12540: clear-libs
                   12541: s" m" add-lib
                   12542: \c #include <math.h>
                   12543: c-function sin sin r -- r
                   12544: @end example
                   12545: 
                   12546: First, you clear any libraries that may have been declared earlier
                   12547: (you don't need them for @code{sin}); then you add the @code{m}
                   12548: library (actually @code{libm.so} or somesuch) to the currently
                   12549: declared libraries; you can add as many as you need.  Finally you
                   12550: declare the function as shown above.  Typically you will use the same
                   12551: set of library declarations for many function declarations; you need
                   12552: to write only one set for that, right at the beginning.
                   12553: 
1.196     anton    12554: Note that you must not call @code{clear-libs} inside
                   12555: @code{c-library...end-c-library}; however, @code{c-library} performs
                   12556: the function of @code{clear-libs}, so @code{clear-libs} is not
                   12557: necessary, and you usually want to put @code{add-lib} calls inside
                   12558: @code{c-library...end-c-library}.
                   12559: 
1.195     anton    12560: doc-clear-libs
                   12561: doc-add-lib
                   12562: 
                   12563: 
1.196     anton    12564: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
1.150     anton    12565: @subsection Callbacks
1.155     anton    12566: @cindex Callback functions written in Forth
                   12567: @cindex C function pointers to Forth words
                   12568: 
1.177     anton    12569: Callbacks are not yet supported by the documented C interface.  You
                   12570: can use the undocumented @file{lib.fs} interface for callbacks.
                   12571: 
1.155     anton    12572: In some cases you have to pass a function pointer to a C function,
                   12573: i.e., the library wants to call back to your application (and the
                   12574: pointed-to function is called a callback function).  You can pass the
                   12575: address of an existing C function (that you get with @code{lib-sym},
                   12576: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
                   12577: function, you probably want to define the function as a Forth word.
                   12578: 
                   12579: @c I don't understand the existing callback interface from the example - anton
                   12580: 
1.165     anton    12581: 
                   12582: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
                   12583: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
                   12584: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
                   12585: @c > > C-Funktionsadresse auf dem TOS).
                   12586: @c >
                   12587: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
                   12588: @c > gesehen habe, wozu das gut ist.
                   12589: @c 
                   12590: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch 
                   12591: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen 
                   12592: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit 
                   12593: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte 
                   12594: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit 
                   12595: @c demselben Prototyp.
                   12596: 
                   12597: 
1.178     anton    12598: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177     anton    12599: @subsection How the C interface works
                   12600: 
                   12601: The documented C interface works by generating a C code out of the
                   12602: declarations.
                   12603: 
                   12604: In particular, for every Forth word declared with @code{c-function},
                   12605: it generates a wrapper function in C that takes the Forth data from
                   12606: the Forth stacks, and calls the target C function with these data as
                   12607: arguments.  The C compiler then performs an implicit conversion
                   12608: between the Forth type from the stack, and the C type for the
                   12609: parameter, which is given by the C function prototype.  After the C
                   12610: function returns, the return value is likewise implicitly converted to
                   12611: a Forth type and written back on the stack.
                   12612: 
                   12613: The @code{\c} lines are literally included in the C code (but without
                   12614: the @code{\c}), and provide the necessary declarations so that the C
                   12615: compiler knows the C types and has enough information to perform the
                   12616: conversion.
                   12617: 
                   12618: These wrapper functions are eventually compiled and dynamically linked
                   12619: into Gforth, and then they can be called.
                   12620: 
1.195     anton    12621: The libraries added with @code{add-lib} are used in the compile
                   12622: command line to specify dependent libraries with @code{-l@var{lib}},
                   12623: causing these libraries to be dynamically linked when the wrapper
                   12624: function is linked.
                   12625: 
1.177     anton    12626: 
1.178     anton    12627: @node Low-Level C Interface Words,  , C interface internals, C Interface
1.155     anton    12628: @subsection Low-Level C Interface Words
1.44      crook    12629: 
1.155     anton    12630: doc-open-lib
                   12631: doc-lib-sym
1.196     anton    12632: doc-lib-error
1.177     anton    12633: doc-call-c
1.26      crook    12634: 
1.78      anton    12635: @c -------------------------------------------------------------
1.150     anton    12636: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78      anton    12637: @section Assembler and Code Words
                   12638: @cindex assembler
                   12639: @cindex code words
1.44      crook    12640: 
1.78      anton    12641: @menu
1.221     anton    12642: * Assembler Definitions::       Definitions in assembly language
1.78      anton    12643: * Common Assembler::            Assembler Syntax
                   12644: * Common Disassembler::         
                   12645: * 386 Assembler::               Deviations and special cases
1.221     anton    12646: * AMD64 Assembler::             
1.78      anton    12647: * Alpha Assembler::             Deviations and special cases
                   12648: * MIPS assembler::              Deviations and special cases
1.161     anton    12649: * PowerPC assembler::           Deviations and special cases
1.193     dvdkhlng 12650: * ARM Assembler::               Deviations and special cases
1.78      anton    12651: * Other assemblers::            How to write them
                   12652: @end menu
1.21      crook    12653: 
1.221     anton    12654: @node Assembler Definitions, Common Assembler, Assembler and Code Words, Assembler and Code Words
1.219     anton    12655: @subsection Definitions in assembly language
1.21      crook    12656: 
1.219     anton    12657: Gforth provides ways to implement words in assembly language (using
                   12658: @code{abi-code}...@code{end-code}), and also ways to define defining
                   12659: words with arbitrary run-time behaviour (like @code{does>}), where
                   12660: (unlike @code{does>}) the behaviour is not defined in Forth, but in
                   12661: assembly language (with @code{;code}).
                   12662: 
                   12663: However, the machine-independent nature of Gforth poses a few
                   12664: problems: First of all, Gforth runs on several architectures, so it
                   12665: can provide no standard assembler. It does provide assemblers for
                   12666: several of the architectures it runs on, though.  Moreover, you can
                   12667: use a system-independent assembler in Gforth, or compile machine code
                   12668: directly with @code{,} and @code{c,}.
                   12669: 
                   12670: Another problem is that the virtual machine registers of Gforth (the
                   12671: stack pointers and the virtual machine instruction pointer) depend on
                   12672: the installation and engine.  Also, which registers are free to use
                   12673: also depend on the installation and engine.  So any code written to
                   12674: run in the context of the Gforth virtual machine is essentially
                   12675: limited to the installation and engine it was developed for (it may
                   12676: run elsewhere, but you cannot rely on that).
                   12677: 
                   12678: Fortunately, you can define @code{abi-code} words in Gforth that are
1.221     anton    12679: portable to any Gforth running on a platform with the same calling
                   12680: convention (ABI); typically this means portability to the same
1.219     anton    12681: architecture/OS combination, sometimes crossing OS boundaries).
1.44      crook    12682: 
1.78      anton    12683: doc-assembler
                   12684: doc-init-asm
1.215     dvdkhlng 12685: doc-abi-code
1.78      anton    12686: doc-end-code
1.219     anton    12687: doc-code
1.78      anton    12688: doc-;code
                   12689: doc-flush-icache
1.44      crook    12690: 
1.21      crook    12691: 
1.219     anton    12692: If @code{flush-icache} does not work correctly, @code{abi-code} words
1.78      anton    12693: etc. will not work (reliably), either.
1.44      crook    12694: 
1.219     anton    12695: The typical usage of these words can be shown most easily by analogy
                   12696: to the equivalent high-level defining words:
1.44      crook    12697: 
1.78      anton    12698: @example
1.219     anton    12699: : foo                              abi-code foo
1.78      anton    12700:    <high-level Forth words>              <assembler>
                   12701: ;                                  end-code
                   12702:                                 
                   12703: : bar                              : bar
                   12704:    <high-level Forth words>           <high-level Forth words>
                   12705:    CREATE                             CREATE
                   12706:       <high-level Forth words>           <high-level Forth words>
                   12707:    DOES>                              ;code
                   12708:       <high-level Forth words>           <assembler>
                   12709: ;                                  end-code
                   12710: @end example
1.21      crook    12711: 
1.219     anton    12712: For using @code{abi-code}, take a look at the ABI documentation of
                   12713: your platform to see how the parameters are passed (so you know where
                   12714: you get the stack pointers) and how the return value is passed (so you
                   12715: know where the data stack pointer is returned).  The ABI documentation
                   12716: also tells you which registers are saved by the caller (caller-saved),
                   12717: so you are free to destroy them in your code, and which registers have
                   12718: to be preserved by the called word (callee-saved), so you have to save
1.221     anton    12719: them before using them, and restore them afterwards.  For some
                   12720: architectures and OSs we give short summaries of the parts of the
                   12721: calling convention in the appropriate sections.  More
1.219     anton    12722: reverse-engineering oriented people can also find out about the
                   12723: passing and returning of the stack pointers through @code{see
                   12724: abi-call}.
                   12725: 
                   12726: Most ABIs pass the parameters through registers, but some (in
1.221     anton    12727: particular the most common 386 (aka IA-32) calling conventions) pass
                   12728: them on the architectural stack.  The common ABIs all pass the return
                   12729: value in a register.
                   12730: 
                   12731: Other things you need to know for using @code{abi-code} is that both
                   12732: the data and the FP stack grow downwards (towards lower addresses) in
                   12733: Gforth, with @code{1 cells} size per cell, and @code{1 floats} size
                   12734: per FP value.
1.219     anton    12735: 
                   12736: Here's an example of using @code{abi-code} on the 386 architecture:
                   12737: 
                   12738: @example
                   12739: abi-code my+ ( n1 n2 -- n )
                   12740: 4 sp d) ax mov \ sp into return reg
                   12741: ax )    cx mov \ tos
                   12742: 4 #     ax add \ update sp (pop)
1.221     anton    12743: cx    ax ) add \ sec = sec+tos
1.219     anton    12744: ret            \ return from my+
                   12745: end-code
                   12746: @end example
1.44      crook    12747: 
1.221     anton    12748: An AMD64 variant of this example can be found in @ref{AMD64 Assembler}.
1.44      crook    12749: 
1.221     anton    12750: Here's a 386 example that deals with FP values:
                   12751: 
                   12752: @example
                   12753: abi-code my-f+ ( r1 r2 -- r )
                   12754: 8 sp d) cx mov  \ load address of fp
                   12755: cx )    dx mov  \ load fp
                   12756: .fl dx )   fld  \ r2
                   12757: 8 #     dx add  \ update fp
                   12758: .fl dx )   fadd \ r1+r2
                   12759: .fl dx )   fstp \ store r
                   12760: dx    cx ) mov  \ store new fp
                   12761: 4 sp d) ax mov  \ sp into return reg
                   12762: ret             \ return from my-f+
                   12763: end-code
                   12764: @end example
                   12765: 
                   12766: 
                   12767: @node Common Assembler, Common Disassembler, Assembler Definitions, Assembler and Code Words
1.78      anton    12768: @subsection Common Assembler
1.44      crook    12769: 
1.78      anton    12770: The assemblers in Gforth generally use a postfix syntax, i.e., the
                   12771: instruction name follows the operands.
1.21      crook    12772: 
1.78      anton    12773: The operands are passed in the usual order (the same that is used in the
                   12774: manual of the architecture).  Since they all are Forth words, they have
                   12775: to be separated by spaces; you can also use Forth words to compute the
                   12776: operands.
1.44      crook    12777: 
1.78      anton    12778: The instruction names usually end with a @code{,}.  This makes it easier
                   12779: to visually separate instructions if you put several of them on one
                   12780: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21      crook    12781: 
1.78      anton    12782: Registers are usually specified by number; e.g., (decimal) @code{11}
                   12783: specifies registers R11 and F11 on the Alpha architecture (which one,
                   12784: depends on the instruction).  The usual names are also available, e.g.,
                   12785: @code{s2} for R11 on Alpha.
1.21      crook    12786: 
1.78      anton    12787: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
                   12788: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
                   12789: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
                   12790: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
                   12791: conditions are specified in a way specific to each assembler.
1.1       anton    12792: 
1.219     anton    12793: The rest of this section is of interest mainly for those who want to
                   12794: define @code{code} words (instead of the more portable @code{abi-code}
                   12795: words).
                   12796: 
1.78      anton    12797: Note that the register assignments of the Gforth engine can change
                   12798: between Gforth versions, or even between different compilations of the
1.215     dvdkhlng 12799: same Gforth version (e.g., if you use a different GCC version).  If
                   12800: you are using @code{CODE} instead of @code{ABI-CODE}, and you want to
                   12801: refer to Gforth's registers (e.g., the stack pointer or TOS), I
                   12802: recommend defining your own words for refering to these registers, and
1.219     anton    12803: using them later on; then you can adapt to a changed register
1.221     anton    12804: assignment.
1.1       anton    12805: 
1.219     anton    12806: The most common use of these registers is to end a @code{code}
                   12807: definition with a dispatch to the next word (the @code{next} routine).
                   12808: A portable way to do this is to jump to @code{' noop >code-address}
                   12809: (of course, this is less efficient than integrating the @code{next}
                   12810: code and scheduling it well).  When using @code{ABI-CODE}, you can
                   12811: just assemble a normal subroutine return (but make sure you return the
                   12812: data stack pointer).
1.1       anton    12813: 
1.219     anton    12814: Another difference between Gforth versions is that the top of stack is
1.215     dvdkhlng 12815: kept in memory in @code{gforth} and, on most platforms, in a register
                   12816: in @code{gforth-fast}.  For @code{ABI-CODE} definitions, any stack
                   12817: caching registers are guaranteed to be flushed to the stack, allowing
1.219     anton    12818: you to reliably access the top of stack in memory.
1.96      anton    12819: 
1.78      anton    12820: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
                   12821: @subsection Common Disassembler
1.127     anton    12822: @cindex disassembler, general
                   12823: @cindex gdb disassembler
1.1       anton    12824: 
1.78      anton    12825: You can disassemble a @code{code} word with @code{see}
                   12826: (@pxref{Debugging}).  You can disassemble a section of memory with
1.1       anton    12827: 
1.127     anton    12828: doc-discode
1.44      crook    12829: 
1.127     anton    12830: There are two kinds of disassembler for Gforth: The Forth disassembler
                   12831: (available on some CPUs) and the gdb disassembler (available on
                   12832: platforms with @command{gdb} and @command{mktemp}).  If both are
                   12833: available, the Forth disassembler is used by default.  If you prefer
                   12834: the gdb disassembler, say
                   12835: 
                   12836: @example
                   12837: ' disasm-gdb is discode
                   12838: @end example
                   12839: 
                   12840: If neither is available, @code{discode} performs @code{dump}.
                   12841: 
                   12842: The Forth disassembler generally produces output that can be fed into the
1.78      anton    12843: assembler (i.e., same syntax, etc.).  It also includes additional
                   12844: information in comments.  In particular, the address of the instruction
                   12845: is given in a comment before the instruction.
1.1       anton    12846: 
1.127     anton    12847: The gdb disassembler produces output in the same format as the gdb
                   12848: @code{disassemble} command (@pxref{Machine Code,,Source and machine
                   12849: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
                   12850: the 386 and AMD64 architectures).
                   12851: 
1.78      anton    12852: @code{See} may display more or less than the actual code of the word,
                   12853: because the recognition of the end of the code is unreliable.  You can
1.127     anton    12854: use @code{discode} if it did not display enough.  It may display more, if
1.78      anton    12855: the code word is not immediately followed by a named word.  If you have
1.116     anton    12856: something else there, you can follow the word with @code{align latest ,}
1.78      anton    12857: to ensure that the end is recognized.
1.21      crook    12858: 
1.221     anton    12859: @node 386 Assembler, AMD64 Assembler, Common Disassembler, Assembler and Code Words
1.78      anton    12860: @subsection 386 Assembler
1.44      crook    12861: 
1.78      anton    12862: The 386 assembler included in Gforth was written by Bernd Paysan, it's
                   12863: available under GPL, and originally part of bigFORTH.
1.21      crook    12864: 
1.78      anton    12865: The 386 disassembler included in Gforth was written by Andrew McKewan
                   12866: and is in the public domain.
1.21      crook    12867: 
1.91      anton    12868: The disassembler displays code in an Intel-like prefix syntax.
1.21      crook    12869: 
1.221     anton    12870: The assembler uses a postfix syntax with AT&T-style parameter order
                   12871: (i.e., destination last).
1.1       anton    12872: 
1.78      anton    12873: The assembler includes all instruction of the Athlon, i.e. 486 core
                   12874: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
                   12875: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
                   12876: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1       anton    12877: 
1.78      anton    12878: There are several prefixes to switch between different operation sizes,
                   12879: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
                   12880: double-word accesses. Addressing modes can be switched with @code{.wa}
                   12881: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
                   12882: need a prefix for byte register names (@code{AL} et al).
1.1       anton    12883: 
1.78      anton    12884: For floating point operations, the prefixes are @code{.fs} (IEEE
                   12885: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
1.221     anton    12886: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).  The
                   12887: default is @code{.fx}, so you need to specify @code{.fl} explicitly
                   12888: when dealing with Gforth FP values.
1.21      crook    12889: 
1.78      anton    12890: The MMX opcodes don't have size prefixes, they are spelled out like in
                   12891: the Intel assembler. Instead of move from and to memory, there are
                   12892: PLDQ/PLDD and PSTQ/PSTD.
1.21      crook    12893: 
1.78      anton    12894: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
                   12895: ax.  Immediate values are indicated by postfixing them with @code{#},
1.91      anton    12896: e.g., @code{3 #}.  Here are some examples of addressing modes in various
                   12897: syntaxes:
1.21      crook    12898: 
1.26      crook    12899: @example
1.91      anton    12900: Gforth          Intel (NASM)   AT&T (gas)      Name
                   12901: .w ax           ax             %ax             register (16 bit)
                   12902: ax              eax            %eax            register (32 bit)
                   12903: 3 #             offset 3       $3              immediate
                   12904: 1000 #)         byte ptr 1000  1000            displacement
                   12905: bx )            [ebx]          (%ebx)          base
                   12906: 100 di d)       100[edi]       100(%edi)       base+displacement
                   12907: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
                   12908: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
                   12909: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
                   12910: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
                   12911: @end example
                   12912: 
                   12913: You can use @code{L)} and @code{LI)} instead of @code{D)} and
                   12914: @code{DI)} to enforce 32-bit displacement fields (useful for
                   12915: later patching).
1.21      crook    12916: 
1.78      anton    12917: Some example of instructions are:
1.1       anton    12918: 
                   12919: @example
1.78      anton    12920: ax bx mov             \ move ebx,eax
                   12921: 3 # ax mov            \ mov eax,3
1.137     pazsan   12922: 100 di d) ax mov      \ mov eax,100[edi]
1.78      anton    12923: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
                   12924: .w ax bx mov          \ mov bx,ax
1.1       anton    12925: @end example
                   12926: 
1.78      anton    12927: The following forms are supported for binary instructions:
1.1       anton    12928: 
                   12929: @example
1.78      anton    12930: <reg> <reg> <inst>
                   12931: <n> # <reg> <inst>
                   12932: <mem> <reg> <inst>
                   12933: <reg> <mem> <inst>
1.136     pazsan   12934: <n> # <mem> <inst>
1.1       anton    12935: @end example
                   12936: 
1.136     pazsan   12937: The shift/rotate syntax is:
1.1       anton    12938: 
1.26      crook    12939: @example
1.78      anton    12940: <reg/mem> 1 # shl \ shortens to shift without immediate
                   12941: <reg/mem> 4 # shl
                   12942: <reg/mem> cl shl
1.26      crook    12943: @end example
1.1       anton    12944: 
1.78      anton    12945: Precede string instructions (@code{movs} etc.) with @code{.b} to get
                   12946: the byte version.
1.1       anton    12947: 
1.78      anton    12948: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
                   12949: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
                   12950: pc < >= <= >}. (Note that most of these words shadow some Forth words
                   12951: when @code{assembler} is in front of @code{forth} in the search path,
                   12952: e.g., in @code{code} words).  Currently the control structure words use
                   12953: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
                   12954: to shuffle them (you can also use @code{swap} etc.).
1.21      crook    12955: 
1.221     anton    12956: Based on the Intel ABI (used in Linux), @code{abi-code} words can find
                   12957: the data stack pointer at @code{4 sp d)}, and the address of the FP
                   12958: stack pointer at @code{8 sp d)}; the data stack pointer is returned in
                   12959: @code{ax}; @code{Ax}, @code{cx}, and @code{dx} are caller-saved, so
                   12960: you do not need to preserve their values inside the word.  You can
                   12961: return from the word with @code{ret}, the parameters are cleaned up by
                   12962: the caller.
                   12963: 
                   12964: For examples of 386 @code{abi-code} words, see @ref{Assembler Definitions}.
1.21      crook    12965: 
                   12966: 
1.221     anton    12967: @node AMD64 Assembler, Alpha Assembler, 386 Assembler, Assembler and Code Words
1.220     dvdkhlng 12968: @subsection AMD64 (x86_64) Assembler
1.161     anton    12969: 
1.220     dvdkhlng 12970: The AMD64 assembler is a slightly modified version of the 386
                   12971: assembler, and as such shares most of the syntax.  Two new prefixes,
                   12972: @code{.q} and @code{.qa}, are provided to select 64-bit operand and
1.221     anton    12973: address sizes respectively.  64-bit sizes are the default, so normally
                   12974: you only have to use the other prefixes.  Also there are additional
                   12975: register operands @code{R8}-@code{R15}.
1.220     dvdkhlng 12976: 
                   12977: The registers lack the 'e' or 'r' prefix; even in 64 bit mode,
                   12978: @code{rax} is called @code{ax}.  Additional register operands are
                   12979: available to refer to the lowest-significant byte of all registers:
                   12980: @code{R8L}-@code{R15L}, @code{SPL}, @code{BPL}, @code{SIL},
                   12981: @code{DIL}.
                   12982: 
1.221     anton    12983: The Linux-AMD64 calling convention is to pass the first 6 integer
                   12984: parameters in rdi, rsi, rdx, rcx, r8 and r9 and to return the result
                   12985: in rax and rdx; to pass the first 8 FP parameters in xmm0--xmm7 and to
                   12986: return FP results in xmm0--xmm1.  So @code{abi-code} words get the
                   12987: data stack pointer in @code{di} and the address of the FP stack
                   12988: pointer in @code{si}, and return the data stack pointer in @code{ax}.
                   12989: The other caller-saved registers are: r10, r11, xmm8-xmm15.  This
1.222     anton    12990: calling convention reportedly is also used in other non-Microsoft OSs.
                   12991: @c source: http://en.wikipedia.org/wiki/X86_calling_conventions#AMD64_ABI_convention
                   12992: 
                   12993: @c source: http://msdn.microsoft.com/en-us/library/9b372w95(v=VS.90).aspx
                   12994: Windows x64 passes the first four integer parameters in rcx, rdx, r8
                   12995: and r9 and return the integer result in rax.  The other caller-saved
                   12996: registers are r10 and r11.
1.221     anton    12997: 
1.220     dvdkhlng 12998: Here is an example of an AMD64 @code{abi-code} word:
                   12999: 
                   13000: @example
                   13001: abi-code my+  ( n1 n2 -- n3 )
1.221     anton    13002: \ SP passed in di, returned in ax,  address of FP passed in si
                   13003: 8 di d) ax lea        \ compute new sp in result reg
                   13004: di )    dx mov        \ get old tos
                   13005: dx    ax ) add        \ add to new tos
                   13006: ret
1.220     dvdkhlng 13007: end-code
                   13008: @end example
                   13009: 
1.226     dvdkhlng 13010: Here's a AMD64 example that deals with FP values:
                   13011: 
                   13012: @example
                   13013: abi-code my-f+  ( r1 r2 -- r )
                   13014: \ SP passed in di, returned in ax,  address of FP passed in si
1.227     dvdkhlng 13015: si )       dx mov         \ load fp
                   13016: 8 dx d)  xmm0 movsd       \ r2
                   13017: dx )     xmm0 addsd       \ r1+r2
                   13018: xmm0  8 dx d) movsd       \ store r
                   13019: 8 #      si ) add         \ update fp
                   13020: di         ax mov         \ sp into return reg
1.226     dvdkhlng 13021: ret
                   13022: end-code
                   13023: @end example
                   13024: 
1.221     anton    13025: @node Alpha Assembler, MIPS assembler, AMD64 Assembler, Assembler and Code Words
1.78      anton    13026: @subsection Alpha Assembler
1.21      crook    13027: 
1.78      anton    13028: The Alpha assembler and disassembler were originally written by Bernd
                   13029: Thallner.
1.26      crook    13030: 
1.78      anton    13031: The register names @code{a0}--@code{a5} are not available to avoid
                   13032: shadowing hex numbers.
1.2       jwilke   13033: 
1.78      anton    13034: Immediate forms of arithmetic instructions are distinguished by a
                   13035: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
                   13036: does not count as arithmetic instruction).
1.2       jwilke   13037: 
1.78      anton    13038: You have to specify all operands to an instruction, even those that
                   13039: other assemblers consider optional, e.g., the destination register for
                   13040: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2       jwilke   13041: 
1.78      anton    13042: You can specify conditions for @code{if,} by removing the first @code{b}
                   13043: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2       jwilke   13044: 
1.26      crook    13045: @example
1.78      anton    13046: 11 fgt if, \ if F11>0e
                   13047:   ...
                   13048: endif,
1.26      crook    13049: @end example
1.2       jwilke   13050: 
1.78      anton    13051: @code{fbgt,} gives @code{fgt}.  
                   13052: 
1.161     anton    13053: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78      anton    13054: @subsection MIPS assembler
1.2       jwilke   13055: 
1.78      anton    13056: The MIPS assembler was originally written by Christian Pirker.
1.2       jwilke   13057: 
1.224     dvdkhlng 13058: Currently the assembler and disassembler covers most of the MIPS32
                   13059: architecture and doesn't support FP instructions.
1.2       jwilke   13060: 
1.78      anton    13061: The register names @code{$a0}--@code{$a3} are not available to avoid
1.224     dvdkhlng 13062: shadowing hex numbers.  Use register numbers @code{$4}--@code{$7}
                   13063: instead.
1.2       jwilke   13064: 
1.224     dvdkhlng 13065: Nothing distinguishes registers from immediate values.  Use explicit
                   13066: opcode names with the @code{i} suffix for instructions with immediate
                   13067: argument.  E.g. @code{addiu,} in place of @code{addu,}.
                   13068: 
                   13069: Where the architecture manual specifies several formats for the
                   13070: instruction (e.g., for @code{jalr,}),use the one with more arguments
                   13071: (i.e. two for @code{jalr,}).  When in doubt, see
1.78      anton    13072: @code{arch/mips/testasm.fs} for an example of correct use.
1.2       jwilke   13073: 
1.224     dvdkhlng 13074: Branches and jumps in the MIPS architecture have a delay slot.  You
                   13075: have to fill it manually (the simplest way is to use @code{nop,}), the
1.78      anton    13076: assembler does not do it for you (unlike @command{as}).  Even
1.224     dvdkhlng 13077: @code{if,}, @code{ahead,}, @code{until,}, @code{again,},
                   13078: @code{while,}, @code{else,} and @code{repeat,} need a delay slot.
                   13079: Since @code{begin,} and @code{then,} just specify branch targets, they
                   13080: are not affected.  For branches the argument specifying the target is
                   13081: a relative address.  Add the address of the delay slot to get the
                   13082: absolute address.
                   13083: 
                   13084: Note that you must not put branches nor jumps (nor control-flow
                   13085: instructions) into the delay slot.  Also it is a bad idea to put
                   13086: pseudo-ops such as @code{li,} into a delay slot, as these may expand
                   13087: to several instructions.  The MIPS I architecture also had load delay
                   13088: slots, and newer MIPSes still have restrictions on using @code{mfhi,}
                   13089: and @code{mflo,}.  Be careful to satisfy these restrictions, the
                   13090: assembler does not do it for you.
                   13091: 
                   13092: Some example of instructions are:
                   13093: 
                   13094: @example
                   13095: $ra  12 $sp  sw,         \ sw    ra,12(sp)
                   13096: $4    8 $s0  lw,         \ lw    a0,8(s0)
                   13097: $v0  $0  lui,            \ lui   v0,0x0
                   13098: $s0  $s4  $12  addiu,    \ addiu s0,s4,0x12
                   13099: $s0  $s4  $4  addu,      \ addu  s0,s4,$a0
                   13100: $ra  $t9  jalr,          \ jalr  t9
                   13101: @end example
1.1       anton    13102: 
1.78      anton    13103: You can specify the conditions for @code{if,} etc. by taking a
                   13104: conditional branch and leaving away the @code{b} at the start and the
                   13105: @code{,} at the end.  E.g.,
1.1       anton    13106: 
1.26      crook    13107: @example
1.78      anton    13108: 4 5 eq if,
                   13109:   ... \ do something if $4 equals $5
                   13110: then,
1.26      crook    13111: @end example
1.1       anton    13112: 
1.223     dvdkhlng 13113: The calling conventions for 32-bit MIPS machines is to pass the first
                   13114: 4 arguments in registers @code{$4}..@code{$7}, and to use
                   13115: @code{$v0}-@code{$v1} for return values.  In addition to these
                   13116: registers, it is ok to clobber registers @code{$t0}-@code{$t8} without
                   13117: saving and restoring them.
                   13118: 
                   13119: If you use @code{jalr,} to call into dynamic library routines, you
                   13120: must first load the called function's address into @code{$t9}, which
                   13121: is used by position-indirect code to do relative memory accesses.
                   13122: 
                   13123: Here is an example of a MIPS32 @code{abi-code} word:
                   13124: 
                   13125: @example
                   13126: abi-code my+  ( n1 n2 -- n3 )
                   13127:   \ SP passed in $4, returned in $v0
1.225     dvdkhlng 13128:   $t0  4 $4  lw,         \ load n1, n2 from stack
                   13129:   $t1  0 $4  lw,    
1.223     dvdkhlng 13130:   $t0  $t0  $t1  addu,   \ add n1+n2, result in $t0
                   13131:   $t0  4 $4  sw,         \ store result (overwriting n1)
                   13132:   $ra  jr,               \ return to caller
                   13133:   $v0  $4  4  addiu,     \ (delay slot) return uptated SP in $v0
                   13134: end-code
                   13135: @end example
1.161     anton    13136: 
1.193     dvdkhlng 13137: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
1.161     anton    13138: @subsection PowerPC assembler
                   13139: 
1.162     anton    13140: The PowerPC assembler and disassembler were contributed by Michal
1.161     anton    13141: Revucky.
                   13142: 
1.162     anton    13143: This assembler does not follow the convention of ending mnemonic names
                   13144: with a ``,'', so some mnemonic names shadow regular Forth words (in
                   13145: particular: @code{and or xor fabs}); so if you want to use the Forth
                   13146: words, you have to make them visible first, e.g., with @code{also
                   13147: forth}.
                   13148: 
1.161     anton    13149: Registers are referred to by their number, e.g., @code{9} means the
                   13150: integer register 9 or the FP register 9 (depending on the
                   13151: instruction).
                   13152: 
                   13153: Because there is no way to distinguish registers from immediate values,
                   13154: you have to explicitly use the immediate forms of instructions, i.e.,
1.162     anton    13155: @code{addi,}, not just @code{add,}.
1.161     anton    13156: 
1.162     anton    13157: The assembler and disassembler usually support the most general form
1.161     anton    13158: of an instruction, but usually not the shorter forms (especially for
                   13159: branches).
                   13160: 
                   13161: 
1.193     dvdkhlng 13162: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
                   13163: @subsection ARM Assembler
1.161     anton    13164: 
1.215     dvdkhlng 13165: The ARM assembler includes all instruction of ARM architecture version
                   13166: 4, and the BLX instruction from architecture 5.  It does not (yet)
                   13167: have support for Thumb instructions.  It also lacks support for any
                   13168: co-processors.
                   13169: 
                   13170: The assembler uses a postfix syntax with the same operand order as
                   13171: used in the ARM Architecture Reference Manual.  Mnemonics are suffixed
                   13172: by a comma.
1.193     dvdkhlng 13173: 
                   13174: Registers are specified by their names @code{r0} through @code{r15},
                   13175: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
1.215     dvdkhlng 13176: @code{fp} provided for convenience.  Note that @code{ip} refers to
                   13177: the``intra procedure call scratch register'' (@code{r12}) and does not
                   13178: refer to an instruction pointer.  @code{sp} refers to the ARM ABI
                   13179: stack pointer (@code{r13}) and not the Forth stack pointer.
1.193     dvdkhlng 13180: 
                   13181: Condition codes can be specified anywhere in the instruction, but will
                   13182: be most readable if specified just in front of the mnemonic.  The 'S'
                   13183: flag is not a separate word, but encoded into instruction mnemonics,
                   13184: ie. just use @code{adds,} instead of @code{add,} if you want the
                   13185: status register to be updated.
                   13186: 
                   13187: The following table lists the syntax of operands for general
                   13188: instructions:
                   13189: 
                   13190: @example
                   13191: Gforth          normal assembler      description
                   13192: 123 #           #123                  immediate
                   13193: r12             r12                   register
                   13194: r12 4 #LSL      r12, LSL #4           shift left by immediate
                   13195: r12 r1 #LSL     r12, LSL r1           shift left by register
                   13196: r12 4 #LSR      r12, LSR #4           shift right by immediate
                   13197: r12 r1 #LSR     r12, LSR r1           shift right by register
                   13198: r12 4 #ASR      r12, ASR #4           arithmetic shift right
                   13199: r12 r1 #ASR     r12, ASR r1           ... by register
                   13200: r12 4 #ROR      r12, ROR #4           rotate right by immediate
                   13201: r12 r1 #ROR     r12, ROR r1           ... by register
                   13202: r12 RRX         r12, RRX              rotate right with extend by 1
                   13203: @end example
                   13204: 
                   13205: Memory operand syntax is listed in this table:
                   13206: 
                   13207: @example
                   13208: Gforth            normal assembler      description
                   13209: r4 ]              [r4]                  register
                   13210: r4 4 #]           [r4, #+4]             register with immediate offset
                   13211: r4 -4 #]          [r4, #-4]             with negative offset
                   13212: r4 r1 +]          [r4, +r1]             register with register offset
                   13213: r4 r1 -]          [r4, -r1]             with negated register offset
                   13214: r4 r1 2 #LSL -]   [r4, -r1, LSL #2]     with negated and shifted offset
                   13215: r4 4 #]!          [r4, #+4]!            immediate preincrement
                   13216: r4 r1 +]!         [r4, +r1]!            register preincrement
                   13217: r4 r1 -]!         [r4, +r1]!            register predecrement
                   13218: r4 r1 2 #LSL +]!  [r4, +r1, LSL #2]!    shifted preincrement
                   13219: r4 -4 ]#          [r4], #-4             immediate postdecrement
                   13220: r4 r1 ]+          [r4], r1              register postincrement
                   13221: r4 r1 ]-          [r4], -r1             register postdecrement
                   13222: r4 r1 2 #LSL ]-   [r4], -r1, LSL #2     shifted postdecrement
                   13223: ' xyz >body [#]   xyz                   PC-relative addressing
                   13224: @end example
                   13225: 
                   13226: Register lists for load/store multiple instructions are started and
1.220     dvdkhlng 13227: terminated by using the words @code{@{} and @code{@}} respectively.
1.215     dvdkhlng 13228: Between braces, register names can be listed one by one or register
                   13229: ranges can be formed by using the postfix operator @code{r-r}.  The
                   13230: @code{^} flag is not encoded in the register list operand, but instead
                   13231: directly encoded into the instruction mnemonic, ie. use @code{^ldm,}
                   13232: and @code{^stm,}.
1.193     dvdkhlng 13233: 
                   13234: Addressing modes for load/store multiple are not encoded as
1.216     dvdkhlng 13235: instruction suffixes, but instead specified like an addressing mode,
                   13236: Use one of @code{DA}, @code{IA}, @code{DB}, @code{IB}, @code{DA!},
                   13237: @code{IA!}, @code{DB!} or @code{IB!}.
1.193     dvdkhlng 13238: 
                   13239: The following table gives some examples:
                   13240: 
                   13241: @example
                   13242: Gforth                           normal assembler
1.216     dvdkhlng 13243: r4 ia  @{ r0 r7 r8 @}  stm,        stmia    r4, @{r0,r7,r8@}
                   13244: r4 db!  @{ r0 r7 r8 @}  ldm,       ldmdb    r4!, @{r0,r7,r8@}
                   13245: sp ia!  @{ r0 r15 r-r @}  ^ldm,    ldmfd    sp!, @{r0-r15@}^
1.193     dvdkhlng 13246: @end example
                   13247: 
1.215     dvdkhlng 13248: Control structure words typical for Forth assemblers are available:
                   13249: @code{if,} @code{ahead,} @code{then,} @code{else,} @code{begin,}
                   13250: @code{until,} @code{again,} @code{while,} @code{repeat,}
                   13251: @code{repeat-until,}.  Conditions are specified in front of these words:
1.193     dvdkhlng 13252: 
                   13253: @example
                   13254: r1 r2 cmp,    \ compare r1 and r2
                   13255: eq if,        \ equal?
                   13256:    ...          \ code executed if r1 == r2
                   13257: then,
                   13258: @end example
                   13259: 
1.215     dvdkhlng 13260: Example of a definition using the ARM assembler:
1.193     dvdkhlng 13261: 
                   13262: @example
1.215     dvdkhlng 13263: abi-code my+ ( n1 n2 --  n3 )
1.220     dvdkhlng 13264:    \ arm abi: r0=SP, r1=&FP, r2,r3,r12 saved by caller
                   13265:    r0 IA!  @{ r2 r3 @}  ldm,     \ pop r2 = n2, r3 = n1
                   13266:    r3  r2  r3         add,     \ r3 = n1+n1
                   13267:    r3  r0 -4 #]!      str,     \ push r3
                   13268:    pc  lr             mov,     \ return to caller, new SP in r0
1.193     dvdkhlng 13269: end-code
                   13270: @end example
                   13271: 
                   13272: @node Other assemblers,  , ARM Assembler, Assembler and Code Words
1.78      anton    13273: @subsection Other assemblers
                   13274: 
                   13275: If you want to contribute another assembler/disassembler, please contact
1.103     anton    13276: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
                   13277: an assembler already.  If you are writing them from scratch, please use
                   13278: a similar syntax style as the one we use (i.e., postfix, commas at the
                   13279: end of the instruction names, @pxref{Common Assembler}); make the output
                   13280: of the disassembler be valid input for the assembler, and keep the style
1.78      anton    13281: similar to the style we used.
                   13282: 
                   13283: Hints on implementation: The most important part is to have a good test
                   13284: suite that contains all instructions.  Once you have that, the rest is
                   13285: easy.  For actual coding you can take a look at
                   13286: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
                   13287: the assembler and disassembler, avoiding redundancy and some potential
                   13288: bugs.  You can also look at that file (and @pxref{Advanced does> usage
                   13289: example}) to get ideas how to factor a disassembler.
                   13290: 
                   13291: Start with the disassembler, because it's easier to reuse data from the
                   13292: disassembler for the assembler than the other way round.
1.1       anton    13293: 
1.78      anton    13294: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
                   13295: how simple it can be.
1.1       anton    13296: 
1.161     anton    13297: 
                   13298: 
                   13299: 
1.78      anton    13300: @c -------------------------------------------------------------
                   13301: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
                   13302: @section Threading Words
                   13303: @cindex threading words
1.1       anton    13304: 
1.78      anton    13305: @cindex code address
                   13306: These words provide access to code addresses and other threading stuff
                   13307: in Gforth (and, possibly, other interpretive Forths). It more or less
                   13308: abstracts away the differences between direct and indirect threading
                   13309: (and, for direct threading, the machine dependences). However, at
                   13310: present this wordset is still incomplete. It is also pretty low-level;
                   13311: some day it will hopefully be made unnecessary by an internals wordset
                   13312: that abstracts implementation details away completely.
1.1       anton    13313: 
1.78      anton    13314: The terminology used here stems from indirect threaded Forth systems; in
                   13315: such a system, the XT of a word is represented by the CFA (code field
                   13316: address) of a word; the CFA points to a cell that contains the code
                   13317: address.  The code address is the address of some machine code that
                   13318: performs the run-time action of invoking the word (e.g., the
                   13319: @code{dovar:} routine pushes the address of the body of the word (a
                   13320: variable) on the stack
                   13321: ).
1.1       anton    13322: 
1.78      anton    13323: @cindex code address
                   13324: @cindex code field address
                   13325: In an indirect threaded Forth, you can get the code address of @i{name}
                   13326: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
                   13327: >code-address}, independent of the threading method.
1.1       anton    13328: 
1.78      anton    13329: doc-threading-method
                   13330: doc->code-address
                   13331: doc-code-address!
1.1       anton    13332: 
1.78      anton    13333: @cindex @code{does>}-handler
                   13334: @cindex @code{does>}-code
                   13335: For a word defined with @code{DOES>}, the code address usually points to
                   13336: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
                   13337: routine (in Gforth on some platforms, it can also point to the dodoes
                   13338: routine itself).  What you are typically interested in, though, is
                   13339: whether a word is a @code{DOES>}-defined word, and what Forth code it
                   13340: executes; @code{>does-code} tells you that.
1.1       anton    13341: 
1.78      anton    13342: doc->does-code
1.1       anton    13343: 
1.78      anton    13344: To create a @code{DOES>}-defined word with the following basic words,
                   13345: you have to set up a @code{DOES>}-handler with @code{does-handler!};
                   13346: @code{/does-handler} aus behind you have to place your executable Forth
                   13347: code.  Finally you have to create a word and modify its behaviour with
                   13348: @code{does-handler!}.
1.1       anton    13349: 
1.78      anton    13350: doc-does-code!
                   13351: doc-does-handler!
                   13352: doc-/does-handler
1.1       anton    13353: 
1.78      anton    13354: The code addresses produced by various defining words are produced by
                   13355: the following words:
1.1       anton    13356: 
1.78      anton    13357: doc-docol:
                   13358: doc-docon:
                   13359: doc-dovar:
                   13360: doc-douser:
                   13361: doc-dodefer:
                   13362: doc-dofield:
1.1       anton    13363: 
1.99      anton    13364: @cindex definer
                   13365: The following two words generalize @code{>code-address},
                   13366: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
                   13367: 
                   13368: doc->definer
                   13369: doc-definer!
                   13370: 
1.26      crook    13371: @c -------------------------------------------------------------
1.78      anton    13372: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21      crook    13373: @section Passing Commands to the Operating System
                   13374: @cindex operating system - passing commands
                   13375: @cindex shell commands
                   13376: 
                   13377: Gforth allows you to pass an arbitrary string to the host operating
                   13378: system shell (if such a thing exists) for execution.
                   13379: 
                   13380: doc-sh
                   13381: doc-system
                   13382: doc-$?
1.23      crook    13383: doc-getenv
1.44      crook    13384: 
1.26      crook    13385: @c -------------------------------------------------------------
1.47      crook    13386: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
                   13387: @section Keeping track of Time
                   13388: @cindex time-related words
                   13389: 
                   13390: doc-ms
                   13391: doc-time&date
1.79      anton    13392: doc-utime
                   13393: doc-cputime
1.47      crook    13394: 
                   13395: 
                   13396: @c -------------------------------------------------------------
                   13397: @node Miscellaneous Words,  , Keeping track of Time, Words
1.21      crook    13398: @section Miscellaneous Words
                   13399: @cindex miscellaneous words
                   13400: 
1.29      crook    13401: @comment TODO find homes for these
                   13402: 
1.26      crook    13403: These section lists the ANS Forth words that are not documented
1.21      crook    13404: elsewhere in this manual. Ultimately, they all need proper homes.
                   13405: 
1.68      anton    13406: doc-quit
1.44      crook    13407: 
1.26      crook    13408: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    13409: (@pxref{ANS conformance}):
1.21      crook    13410: 
                   13411: @code{EDITOR} 
                   13412: @code{EMIT?} 
                   13413: @code{FORGET} 
                   13414: 
1.24      anton    13415: @c ******************************************************************
                   13416: @node Error messages, Tools, Words, Top
                   13417: @chapter Error messages
                   13418: @cindex error messages
                   13419: @cindex backtrace
                   13420: 
                   13421: A typical Gforth error message looks like this:
                   13422: 
                   13423: @example
1.86      anton    13424: in file included from \evaluated string/:-1
1.24      anton    13425: in file included from ./yyy.fs:1
                   13426: ./xxx.fs:4: Invalid memory address
1.134     anton    13427: >>>bar<<<
1.79      anton    13428: Backtrace:
1.25      anton    13429: $400E664C @@
                   13430: $400E6664 foo
1.24      anton    13431: @end example
                   13432: 
                   13433: The message identifying the error is @code{Invalid memory address}.  The
                   13434: error happened when text-interpreting line 4 of the file
                   13435: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   13436: word on the line where the error happened, is pointed out (with
1.134     anton    13437: @code{>>>} and @code{<<<}).
1.24      anton    13438: 
                   13439: The file containing the error was included in line 1 of @file{./yyy.fs},
                   13440: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   13441: @file{yyy.fs} as command-line parameter to Gforth).
                   13442: 
                   13443: At the end of the error message you find a return stack dump that can be
                   13444: interpreted as a backtrace (possibly empty). On top you find the top of
                   13445: the return stack when the @code{throw} happened, and at the bottom you
                   13446: find the return stack entry just above the return stack of the topmost
                   13447: text interpreter.
                   13448: 
                   13449: To the right of most return stack entries you see a guess for the word
                   13450: that pushed that return stack entry as its return address. This gives a
                   13451: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   13452: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   13453: address} exception).
                   13454: 
                   13455: Note that the backtrace is not perfect: We don't know which return stack
                   13456: entries are return addresses (so we may get false positives); and in
                   13457: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   13458: address the word that pushed the return address, so for some return
                   13459: addresses you see no names in the return stack dump.
1.25      anton    13460: 
                   13461: @cindex @code{catch} and backtraces
                   13462: The return stack dump represents the return stack at the time when a
                   13463: specific @code{throw} was executed.  In programs that make use of
                   13464: @code{catch}, it is not necessarily clear which @code{throw} should be
                   13465: used for the return stack dump (e.g., consider one @code{throw} that
                   13466: indicates an error, which is caught, and during recovery another error
1.160     anton    13467: happens; which @code{throw} should be used for the stack dump?).
                   13468: Gforth presents the return stack dump for the first @code{throw} after
                   13469: the last executed (not returned-to) @code{catch} or @code{nothrow};
                   13470: this works well in the usual case. To get the right backtrace, you
                   13471: usually want to insert @code{nothrow} or @code{['] false catch drop}
                   13472: after a @code{catch} if the error is not rethrown.
1.25      anton    13473: 
                   13474: @cindex @code{gforth-fast} and backtraces
                   13475: @cindex @code{gforth-fast}, difference from @code{gforth}
                   13476: @cindex backtraces with @code{gforth-fast}
                   13477: @cindex return stack dump with @code{gforth-fast}
1.79      anton    13478: @code{Gforth} is able to do a return stack dump for throws generated
1.25      anton    13479: from primitives (e.g., invalid memory address, stack empty etc.);
                   13480: @code{gforth-fast} is only able to do a return stack dump from a
1.96      anton    13481: directly called @code{throw} (including @code{abort} etc.).  Given an
1.30      anton    13482: exception caused by a primitive in @code{gforth-fast}, you will
                   13483: typically see no return stack dump at all; however, if the exception is
                   13484: caught by @code{catch} (e.g., for restoring some state), and then
                   13485: @code{throw}n again, the return stack dump will be for the first such
                   13486: @code{throw}.
1.2       jwilke   13487: 
1.5       anton    13488: @c ******************************************************************
1.24      anton    13489: @node Tools, ANS conformance, Error messages, Top
1.1       anton    13490: @chapter Tools
                   13491: 
                   13492: @menu
                   13493: * ANS Report::                  Report the words used, sorted by wordset.
1.127     anton    13494: * Stack depth changes::         Where does this stack item come from?
1.1       anton    13495: @end menu
                   13496: 
                   13497: See also @ref{Emacs and Gforth}.
                   13498: 
1.126     pazsan   13499: @node ANS Report, Stack depth changes, Tools, Tools
1.1       anton    13500: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   13501: @cindex @file{ans-report.fs}
                   13502: @cindex report the words used in your program
                   13503: @cindex words used in your program
                   13504: 
                   13505: If you want to label a Forth program as ANS Forth Program, you must
                   13506: document which wordsets the program uses; for extension wordsets, it is
                   13507: helpful to list the words the program requires from these wordsets
                   13508: (because Forth systems are allowed to provide only some words of them).
                   13509: 
                   13510: The @file{ans-report.fs} tool makes it easy for you to determine which
                   13511: words from which wordset and which non-ANS words your application
                   13512: uses. You simply have to include @file{ans-report.fs} before loading the
                   13513: program you want to check. After loading your program, you can get the
                   13514: report with @code{print-ans-report}. A typical use is to run this as
                   13515: batch job like this:
                   13516: @example
                   13517: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   13518: @end example
                   13519: 
                   13520: The output looks like this (for @file{compat/control.fs}):
                   13521: @example
                   13522: The program uses the following words
                   13523: from CORE :
                   13524: : POSTPONE THEN ; immediate ?dup IF 0= 
                   13525: from BLOCK-EXT :
                   13526: \ 
                   13527: from FILE :
                   13528: ( 
                   13529: @end example
                   13530: 
                   13531: @subsection Caveats
                   13532: 
                   13533: Note that @file{ans-report.fs} just checks which words are used, not whether
                   13534: they are used in an ANS Forth conforming way!
                   13535: 
                   13536: Some words are defined in several wordsets in the
                   13537: standard. @file{ans-report.fs} reports them for only one of the
                   13538: wordsets, and not necessarily the one you expect. It depends on usage
                   13539: which wordset is the right one to specify. E.g., if you only use the
                   13540: compilation semantics of @code{S"}, it is a Core word; if you also use
                   13541: its interpretation semantics, it is a File word.
1.124     anton    13542: 
                   13543: 
1.127     anton    13544: @node Stack depth changes,  , ANS Report, Tools
1.124     anton    13545: @section Stack depth changes during interpretation
                   13546: @cindex @file{depth-changes.fs}
                   13547: @cindex depth changes during interpretation
                   13548: @cindex stack depth changes during interpretation
                   13549: @cindex items on the stack after interpretation
                   13550: 
                   13551: Sometimes you notice that, after loading a file, there are items left
                   13552: on the stack.  The tool @file{depth-changes.fs} helps you find out
                   13553: quickly where in the file these stack items are coming from.
                   13554: 
                   13555: The simplest way of using @file{depth-changes.fs} is to include it
                   13556: before the file(s) you want to check, e.g.:
                   13557: 
                   13558: @example
                   13559: gforth depth-changes.fs my-file.fs
                   13560: @end example
                   13561: 
                   13562: This will compare the stack depths of the data and FP stack at every
                   13563: empty line (in interpretation state) against these depths at the last
                   13564: empty line (in interpretation state).  If the depths are not equal,
                   13565: the position in the file and the stack contents are printed with
                   13566: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
                   13567: change has occured in the paragraph of non-empty lines before the
                   13568: indicated line.  It is a good idea to leave an empty line at the end
                   13569: of the file, so the last paragraph is checked, too.
                   13570: 
                   13571: Checking only at empty lines usually works well, but sometimes you
                   13572: have big blocks of non-empty lines (e.g., when building a big table),
                   13573: and you want to know where in this block the stack depth changed.  You
                   13574: can check all interpreted lines with
                   13575: 
                   13576: @example
                   13577: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
                   13578: @end example
                   13579: 
                   13580: This checks the stack depth at every end-of-line.  So the depth change
                   13581: occured in the line reported by the @code{~~} (not in the line
                   13582: before).
                   13583: 
                   13584: Note that, while this offers better accuracy in indicating where the
                   13585: stack depth changes, it will often report many intentional stack depth
                   13586: changes (e.g., when an interpreted computation stretches across
                   13587: several lines).  You can suppress the checking of some lines by
                   13588: putting backslashes at the end of these lines (not followed by white
                   13589: space), and using
                   13590: 
                   13591: @example
                   13592: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
                   13593: @end example
1.1       anton    13594: 
                   13595: @c ******************************************************************
1.65      anton    13596: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1       anton    13597: @chapter ANS conformance
                   13598: @cindex ANS conformance of Gforth
                   13599: 
                   13600: To the best of our knowledge, Gforth is an
                   13601: 
                   13602: ANS Forth System
                   13603: @itemize @bullet
                   13604: @item providing the Core Extensions word set
                   13605: @item providing the Block word set
                   13606: @item providing the Block Extensions word set
                   13607: @item providing the Double-Number word set
                   13608: @item providing the Double-Number Extensions word set
                   13609: @item providing the Exception word set
                   13610: @item providing the Exception Extensions word set
                   13611: @item providing the Facility word set
1.40      anton    13612: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1       anton    13613: @item providing the File Access word set
                   13614: @item providing the File Access Extensions word set
                   13615: @item providing the Floating-Point word set
                   13616: @item providing the Floating-Point Extensions word set
                   13617: @item providing the Locals word set
                   13618: @item providing the Locals Extensions word set
                   13619: @item providing the Memory-Allocation word set
                   13620: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   13621: @item providing the Programming-Tools word set
                   13622: @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
                   13623: @item providing the Search-Order word set
                   13624: @item providing the Search-Order Extensions word set
                   13625: @item providing the String word set
                   13626: @item providing the String Extensions word set (another easy one)
                   13627: @end itemize
                   13628: 
1.118     anton    13629: Gforth has the following environmental restrictions:
                   13630: 
                   13631: @cindex environmental restrictions
                   13632: @itemize @bullet
                   13633: @item
                   13634: While processing the OS command line, if an exception is not caught,
                   13635: Gforth exits with a non-zero exit code instyead of performing QUIT.
                   13636: 
                   13637: @item
                   13638: When an @code{throw} is performed after a @code{query}, Gforth does not
                   13639: allways restore the input source specification in effect at the
                   13640: corresponding catch.
                   13641: 
                   13642: @end itemize
                   13643: 
                   13644: 
1.1       anton    13645: @cindex system documentation
                   13646: In addition, ANS Forth systems are required to document certain
                   13647: implementation choices. This chapter tries to meet these
                   13648: requirements. In many cases it gives a way to ask the system for the
                   13649: information instead of providing the information directly, in
                   13650: particular, if the information depends on the processor, the operating
                   13651: system or the installation options chosen, or if they are likely to
                   13652: change during the maintenance of Gforth.
                   13653: 
                   13654: @comment The framework for the rest has been taken from pfe.
                   13655: 
                   13656: @menu
                   13657: * The Core Words::              
                   13658: * The optional Block word set::  
                   13659: * The optional Double Number word set::  
                   13660: * The optional Exception word set::  
                   13661: * The optional Facility word set::  
                   13662: * The optional File-Access word set::  
                   13663: * The optional Floating-Point word set::  
                   13664: * The optional Locals word set::  
                   13665: * The optional Memory-Allocation word set::  
                   13666: * The optional Programming-Tools word set::  
                   13667: * The optional Search-Order word set::  
                   13668: @end menu
                   13669: 
                   13670: 
                   13671: @c =====================================================================
                   13672: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   13673: @comment  node-name,  next,  previous,  up
                   13674: @section The Core Words
                   13675: @c =====================================================================
                   13676: @cindex core words, system documentation
                   13677: @cindex system documentation, core words
                   13678: 
                   13679: @menu
                   13680: * core-idef::                   Implementation Defined Options                   
                   13681: * core-ambcond::                Ambiguous Conditions                
                   13682: * core-other::                  Other System Documentation                  
                   13683: @end menu
                   13684: 
                   13685: @c ---------------------------------------------------------------------
                   13686: @node core-idef, core-ambcond, The Core Words, The Core Words
                   13687: @subsection Implementation Defined Options
                   13688: @c ---------------------------------------------------------------------
                   13689: @cindex core words, implementation-defined options
                   13690: @cindex implementation-defined options, core words
                   13691: 
                   13692: 
                   13693: @table @i
                   13694: @item (Cell) aligned addresses:
                   13695: @cindex cell-aligned addresses
                   13696: @cindex aligned addresses
                   13697: processor-dependent. Gforth's alignment words perform natural alignment
                   13698: (e.g., an address aligned for a datum of size 8 is divisible by
                   13699: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   13700: 
                   13701: @item @code{EMIT} and non-graphic characters:
                   13702: @cindex @code{EMIT} and non-graphic characters
                   13703: @cindex non-graphic characters and @code{EMIT}
                   13704: The character is output using the C library function (actually, macro)
                   13705: @code{putc}.
                   13706: 
                   13707: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   13708: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   13709: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   13710: @cindex @code{ACCEPT}, editing
                   13711: @cindex @code{EXPECT}, editing
                   13712: This is modeled on the GNU readline library (@pxref{Readline
                   13713: Interaction, , Command Line Editing, readline, The GNU Readline
                   13714: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   13715: producing a full word completion every time you type it (instead of
1.28      crook    13716: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    13717: 
                   13718: @item character set:
                   13719: @cindex character set
                   13720: The character set of your computer and display device. Gforth is
                   13721: 8-bit-clean (but some other component in your system may make trouble).
                   13722: 
                   13723: @item Character-aligned address requirements:
                   13724: @cindex character-aligned address requirements
                   13725: installation-dependent. Currently a character is represented by a C
                   13726: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   13727: (Comments on that requested).
                   13728: 
                   13729: @item character-set extensions and matching of names:
                   13730: @cindex character-set extensions and matching of names
1.26      crook    13731: @cindex case-sensitivity for name lookup
                   13732: @cindex name lookup, case-sensitivity
                   13733: @cindex locale and case-sensitivity
1.21      crook    13734: Any character except the ASCII NUL character can be used in a
1.1       anton    13735: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47      crook    13736: matching is performed using the C library function @code{strncasecmp}, whose
1.1       anton    13737: function is probably influenced by the locale. E.g., the @code{C} locale
                   13738: does not know about accents and umlauts, so they are matched
                   13739: case-sensitively in that locale. For portability reasons it is best to
                   13740: write programs such that they work in the @code{C} locale. Then one can
                   13741: use libraries written by a Polish programmer (who might use words
                   13742: containing ISO Latin-2 encoded characters) and by a French programmer
                   13743: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   13744: funny results for some of the words (which ones, depends on the font you
                   13745: are using)). Also, the locale you prefer may not be available in other
                   13746: operating systems. Hopefully, Unicode will solve these problems one day.
                   13747: 
                   13748: @item conditions under which control characters match a space delimiter:
                   13749: @cindex space delimiters
                   13750: @cindex control characters as delimiters
1.117     anton    13751: If @code{word} is called with the space character as a delimiter, all
1.1       anton    13752: white-space characters (as identified by the C macro @code{isspace()})
1.117     anton    13753: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138     anton    13754: delimiters.  @code{Parse-name}, which is used by the outer
1.1       anton    13755: interpreter (aka text interpreter) by default, treats all white-space
                   13756: characters as delimiters.
                   13757: 
1.26      crook    13758: @item format of the control-flow stack:
                   13759: @cindex control-flow stack, format
                   13760: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    13761: stack item in cells is given by the constant @code{cs-item-size}. At the
                   13762: time of this writing, an item consists of a (pointer to a) locals list
                   13763: (third), an address in the code (second), and a tag for identifying the
                   13764: item (TOS). The following tags are used: @code{defstart},
                   13765: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   13766: @code{scopestart}.
                   13767: 
                   13768: @item conversion of digits > 35
                   13769: @cindex digits > 35
                   13770: The characters @code{[\]^_'} are the digits with the decimal value
                   13771: 36@minus{}41. There is no way to input many of the larger digits.
                   13772: 
                   13773: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   13774: @cindex @code{EXPECT}, display after end of input
                   13775: @cindex @code{ACCEPT}, display after end of input
                   13776: The cursor is moved to the end of the entered string. If the input is
                   13777: terminated using the @kbd{Return} key, a space is typed.
                   13778: 
                   13779: @item exception abort sequence of @code{ABORT"}:
                   13780: @cindex exception abort sequence of @code{ABORT"}
                   13781: @cindex @code{ABORT"}, exception abort sequence
                   13782: The error string is stored into the variable @code{"error} and a
                   13783: @code{-2 throw} is performed.
                   13784: 
                   13785: @item input line terminator:
                   13786: @cindex input line terminator
                   13787: @cindex line terminator on input
1.26      crook    13788: @cindex newline character on input
1.1       anton    13789: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   13790: lines. One of these characters is typically produced when you type the
                   13791: @kbd{Enter} or @kbd{Return} key.
                   13792: 
                   13793: @item maximum size of a counted string:
                   13794: @cindex maximum size of a counted string
                   13795: @cindex counted string, maximum size
                   13796: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79      anton    13797: on all platforms, but this may change.
1.1       anton    13798: 
                   13799: @item maximum size of a parsed string:
                   13800: @cindex maximum size of a parsed string
                   13801: @cindex parsed string, maximum size
                   13802: Given by the constant @code{/line}. Currently 255 characters.
                   13803: 
                   13804: @item maximum size of a definition name, in characters:
                   13805: @cindex maximum size of a definition name, in characters
                   13806: @cindex name, maximum length
1.113     anton    13807: MAXU/8
1.1       anton    13808: 
                   13809: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   13810: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   13811: @cindex @code{ENVIRONMENT?} string length, maximum
1.113     anton    13812: MAXU/8
1.1       anton    13813: 
                   13814: @item method of selecting the user input device:
                   13815: @cindex user input device, method of selecting
                   13816: The user input device is the standard input. There is currently no way to
                   13817: change it from within Gforth. However, the input can typically be
                   13818: redirected in the command line that starts Gforth.
                   13819: 
                   13820: @item method of selecting the user output device:
                   13821: @cindex user output device, method of selecting
                   13822: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    13823: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   13824: output when the user output device is a terminal, otherwise the output
                   13825: is buffered.
1.1       anton    13826: 
                   13827: @item methods of dictionary compilation:
                   13828: What are we expected to document here?
                   13829: 
                   13830: @item number of bits in one address unit:
                   13831: @cindex number of bits in one address unit
                   13832: @cindex address unit, size in bits
                   13833: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79      anton    13834: platforms.
1.1       anton    13835: 
                   13836: @item number representation and arithmetic:
                   13837: @cindex number representation and arithmetic
1.79      anton    13838: Processor-dependent. Binary two's complement on all current platforms.
1.1       anton    13839: 
                   13840: @item ranges for integer types:
                   13841: @cindex ranges for integer types
                   13842: @cindex integer types, ranges
                   13843: Installation-dependent. Make environmental queries for @code{MAX-N},
                   13844: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   13845: unsigned (and positive) types is 0. The lower bound for signed types on
                   13846: two's complement and one's complement machines machines can be computed
                   13847: by adding 1 to the upper bound.
                   13848: 
                   13849: @item read-only data space regions:
                   13850: @cindex read-only data space regions
                   13851: @cindex data-space, read-only regions
                   13852: The whole Forth data space is writable.
                   13853: 
                   13854: @item size of buffer at @code{WORD}:
                   13855: @cindex size of buffer at @code{WORD}
                   13856: @cindex @code{WORD} buffer size
                   13857: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   13858: shared with the pictured numeric output string. If overwriting
                   13859: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   13860: space, although only as much can be sensibly used as fits in a counted
                   13861: string.
                   13862: 
                   13863: @item size of one cell in address units:
                   13864: @cindex cell size
                   13865: @code{1 cells .}.
                   13866: 
                   13867: @item size of one character in address units:
                   13868: @cindex char size
1.79      anton    13869: @code{1 chars .}. 1 on all current platforms.
1.1       anton    13870: 
                   13871: @item size of the keyboard terminal buffer:
                   13872: @cindex size of the keyboard terminal buffer
                   13873: @cindex terminal buffer, size
                   13874: Varies. You can determine the size at a specific time using @code{lp@@
                   13875: tib - .}. It is shared with the locals stack and TIBs of files that
                   13876: include the current file. You can change the amount of space for TIBs
                   13877: and locals stack at Gforth startup with the command line option
                   13878: @code{-l}.
                   13879: 
                   13880: @item size of the pictured numeric output buffer:
                   13881: @cindex size of the pictured numeric output buffer
                   13882: @cindex pictured numeric output buffer, size
                   13883: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   13884: shared with @code{WORD}.
                   13885: 
                   13886: @item size of the scratch area returned by @code{PAD}:
                   13887: @cindex size of the scratch area returned by @code{PAD}
                   13888: @cindex @code{PAD} size
                   13889: The remainder of dictionary space. @code{unused pad here - - .}.
                   13890: 
                   13891: @item system case-sensitivity characteristics:
                   13892: @cindex case-sensitivity characteristics
1.26      crook    13893: Dictionary searches are case-insensitive (except in
1.1       anton    13894: @code{TABLE}s). However, as explained above under @i{character-set
                   13895: extensions}, the matching for non-ASCII characters is determined by the
                   13896: locale you are using. In the default @code{C} locale all non-ASCII
                   13897: characters are matched case-sensitively.
                   13898: 
                   13899: @item system prompt:
                   13900: @cindex system prompt
                   13901: @cindex prompt
                   13902: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   13903: 
                   13904: @item division rounding:
                   13905: @cindex division rounding
1.166     anton    13906: The ordinary division words @code{/ mod /mod */ */mod} perform floored
                   13907: division (with the default installation of Gforth).  You can check
                   13908: this with @code{s" floored" environment? drop .}.  If you write
                   13909: programs that need a specific division rounding, best use
                   13910: @code{fm/mod} or @code{sm/rem} for portability.
1.1       anton    13911: 
                   13912: @item values of @code{STATE} when true:
                   13913: @cindex @code{STATE} values
                   13914: -1.
                   13915: 
                   13916: @item values returned after arithmetic overflow:
                   13917: On two's complement machines, arithmetic is performed modulo
                   13918: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164     anton    13919: arithmetic (with appropriate mapping for signed types). Division by
                   13920: zero typically results in a @code{-55 throw} (Floating-point
                   13921: unidentified fault) or @code{-10 throw} (divide by zero).  Integer
1.166     anton    13922: division overflow can result in these throws, or in @code{-11 throw};
                   13923: in @code{gforth-fast} division overflow and divide by zero may also
                   13924: result in returning bogus results without producing an exception.
1.1       anton    13925: 
                   13926: @item whether the current definition can be found after @t{DOES>}:
                   13927: @cindex @t{DOES>}, visibility of current definition
                   13928: No.
                   13929: 
                   13930: @end table
                   13931: 
                   13932: @c ---------------------------------------------------------------------
                   13933: @node core-ambcond, core-other, core-idef, The Core Words
                   13934: @subsection Ambiguous conditions
                   13935: @c ---------------------------------------------------------------------
                   13936: @cindex core words, ambiguous conditions
                   13937: @cindex ambiguous conditions, core words
                   13938: 
                   13939: @table @i
                   13940: 
                   13941: @item a name is neither a word nor a number:
                   13942: @cindex name not found
1.26      crook    13943: @cindex undefined word
1.80      anton    13944: @code{-13 throw} (Undefined word).
1.1       anton    13945: 
                   13946: @item a definition name exceeds the maximum length allowed:
1.26      crook    13947: @cindex word name too long
1.1       anton    13948: @code{-19 throw} (Word name too long)
                   13949: 
                   13950: @item addressing a region not inside the various data spaces of the forth system:
                   13951: @cindex Invalid memory address
1.32      anton    13952: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    13953: typically readable. Accessing other addresses gives results dependent on
                   13954: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   13955: address).
                   13956: 
                   13957: @item argument type incompatible with parameter:
1.26      crook    13958: @cindex argument type mismatch
1.1       anton    13959: This is usually not caught. Some words perform checks, e.g., the control
                   13960: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   13961: mismatch).
                   13962: 
                   13963: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   13964: @cindex Interpreting a compile-only word, for @code{'} etc.
                   13965: @cindex execution token of words with undefined execution semantics
                   13966: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   13967: get an execution token for @code{compile-only-error} (which performs a
                   13968: @code{-14 throw} when executed).
                   13969: 
                   13970: @item dividing by zero:
                   13971: @cindex dividing by zero
                   13972: @cindex floating point unidentified fault, integer division
1.80      anton    13973: On some platforms, this produces a @code{-10 throw} (Division by
1.24      anton    13974: zero); on other systems, this typically results in a @code{-55 throw}
                   13975: (Floating-point unidentified fault).
1.1       anton    13976: 
                   13977: @item insufficient data stack or return stack space:
                   13978: @cindex insufficient data stack or return stack space
                   13979: @cindex stack overflow
1.26      crook    13980: @cindex address alignment exception, stack overflow
1.1       anton    13981: @cindex Invalid memory address, stack overflow
                   13982: Depending on the operating system, the installation, and the invocation
                   13983: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    13984: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   13985: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   13986: throw} (Invalid memory address) (depending on the platform and how you
                   13987: achieved the overflow) as soon as the overflow happens. If it is not
                   13988: checked, overflows typically result in mysterious illegal memory
                   13989: accesses, producing @code{-9 throw} (Invalid memory address) or
                   13990: @code{-23 throw} (Address alignment exception); they might also destroy
                   13991: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   13992: various errors in these words.
1.1       anton    13993: 
                   13994: @item insufficient space for loop control parameters:
                   13995: @cindex insufficient space for loop control parameters
1.80      anton    13996: Like other return stack overflows.
1.1       anton    13997: 
                   13998: @item insufficient space in the dictionary:
                   13999: @cindex insufficient space in the dictionary
                   14000: @cindex dictionary overflow
1.12      anton    14001: If you try to allot (either directly with @code{allot}, or indirectly
                   14002: with @code{,}, @code{create} etc.) more memory than available in the
                   14003: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   14004: to access memory beyond the end of the dictionary, the results are
                   14005: similar to stack overflows.
1.1       anton    14006: 
                   14007: @item interpreting a word with undefined interpretation semantics:
                   14008: @cindex interpreting a word with undefined interpretation semantics
                   14009: @cindex Interpreting a compile-only word
                   14010: For some words, we have defined interpretation semantics. For the
                   14011: others: @code{-14 throw} (Interpreting a compile-only word).
                   14012: 
                   14013: @item modifying the contents of the input buffer or a string literal:
                   14014: @cindex modifying the contents of the input buffer or a string literal
                   14015: These are located in writable memory and can be modified.
                   14016: 
                   14017: @item overflow of the pictured numeric output string:
                   14018: @cindex overflow of the pictured numeric output string
                   14019: @cindex pictured numeric output string, overflow
1.24      anton    14020: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    14021: 
                   14022: @item parsed string overflow:
                   14023: @cindex parsed string overflow
                   14024: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   14025: 
                   14026: @item producing a result out of range:
                   14027: @cindex result out of range
                   14028: On two's complement machines, arithmetic is performed modulo
                   14029: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166     anton    14030: arithmetic (with appropriate mapping for signed types). Division by
                   14031: zero typically results in a @code{-10 throw} (divide by zero) or
                   14032: @code{-55 throw} (floating point unidentified fault). Overflow on
                   14033: division may result in these errors or in @code{-11 throw} (result out
                   14034: of range).  @code{Gforth-fast} may silently produce bogus results on
                   14035: division overflow or division by zero.  @code{Convert} and
1.24      anton    14036: @code{>number} currently overflow silently.
1.1       anton    14037: 
                   14038: @item reading from an empty data or return stack:
                   14039: @cindex stack empty
                   14040: @cindex stack underflow
1.24      anton    14041: @cindex return stack underflow
1.1       anton    14042: The data stack is checked by the outer (aka text) interpreter after
                   14043: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   14044: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    14045: depending on operating system, installation, and invocation. If they are
                   14046: caught by a check, they typically result in @code{-4 throw} (Stack
                   14047: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   14048: (Invalid memory address), depending on the platform and which stack
                   14049: underflows and by how much. Note that even if the system uses checking
                   14050: (through the MMU), your program may have to underflow by a significant
                   14051: number of stack items to trigger the reaction (the reason for this is
                   14052: that the MMU, and therefore the checking, works with a page-size
                   14053: granularity).  If there is no checking, the symptoms resulting from an
                   14054: underflow are similar to those from an overflow.  Unbalanced return
1.80      anton    14055: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24      anton    14056: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   14057: throw}).
1.1       anton    14058: 
                   14059: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   14060: @cindex unexpected end of the input buffer
                   14061: @cindex zero-length string as a name
                   14062: @cindex Attempt to use zero-length string as a name
                   14063: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   14064: use zero-length string as a name). Words like @code{'} probably will not
                   14065: find what they search. Note that it is possible to create zero-length
                   14066: names with @code{nextname} (should it not?).
                   14067: 
                   14068: @item @code{>IN} greater than input buffer:
                   14069: @cindex @code{>IN} greater than input buffer
                   14070: The next invocation of a parsing word returns a string with length 0.
                   14071: 
                   14072: @item @code{RECURSE} appears after @code{DOES>}:
                   14073: @cindex @code{RECURSE} appears after @code{DOES>}
                   14074: Compiles a recursive call to the defining word, not to the defined word.
                   14075: 
                   14076: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   14077: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    14078: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    14079: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   14080: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   14081: the end of the file was reached), its source-id may be
                   14082: reused. Therefore, restoring an input source specification referencing a
                   14083: closed file may lead to unpredictable results instead of a @code{-12
                   14084: THROW}.
                   14085: 
                   14086: In the future, Gforth may be able to restore input source specifications
                   14087: from other than the current input source.
                   14088: 
                   14089: @item data space containing definitions gets de-allocated:
                   14090: @cindex data space containing definitions gets de-allocated
                   14091: Deallocation with @code{allot} is not checked. This typically results in
                   14092: memory access faults or execution of illegal instructions.
                   14093: 
                   14094: @item data space read/write with incorrect alignment:
                   14095: @cindex data space read/write with incorrect alignment
                   14096: @cindex alignment faults
1.26      crook    14097: @cindex address alignment exception
1.1       anton    14098: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    14099: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    14100: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   14101: (Invalid memory address). There are reportedly some processors with
1.12      anton    14102: alignment restrictions that do not report violations.
1.1       anton    14103: 
                   14104: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   14105: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   14106: Like other alignment errors.
                   14107: 
                   14108: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   14109: Like other stack underflows.
                   14110: 
                   14111: @item loop control parameters not available:
                   14112: @cindex loop control parameters not available
                   14113: Not checked. The counted loop words simply assume that the top of return
                   14114: stack items are loop control parameters and behave accordingly.
                   14115: 
                   14116: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   14117: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   14118: @cindex last word was headerless
                   14119: @code{abort" last word was headerless"}.
                   14120: 
                   14121: @item name not defined by @code{VALUE} used by @code{TO}:
                   14122: @cindex name not defined by @code{VALUE} used by @code{TO}
                   14123: @cindex @code{TO} on non-@code{VALUE}s
                   14124: @cindex Invalid name argument, @code{TO}
                   14125: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   14126: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   14127: 
                   14128: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   14129: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    14130: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    14131: @code{-13 throw} (Undefined word)
                   14132: 
                   14133: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   14134: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   14135: Gforth behaves as if they were of the same type. I.e., you can predict
                   14136: the behaviour by interpreting all parameters as, e.g., signed.
                   14137: 
                   14138: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   14139: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   14140: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   14141: compilation semantics of @code{TO}.
                   14142: 
                   14143: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    14144: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    14145: @cindex @code{WORD}, string overflow
                   14146: Not checked. The string will be ok, but the count will, of course,
                   14147: contain only the least significant bits of the length.
                   14148: 
                   14149: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   14150: @cindex @code{LSHIFT}, large shift counts
                   14151: @cindex @code{RSHIFT}, large shift counts
                   14152: Processor-dependent. Typical behaviours are returning 0 and using only
                   14153: the low bits of the shift count.
                   14154: 
                   14155: @item word not defined via @code{CREATE}:
                   14156: @cindex @code{>BODY} of non-@code{CREATE}d words
                   14157: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   14158: 
                   14159: @cindex @code{DOES>} of non-@code{CREATE}d words
                   14160: @code{DOES>} changes the execution semantics of the last defined word no
                   14161: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   14162: @code{CREATE , DOES>}.
                   14163: 
                   14164: @item words improperly used outside @code{<#} and @code{#>}:
                   14165: Not checked. As usual, you can expect memory faults.
                   14166: 
                   14167: @end table
                   14168: 
                   14169: 
                   14170: @c ---------------------------------------------------------------------
                   14171: @node core-other,  , core-ambcond, The Core Words
                   14172: @subsection Other system documentation
                   14173: @c ---------------------------------------------------------------------
                   14174: @cindex other system documentation, core words
                   14175: @cindex core words, other system documentation
                   14176: 
                   14177: @table @i
                   14178: @item nonstandard words using @code{PAD}:
                   14179: @cindex @code{PAD} use by nonstandard words
                   14180: None.
                   14181: 
                   14182: @item operator's terminal facilities available:
                   14183: @cindex operator's terminal facilities available
1.80      anton    14184: After processing the OS's command line, Gforth goes into interactive mode,
1.1       anton    14185: and you can give commands to Gforth interactively. The actual facilities
                   14186: available depend on how you invoke Gforth.
                   14187: 
                   14188: @item program data space available:
                   14189: @cindex program data space available
                   14190: @cindex data space available
                   14191: @code{UNUSED .} gives the remaining dictionary space. The total
                   14192: dictionary space can be specified with the @code{-m} switch
                   14193: (@pxref{Invoking Gforth}) when Gforth starts up.
                   14194: 
                   14195: @item return stack space available:
                   14196: @cindex return stack space available
                   14197: You can compute the total return stack space in cells with
                   14198: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   14199: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   14200: 
                   14201: @item stack space available:
                   14202: @cindex stack space available
                   14203: You can compute the total data stack space in cells with
                   14204: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   14205: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   14206: 
                   14207: @item system dictionary space required, in address units:
                   14208: @cindex system dictionary space required, in address units
                   14209: Type @code{here forthstart - .} after startup. At the time of this
                   14210: writing, this gives 80080 (bytes) on a 32-bit system.
                   14211: @end table
                   14212: 
                   14213: 
                   14214: @c =====================================================================
                   14215: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   14216: @section The optional Block word set
                   14217: @c =====================================================================
                   14218: @cindex system documentation, block words
                   14219: @cindex block words, system documentation
                   14220: 
                   14221: @menu
                   14222: * block-idef::                  Implementation Defined Options
                   14223: * block-ambcond::               Ambiguous Conditions               
                   14224: * block-other::                 Other System Documentation                 
                   14225: @end menu
                   14226: 
                   14227: 
                   14228: @c ---------------------------------------------------------------------
                   14229: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   14230: @subsection Implementation Defined Options
                   14231: @c ---------------------------------------------------------------------
                   14232: @cindex implementation-defined options, block words
                   14233: @cindex block words, implementation-defined options
                   14234: 
                   14235: @table @i
                   14236: @item the format for display by @code{LIST}:
                   14237: @cindex @code{LIST} display format
                   14238: First the screen number is displayed, then 16 lines of 64 characters,
                   14239: each line preceded by the line number.
                   14240: 
                   14241: @item the length of a line affected by @code{\}:
                   14242: @cindex length of a line affected by @code{\}
                   14243: @cindex @code{\}, line length in blocks
                   14244: 64 characters.
                   14245: @end table
                   14246: 
                   14247: 
                   14248: @c ---------------------------------------------------------------------
                   14249: @node block-ambcond, block-other, block-idef, The optional Block word set
                   14250: @subsection Ambiguous conditions
                   14251: @c ---------------------------------------------------------------------
                   14252: @cindex block words, ambiguous conditions
                   14253: @cindex ambiguous conditions, block words
                   14254: 
                   14255: @table @i
                   14256: @item correct block read was not possible:
                   14257: @cindex block read not possible
                   14258: Typically results in a @code{throw} of some OS-derived value (between
                   14259: -512 and -2048). If the blocks file was just not long enough, blanks are
                   14260: supplied for the missing portion.
                   14261: 
                   14262: @item I/O exception in block transfer:
                   14263: @cindex I/O exception in block transfer
                   14264: @cindex block transfer, I/O exception
                   14265: Typically results in a @code{throw} of some OS-derived value (between
                   14266: -512 and -2048).
                   14267: 
                   14268: @item invalid block number:
                   14269: @cindex invalid block number
                   14270: @cindex block number invalid
                   14271: @code{-35 throw} (Invalid block number)
                   14272: 
                   14273: @item a program directly alters the contents of @code{BLK}:
                   14274: @cindex @code{BLK}, altering @code{BLK}
                   14275: The input stream is switched to that other block, at the same
                   14276: position. If the storing to @code{BLK} happens when interpreting
                   14277: non-block input, the system will get quite confused when the block ends.
                   14278: 
                   14279: @item no current block buffer for @code{UPDATE}:
                   14280: @cindex @code{UPDATE}, no current block buffer
                   14281: @code{UPDATE} has no effect.
                   14282: 
                   14283: @end table
                   14284: 
                   14285: @c ---------------------------------------------------------------------
                   14286: @node block-other,  , block-ambcond, The optional Block word set
                   14287: @subsection Other system documentation
                   14288: @c ---------------------------------------------------------------------
                   14289: @cindex other system documentation, block words
                   14290: @cindex block words, other system documentation
                   14291: 
                   14292: @table @i
                   14293: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   14294: No restrictions (yet).
                   14295: 
                   14296: @item the number of blocks available for source and data:
                   14297: depends on your disk space.
                   14298: 
                   14299: @end table
                   14300: 
                   14301: 
                   14302: @c =====================================================================
                   14303: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   14304: @section The optional Double Number word set
                   14305: @c =====================================================================
                   14306: @cindex system documentation, double words
                   14307: @cindex double words, system documentation
                   14308: 
                   14309: @menu
                   14310: * double-ambcond::              Ambiguous Conditions              
                   14311: @end menu
                   14312: 
                   14313: 
                   14314: @c ---------------------------------------------------------------------
                   14315: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   14316: @subsection Ambiguous conditions
                   14317: @c ---------------------------------------------------------------------
                   14318: @cindex double words, ambiguous conditions
                   14319: @cindex ambiguous conditions, double words
                   14320: 
                   14321: @table @i
1.29      crook    14322: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   14323: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   14324: The least significant cell of @i{d} is produced.
1.1       anton    14325: 
                   14326: @end table
                   14327: 
                   14328: 
                   14329: @c =====================================================================
                   14330: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   14331: @section The optional Exception word set
                   14332: @c =====================================================================
                   14333: @cindex system documentation, exception words
                   14334: @cindex exception words, system documentation
                   14335: 
                   14336: @menu
                   14337: * exception-idef::              Implementation Defined Options              
                   14338: @end menu
                   14339: 
                   14340: 
                   14341: @c ---------------------------------------------------------------------
                   14342: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   14343: @subsection Implementation Defined Options
                   14344: @c ---------------------------------------------------------------------
                   14345: @cindex implementation-defined options, exception words
                   14346: @cindex exception words, implementation-defined options
                   14347: 
                   14348: @table @i
                   14349: @item @code{THROW}-codes used in the system:
                   14350: @cindex @code{THROW}-codes used in the system
                   14351: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    14352: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    14353: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   14354: allocation operations). The mapping from OS error numbers to throw codes
                   14355: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   14356: undefined OS errors produce a message with a strange number; e.g.,
                   14357: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   14358: @end table
                   14359: 
                   14360: @c =====================================================================
                   14361: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   14362: @section The optional Facility word set
                   14363: @c =====================================================================
                   14364: @cindex system documentation, facility words
                   14365: @cindex facility words, system documentation
                   14366: 
                   14367: @menu
                   14368: * facility-idef::               Implementation Defined Options               
                   14369: * facility-ambcond::            Ambiguous Conditions            
                   14370: @end menu
                   14371: 
                   14372: 
                   14373: @c ---------------------------------------------------------------------
                   14374: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   14375: @subsection Implementation Defined Options
                   14376: @c ---------------------------------------------------------------------
                   14377: @cindex implementation-defined options, facility words
                   14378: @cindex facility words, implementation-defined options
                   14379: 
                   14380: @table @i
                   14381: @item encoding of keyboard events (@code{EKEY}):
                   14382: @cindex keyboard events, encoding in @code{EKEY}
                   14383: @cindex @code{EKEY}, encoding of keyboard events
1.40      anton    14384: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41      anton    14385: Other keys are encoded with the constants @code{k-left}, @code{k-right},
                   14386: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
                   14387: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
                   14388: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40      anton    14389: 
1.1       anton    14390: 
                   14391: @item duration of a system clock tick:
                   14392: @cindex duration of a system clock tick
                   14393: @cindex clock tick duration
                   14394: System dependent. With respect to @code{MS}, the time is specified in
                   14395: microseconds. How well the OS and the hardware implement this, is
                   14396: another question.
                   14397: 
                   14398: @item repeatability to be expected from the execution of @code{MS}:
                   14399: @cindex repeatability to be expected from the execution of @code{MS}
                   14400: @cindex @code{MS}, repeatability to be expected
                   14401: System dependent. On Unix, a lot depends on load. If the system is
                   14402: lightly loaded, and the delay is short enough that Gforth does not get
                   14403: swapped out, the performance should be acceptable. Under MS-DOS and
                   14404: other single-tasking systems, it should be good.
                   14405: 
                   14406: @end table
                   14407: 
                   14408: 
                   14409: @c ---------------------------------------------------------------------
                   14410: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   14411: @subsection Ambiguous conditions
                   14412: @c ---------------------------------------------------------------------
                   14413: @cindex facility words, ambiguous conditions
                   14414: @cindex ambiguous conditions, facility words
                   14415: 
                   14416: @table @i
                   14417: @item @code{AT-XY} can't be performed on user output device:
                   14418: @cindex @code{AT-XY} can't be performed on user output device
                   14419: Largely terminal dependent. No range checks are done on the arguments.
                   14420: No errors are reported. You may see some garbage appearing, you may see
                   14421: simply nothing happen.
                   14422: 
                   14423: @end table
                   14424: 
                   14425: 
                   14426: @c =====================================================================
                   14427: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   14428: @section The optional File-Access word set
                   14429: @c =====================================================================
                   14430: @cindex system documentation, file words
                   14431: @cindex file words, system documentation
                   14432: 
                   14433: @menu
                   14434: * file-idef::                   Implementation Defined Options
                   14435: * file-ambcond::                Ambiguous Conditions                
                   14436: @end menu
                   14437: 
                   14438: @c ---------------------------------------------------------------------
                   14439: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   14440: @subsection Implementation Defined Options
                   14441: @c ---------------------------------------------------------------------
                   14442: @cindex implementation-defined options, file words
                   14443: @cindex file words, implementation-defined options
                   14444: 
                   14445: @table @i
                   14446: @item file access methods used:
                   14447: @cindex file access methods used
                   14448: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   14449: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   14450: @code{wb}): The file is cleared, if it exists, and created, if it does
                   14451: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   14452: @code{create-file} creates a file with 666 permissions modified by your
                   14453: umask.
                   14454: 
                   14455: @item file exceptions:
                   14456: @cindex file exceptions
                   14457: The file words do not raise exceptions (except, perhaps, memory access
                   14458: faults when you pass illegal addresses or file-ids).
                   14459: 
                   14460: @item file line terminator:
                   14461: @cindex file line terminator
                   14462: System-dependent. Gforth uses C's newline character as line
                   14463: terminator. What the actual character code(s) of this are is
                   14464: system-dependent.
                   14465: 
                   14466: @item file name format:
                   14467: @cindex file name format
                   14468: System dependent. Gforth just uses the file name format of your OS.
                   14469: 
                   14470: @item information returned by @code{FILE-STATUS}:
                   14471: @cindex @code{FILE-STATUS}, returned information
                   14472: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   14473: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   14474: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   14475: along with the returned mode.
                   14476: 
                   14477: @item input file state after an exception when including source:
                   14478: @cindex exception when including source
                   14479: All files that are left via the exception are closed.
                   14480: 
1.29      crook    14481: @item @i{ior} values and meaning:
                   14482: @cindex @i{ior} values and meaning
1.68      anton    14483: @cindex @i{wior} values and meaning
1.29      crook    14484: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    14485: intended as throw codes. They typically are in the range
                   14486: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    14487: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    14488: 
                   14489: @item maximum depth of file input nesting:
                   14490: @cindex maximum depth of file input nesting
                   14491: @cindex file input nesting, maximum depth
                   14492: limited by the amount of return stack, locals/TIB stack, and the number
                   14493: of open files available. This should not give you troubles.
                   14494: 
                   14495: @item maximum size of input line:
                   14496: @cindex maximum size of input line
                   14497: @cindex input line size, maximum
                   14498: @code{/line}. Currently 255.
                   14499: 
                   14500: @item methods of mapping block ranges to files:
                   14501: @cindex mapping block ranges to files
                   14502: @cindex files containing blocks
                   14503: @cindex blocks in files
                   14504: By default, blocks are accessed in the file @file{blocks.fb} in the
                   14505: current working directory. The file can be switched with @code{USE}.
                   14506: 
                   14507: @item number of string buffers provided by @code{S"}:
                   14508: @cindex @code{S"}, number of string buffers
                   14509: 1
                   14510: 
                   14511: @item size of string buffer used by @code{S"}:
                   14512: @cindex @code{S"}, size of string buffer
                   14513: @code{/line}. currently 255.
                   14514: 
                   14515: @end table
                   14516: 
                   14517: @c ---------------------------------------------------------------------
                   14518: @node file-ambcond,  , file-idef, The optional File-Access word set
                   14519: @subsection Ambiguous conditions
                   14520: @c ---------------------------------------------------------------------
                   14521: @cindex file words, ambiguous conditions
                   14522: @cindex ambiguous conditions, file words
                   14523: 
                   14524: @table @i
                   14525: @item attempting to position a file outside its boundaries:
                   14526: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   14527: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   14528: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   14529: 
                   14530: @item attempting to read from file positions not yet written:
                   14531: @cindex reading from file positions not yet written
                   14532: End-of-file, i.e., zero characters are read and no error is reported.
                   14533: 
1.29      crook    14534: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   14535: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    14536: An appropriate exception may be thrown, but a memory fault or other
                   14537: problem is more probable.
                   14538: 
1.29      crook    14539: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   14540: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   14541: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   14542: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    14543: thrown.
                   14544: 
                   14545: @item named file cannot be opened (@code{INCLUDED}):
                   14546: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    14547: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    14548: 
                   14549: @item requesting an unmapped block number:
                   14550: @cindex unmapped block numbers
                   14551: There are no unmapped legal block numbers. On some operating systems,
                   14552: writing a block with a large number may overflow the file system and
                   14553: have an error message as consequence.
                   14554: 
                   14555: @item using @code{source-id} when @code{blk} is non-zero:
                   14556: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   14557: @code{source-id} performs its function. Typically it will give the id of
                   14558: the source which loaded the block. (Better ideas?)
                   14559: 
                   14560: @end table
                   14561: 
                   14562: 
                   14563: @c =====================================================================
                   14564: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   14565: @section The optional Floating-Point word set
                   14566: @c =====================================================================
                   14567: @cindex system documentation, floating-point words
                   14568: @cindex floating-point words, system documentation
                   14569: 
                   14570: @menu
                   14571: * floating-idef::               Implementation Defined Options
                   14572: * floating-ambcond::            Ambiguous Conditions            
                   14573: @end menu
                   14574: 
                   14575: 
                   14576: @c ---------------------------------------------------------------------
                   14577: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   14578: @subsection Implementation Defined Options
                   14579: @c ---------------------------------------------------------------------
                   14580: @cindex implementation-defined options, floating-point words
                   14581: @cindex floating-point words, implementation-defined options
                   14582: 
                   14583: @table @i
                   14584: @item format and range of floating point numbers:
                   14585: @cindex format and range of floating point numbers
                   14586: @cindex floating point numbers, format and range
                   14587: System-dependent; the @code{double} type of C.
                   14588: 
1.29      crook    14589: @item results of @code{REPRESENT} when @i{float} is out of range:
                   14590: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    14591: System dependent; @code{REPRESENT} is implemented using the C library
                   14592: function @code{ecvt()} and inherits its behaviour in this respect.
                   14593: 
                   14594: @item rounding or truncation of floating-point numbers:
                   14595: @cindex rounding of floating-point numbers
                   14596: @cindex truncation of floating-point numbers
                   14597: @cindex floating-point numbers, rounding or truncation
                   14598: System dependent; the rounding behaviour is inherited from the hosting C
                   14599: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   14600: nearest, and break ties by rounding to even (i.e., such that the last
                   14601: bit of the mantissa is 0).
                   14602: 
                   14603: @item size of floating-point stack:
                   14604: @cindex floating-point stack size
                   14605: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   14606: the floating-point stack (in floats). You can specify this on startup
                   14607: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   14608: 
                   14609: @item width of floating-point stack:
                   14610: @cindex floating-point stack width 
                   14611: @code{1 floats}.
                   14612: 
                   14613: @end table
                   14614: 
                   14615: 
                   14616: @c ---------------------------------------------------------------------
                   14617: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   14618: @subsection Ambiguous conditions
                   14619: @c ---------------------------------------------------------------------
                   14620: @cindex floating-point words, ambiguous conditions
                   14621: @cindex ambiguous conditions, floating-point words
                   14622: 
                   14623: @table @i
                   14624: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   14625: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   14626: System-dependent. Typically results in a @code{-23 THROW} like other
                   14627: alignment violations.
                   14628: 
                   14629: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   14630: @cindex @code{f@@} used with an address that is not float aligned
                   14631: @cindex @code{f!} used with an address that is not float aligned
                   14632: System-dependent. Typically results in a @code{-23 THROW} like other
                   14633: alignment violations.
                   14634: 
                   14635: @item floating-point result out of range:
                   14636: @cindex floating-point result out of range
1.80      anton    14637: System-dependent. Can result in a @code{-43 throw} (floating point
                   14638: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
                   14639: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1       anton    14640: unidentified fault), or can produce a special value representing, e.g.,
                   14641: Infinity.
                   14642: 
                   14643: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   14644: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   14645: System-dependent. Typically results in an alignment fault like other
                   14646: alignment violations.
                   14647: 
1.35      anton    14648: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   14649: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    14650: The floating-point number is converted into decimal nonetheless.
                   14651: 
                   14652: @item Both arguments are equal to zero (@code{FATAN2}):
                   14653: @cindex @code{FATAN2}, both arguments are equal to zero
                   14654: System-dependent. @code{FATAN2} is implemented using the C library
                   14655: function @code{atan2()}.
                   14656: 
1.29      crook    14657: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   14658: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   14659: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    14660: because of small errors and the tan will be a very large (or very small)
                   14661: but finite number.
                   14662: 
1.29      crook    14663: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   14664: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    14665: The result is rounded to the nearest float.
                   14666: 
                   14667: @item dividing by zero:
                   14668: @cindex dividing by zero, floating-point
                   14669: @cindex floating-point dividing by zero
                   14670: @cindex floating-point unidentified fault, FP divide-by-zero
1.80      anton    14671: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
                   14672: (floating point divide by zero) or @code{-55 throw} (Floating-point
                   14673: unidentified fault).
1.1       anton    14674: 
                   14675: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   14676: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   14677: System dependent. On IEEE-FP based systems the number is converted into
                   14678: an infinity.
                   14679: 
1.29      crook    14680: @item @i{float}<1 (@code{FACOSH}):
                   14681: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    14682: @cindex floating-point unidentified fault, @code{FACOSH}
1.80      anton    14683: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1       anton    14684: 
1.29      crook    14685: @item @i{float}=<-1 (@code{FLNP1}):
                   14686: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    14687: @cindex floating-point unidentified fault, @code{FLNP1}
1.80      anton    14688: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   14689: negative infinity for @i{float}=-1).
1.1       anton    14690: 
1.29      crook    14691: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   14692: @cindex @code{FLN}, @i{float}=<0
                   14693: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    14694: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80      anton    14695: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   14696: negative infinity for @i{float}=0).
1.1       anton    14697: 
1.29      crook    14698: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   14699: @cindex @code{FASINH}, @i{float}<0
                   14700: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    14701: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80      anton    14702: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
                   14703: @code{fasinh} some platforms produce a NaN, others a number (bug in the
                   14704: C library?).
1.1       anton    14705: 
1.29      crook    14706: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   14707: @cindex @code{FACOS}, |@i{float}|>1
                   14708: @cindex @code{FASIN}, |@i{float}|>1
                   14709: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    14710: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80      anton    14711: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1       anton    14712: 
1.29      crook    14713: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   14714: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    14715: @cindex floating-point unidentified fault, @code{F>D}
1.80      anton    14716: Platform-dependent; typically, some double number is produced and no
                   14717: error is reported.
1.1       anton    14718: 
                   14719: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   14720: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80      anton    14721: @code{Precision} characters of the numeric output area are used.  If
                   14722: @code{precision} is too high, these words will smash the data or code
                   14723: close to @code{here}.
1.1       anton    14724: @end table
                   14725: 
                   14726: @c =====================================================================
                   14727: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   14728: @section The optional Locals word set
                   14729: @c =====================================================================
                   14730: @cindex system documentation, locals words
                   14731: @cindex locals words, system documentation
                   14732: 
                   14733: @menu
                   14734: * locals-idef::                 Implementation Defined Options                 
                   14735: * locals-ambcond::              Ambiguous Conditions              
                   14736: @end menu
                   14737: 
                   14738: 
                   14739: @c ---------------------------------------------------------------------
                   14740: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   14741: @subsection Implementation Defined Options
                   14742: @c ---------------------------------------------------------------------
                   14743: @cindex implementation-defined options, locals words
                   14744: @cindex locals words, implementation-defined options
                   14745: 
                   14746: @table @i
                   14747: @item maximum number of locals in a definition:
                   14748: @cindex maximum number of locals in a definition
                   14749: @cindex locals, maximum number in a definition
                   14750: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   14751: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   14752: characters. The number of locals in a definition is bounded by the size
                   14753: of locals-buffer, which contains the names of the locals.
                   14754: 
                   14755: @end table
                   14756: 
                   14757: 
                   14758: @c ---------------------------------------------------------------------
                   14759: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   14760: @subsection Ambiguous conditions
                   14761: @c ---------------------------------------------------------------------
                   14762: @cindex locals words, ambiguous conditions
                   14763: @cindex ambiguous conditions, locals words
                   14764: 
                   14765: @table @i
                   14766: @item executing a named local in interpretation state:
                   14767: @cindex local in interpretation state
                   14768: @cindex Interpreting a compile-only word, for a local
                   14769: Locals have no interpretation semantics. If you try to perform the
                   14770: interpretation semantics, you will get a @code{-14 throw} somewhere
                   14771: (Interpreting a compile-only word). If you perform the compilation
                   14772: semantics, the locals access will be compiled (irrespective of state).
                   14773: 
1.29      crook    14774: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    14775: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   14776: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   14777: @cindex Invalid name argument, @code{TO}
                   14778: @code{-32 throw} (Invalid name argument)
                   14779: 
                   14780: @end table
                   14781: 
                   14782: 
                   14783: @c =====================================================================
                   14784: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   14785: @section The optional Memory-Allocation word set
                   14786: @c =====================================================================
                   14787: @cindex system documentation, memory-allocation words
                   14788: @cindex memory-allocation words, system documentation
                   14789: 
                   14790: @menu
                   14791: * memory-idef::                 Implementation Defined Options                 
                   14792: @end menu
                   14793: 
                   14794: 
                   14795: @c ---------------------------------------------------------------------
                   14796: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   14797: @subsection Implementation Defined Options
                   14798: @c ---------------------------------------------------------------------
                   14799: @cindex implementation-defined options, memory-allocation words
                   14800: @cindex memory-allocation words, implementation-defined options
                   14801: 
                   14802: @table @i
1.29      crook    14803: @item values and meaning of @i{ior}:
                   14804: @cindex  @i{ior} values and meaning
                   14805: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    14806: intended as throw codes. They typically are in the range
                   14807: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    14808: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    14809: 
                   14810: @end table
                   14811: 
                   14812: @c =====================================================================
                   14813: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   14814: @section The optional Programming-Tools word set
                   14815: @c =====================================================================
                   14816: @cindex system documentation, programming-tools words
                   14817: @cindex programming-tools words, system documentation
                   14818: 
                   14819: @menu
                   14820: * programming-idef::            Implementation Defined Options            
                   14821: * programming-ambcond::         Ambiguous Conditions         
                   14822: @end menu
                   14823: 
                   14824: 
                   14825: @c ---------------------------------------------------------------------
                   14826: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   14827: @subsection Implementation Defined Options
                   14828: @c ---------------------------------------------------------------------
                   14829: @cindex implementation-defined options, programming-tools words
                   14830: @cindex programming-tools words, implementation-defined options
                   14831: 
                   14832: @table @i
                   14833: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   14834: @cindex @code{;CODE} ending sequence
                   14835: @cindex @code{CODE} ending sequence
                   14836: @code{END-CODE}
                   14837: 
                   14838: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   14839: @cindex @code{;CODE}, processing input
                   14840: @cindex @code{CODE}, processing input
                   14841: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   14842: the input is processed by the text interpreter, (starting) in interpret
                   14843: state.
                   14844: 
                   14845: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   14846: @cindex @code{ASSEMBLER}, search order capability
                   14847: The ANS Forth search order word set.
                   14848: 
                   14849: @item source and format of display by @code{SEE}:
                   14850: @cindex @code{SEE}, source and format of output
1.80      anton    14851: The source for @code{see} is the executable code used by the inner
1.1       anton    14852: interpreter.  The current @code{see} tries to output Forth source code
1.80      anton    14853: (and on some platforms, assembly code for primitives) as well as
                   14854: possible.
1.1       anton    14855: 
                   14856: @end table
                   14857: 
                   14858: @c ---------------------------------------------------------------------
                   14859: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   14860: @subsection Ambiguous conditions
                   14861: @c ---------------------------------------------------------------------
                   14862: @cindex programming-tools words, ambiguous conditions
                   14863: @cindex ambiguous conditions, programming-tools words
                   14864: 
                   14865: @table @i
                   14866: 
1.21      crook    14867: @item deleting the compilation word list (@code{FORGET}):
                   14868: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    14869: Not implemented (yet).
                   14870: 
1.29      crook    14871: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   14872: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   14873: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    14874: @cindex control-flow stack underflow
                   14875: This typically results in an @code{abort"} with a descriptive error
                   14876: message (may change into a @code{-22 throw} (Control structure mismatch)
                   14877: in the future). You may also get a memory access error. If you are
                   14878: unlucky, this ambiguous condition is not caught.
                   14879: 
1.29      crook    14880: @item @i{name} can't be found (@code{FORGET}):
                   14881: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    14882: Not implemented (yet).
                   14883: 
1.29      crook    14884: @item @i{name} not defined via @code{CREATE}:
                   14885: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    14886: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   14887: the execution semantics of the last defined word no matter how it was
                   14888: defined.
                   14889: 
                   14890: @item @code{POSTPONE} applied to @code{[IF]}:
                   14891: @cindex @code{POSTPONE} applied to @code{[IF]}
                   14892: @cindex @code{[IF]} and @code{POSTPONE}
                   14893: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   14894: equivalent to @code{[IF]}.
                   14895: 
                   14896: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   14897: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   14898: Continue in the same state of conditional compilation in the next outer
                   14899: input source. Currently there is no warning to the user about this.
                   14900: 
                   14901: @item removing a needed definition (@code{FORGET}):
                   14902: @cindex @code{FORGET}, removing a needed definition
                   14903: Not implemented (yet).
                   14904: 
                   14905: @end table
                   14906: 
                   14907: 
                   14908: @c =====================================================================
                   14909: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   14910: @section The optional Search-Order word set
                   14911: @c =====================================================================
                   14912: @cindex system documentation, search-order words
                   14913: @cindex search-order words, system documentation
                   14914: 
                   14915: @menu
                   14916: * search-idef::                 Implementation Defined Options                 
                   14917: * search-ambcond::              Ambiguous Conditions              
                   14918: @end menu
                   14919: 
                   14920: 
                   14921: @c ---------------------------------------------------------------------
                   14922: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   14923: @subsection Implementation Defined Options
                   14924: @c ---------------------------------------------------------------------
                   14925: @cindex implementation-defined options, search-order words
                   14926: @cindex search-order words, implementation-defined options
                   14927: 
                   14928: @table @i
                   14929: @item maximum number of word lists in search order:
                   14930: @cindex maximum number of word lists in search order
                   14931: @cindex search order, maximum depth
                   14932: @code{s" wordlists" environment? drop .}. Currently 16.
                   14933: 
                   14934: @item minimum search order:
                   14935: @cindex minimum search order
                   14936: @cindex search order, minimum
                   14937: @code{root root}.
                   14938: 
                   14939: @end table
                   14940: 
                   14941: @c ---------------------------------------------------------------------
                   14942: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   14943: @subsection Ambiguous conditions
                   14944: @c ---------------------------------------------------------------------
                   14945: @cindex search-order words, ambiguous conditions
                   14946: @cindex ambiguous conditions, search-order words
                   14947: 
                   14948: @table @i
1.21      crook    14949: @item changing the compilation word list (during compilation):
                   14950: @cindex changing the compilation word list (during compilation)
                   14951: @cindex compilation word list, change before definition ends
                   14952: The word is entered into the word list that was the compilation word list
1.1       anton    14953: at the start of the definition. Any changes to the name field (e.g.,
                   14954: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116     anton    14955: are applied to the latest defined word (as reported by @code{latest} or
                   14956: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1       anton    14957: 
                   14958: @item search order empty (@code{previous}):
                   14959: @cindex @code{previous}, search order empty
1.26      crook    14960: @cindex vocstack empty, @code{previous}
1.1       anton    14961: @code{abort" Vocstack empty"}.
                   14962: 
                   14963: @item too many word lists in search order (@code{also}):
                   14964: @cindex @code{also}, too many word lists in search order
1.26      crook    14965: @cindex vocstack full, @code{also}
1.1       anton    14966: @code{abort" Vocstack full"}.
                   14967: 
                   14968: @end table
                   14969: 
                   14970: @c ***************************************************************
1.65      anton    14971: @node Standard vs Extensions, Model, ANS conformance, Top
                   14972: @chapter Should I use Gforth extensions?
                   14973: @cindex Gforth extensions
                   14974: 
                   14975: As you read through the rest of this manual, you will see documentation
                   14976: for @i{Standard} words, and documentation for some appealing Gforth
                   14977: @i{extensions}. You might ask yourself the question: @i{``Should I
                   14978: restrict myself to the standard, or should I use the extensions?''}
                   14979: 
                   14980: The answer depends on the goals you have for the program you are working
                   14981: on:
                   14982: 
                   14983: @itemize @bullet
                   14984: 
                   14985: @item Is it just for yourself or do you want to share it with others?
                   14986: 
                   14987: @item
                   14988: If you want to share it, do the others all use Gforth?
                   14989: 
                   14990: @item
                   14991: If it is just for yourself, do you want to restrict yourself to Gforth?
                   14992: 
                   14993: @end itemize
                   14994: 
                   14995: If restricting the program to Gforth is ok, then there is no reason not
                   14996: to use extensions.  It is still a good idea to keep to the standard
                   14997: where it is easy, in case you want to reuse these parts in another
                   14998: program that you want to be portable.
                   14999: 
                   15000: If you want to be able to port the program to other Forth systems, there
                   15001: are the following points to consider:
                   15002: 
                   15003: @itemize @bullet
                   15004: 
                   15005: @item
                   15006: Most Forth systems that are being maintained support the ANS Forth
                   15007: standard.  So if your program complies with the standard, it will be
                   15008: portable among many systems.
                   15009: 
                   15010: @item
                   15011: A number of the Gforth extensions can be implemented in ANS Forth using
                   15012: public-domain files provided in the @file{compat/} directory. These are
                   15013: mentioned in the text in passing.  There is no reason not to use these
                   15014: extensions, your program will still be ANS Forth compliant; just include
                   15015: the appropriate compat files with your program.
                   15016: 
                   15017: @item
                   15018: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                   15019: analyse your program and determine what non-Standard words it relies
                   15020: upon.  However, it does not check whether you use standard words in a
                   15021: non-standard way.
                   15022: 
                   15023: @item
                   15024: Some techniques are not standardized by ANS Forth, and are hard or
                   15025: impossible to implement in a standard way, but can be implemented in
                   15026: most Forth systems easily, and usually in similar ways (e.g., accessing
                   15027: word headers).  Forth has a rich historical precedent for programmers
                   15028: taking advantage of implementation-dependent features of their tools
                   15029: (for example, relying on a knowledge of the dictionary
                   15030: structure). Sometimes these techniques are necessary to extract every
                   15031: last bit of performance from the hardware, sometimes they are just a
                   15032: programming shorthand.
                   15033: 
                   15034: @item
                   15035: Does using a Gforth extension save more work than the porting this part
                   15036: to other Forth systems (if any) will cost?
                   15037: 
                   15038: @item
                   15039: Is the additional functionality worth the reduction in portability and
                   15040: the additional porting problems?
                   15041: 
                   15042: @end itemize
                   15043: 
1.233     pazsan   15044: In order to perform these considerations, you need to know what's
1.65      anton    15045: standard and what's not.  This manual generally states if something is
1.81      anton    15046: non-standard, but the authoritative source is the
                   15047: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65      anton    15048: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
                   15049: into the thought processes of the technical committee.
                   15050: 
                   15051: Note also that portability between Forth systems is not the only
                   15052: portability issue; there is also the issue of portability between
                   15053: different platforms (processor/OS combinations).
                   15054: 
                   15055: @c ***************************************************************
                   15056: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1       anton    15057: @chapter Model
                   15058: 
                   15059: This chapter has yet to be written. It will contain information, on
                   15060: which internal structures you can rely.
                   15061: 
                   15062: @c ***************************************************************
                   15063: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   15064: @chapter Integrating Gforth into C programs
                   15065: 
                   15066: This is not yet implemented.
                   15067: 
                   15068: Several people like to use Forth as scripting language for applications
                   15069: that are otherwise written in C, C++, or some other language.
                   15070: 
                   15071: The Forth system ATLAST provides facilities for embedding it into
                   15072: applications; unfortunately it has several disadvantages: most
                   15073: importantly, it is not based on ANS Forth, and it is apparently dead
                   15074: (i.e., not developed further and not supported). The facilities
1.21      crook    15075: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    15076: making the switch should not be hard.
                   15077: 
                   15078: We also tried to design the interface such that it can easily be
                   15079: implemented by other Forth systems, so that we may one day arrive at a
                   15080: standardized interface. Such a standard interface would allow you to
                   15081: replace the Forth system without having to rewrite C code.
                   15082: 
                   15083: You embed the Gforth interpreter by linking with the library
                   15084: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   15085: global symbols in this library that belong to the interface, have the
                   15086: prefix @code{forth_}. (Global symbols that are used internally have the
                   15087: prefix @code{gforth_}).
                   15088: 
                   15089: You can include the declarations of Forth types and the functions and
                   15090: variables of the interface with @code{#include <forth.h>}.
                   15091: 
                   15092: Types.
                   15093: 
                   15094: Variables.
                   15095: 
                   15096: Data and FP Stack pointer. Area sizes.
                   15097: 
                   15098: functions.
                   15099: 
                   15100: forth_init(imagefile)
                   15101: forth_evaluate(string) exceptions?
                   15102: forth_goto(address) (or forth_execute(xt)?)
                   15103: forth_continue() (a corountining mechanism)
                   15104: 
                   15105: Adding primitives.
                   15106: 
                   15107: No checking.
                   15108: 
                   15109: Signals?
                   15110: 
                   15111: Accessing the Stacks
                   15112: 
1.26      crook    15113: @c ******************************************************************
1.1       anton    15114: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   15115: @chapter Emacs and Gforth
                   15116: @cindex Emacs and Gforth
                   15117: 
                   15118: @cindex @file{gforth.el}
                   15119: @cindex @file{forth.el}
                   15120: @cindex Rydqvist, Goran
1.107     dvdkhlng 15121: @cindex Kuehling, David
1.1       anton    15122: @cindex comment editing commands
                   15123: @cindex @code{\}, editing with Emacs
                   15124: @cindex debug tracer editing commands
                   15125: @cindex @code{~~}, removal with Emacs
                   15126: @cindex Forth mode in Emacs
1.107     dvdkhlng 15127: 
1.1       anton    15128: Gforth comes with @file{gforth.el}, an improved version of
                   15129: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    15130: improvements are:
                   15131: 
                   15132: @itemize @bullet
                   15133: @item
1.107     dvdkhlng 15134: A better handling of indentation.
                   15135: @item
                   15136: A custom hilighting engine for Forth-code.
1.26      crook    15137: @item
                   15138: Comment paragraph filling (@kbd{M-q})
                   15139: @item
                   15140: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   15141: @item
                   15142: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41      anton    15143: @item
                   15144: Support of the @code{info-lookup} feature for looking up the
                   15145: documentation of a word.
1.107     dvdkhlng 15146: @item
                   15147: Support for reading and writing blocks files.
1.26      crook    15148: @end itemize
                   15149: 
1.107     dvdkhlng 15150: To get a basic description of these features, enter Forth mode and
                   15151: type @kbd{C-h m}.
1.1       anton    15152: 
                   15153: @cindex source location of error or debugging output in Emacs
                   15154: @cindex error output, finding the source location in Emacs
                   15155: @cindex debugging output, finding the source location in Emacs
                   15156: In addition, Gforth supports Emacs quite well: The source code locations
                   15157: given in error messages, debugging output (from @code{~~}) and failed
                   15158: assertion messages are in the right format for Emacs' compilation mode
                   15159: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   15160: Manual}) so the source location corresponding to an error or other
                   15161: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   15162: @kbd{C-c C-c} for the error under the cursor).
                   15163: 
1.107     dvdkhlng 15164: @cindex viewing the documentation of a word in Emacs
                   15165: @cindex context-sensitive help
                   15166: Moreover, for words documented in this manual, you can look up the
                   15167: glossary entry quickly by using @kbd{C-h TAB}
                   15168: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
                   15169: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
                   15170: later and does not work for words containing @code{:}.
                   15171: 
                   15172: @menu
                   15173: * Installing gforth.el::        Making Emacs aware of Forth.
                   15174: * Emacs Tags::                  Viewing the source of a word in Emacs.
                   15175: * Hilighting::                  Making Forth code look prettier.
                   15176: * Auto-Indentation::            Customizing auto-indentation.
                   15177: * Blocks Files::                Reading and writing blocks files.
                   15178: @end menu
                   15179: 
                   15180: @c ----------------------------------
1.109     anton    15181: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107     dvdkhlng 15182: @section Installing gforth.el
                   15183: @cindex @file{.emacs}
                   15184: @cindex @file{gforth.el}, installation
                   15185: To make the features from @file{gforth.el} available in Emacs, add
                   15186: the following lines to your @file{.emacs} file:
                   15187: 
                   15188: @example
                   15189: (autoload 'forth-mode "gforth.el")
                   15190: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
                   15191:                            auto-mode-alist))
                   15192: (autoload 'forth-block-mode "gforth.el")
                   15193: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
                   15194:                            auto-mode-alist))
                   15195: (add-hook 'forth-mode-hook (function (lambda ()
                   15196:    ;; customize variables here:
                   15197:    (setq forth-indent-level 4)
                   15198:    (setq forth-minor-indent-level 2)
                   15199:    (setq forth-hilight-level 3)
                   15200:    ;;; ...
                   15201: )))
                   15202: @end example
                   15203: 
                   15204: @c ----------------------------------
                   15205: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
                   15206: @section Emacs Tags
1.1       anton    15207: @cindex @file{TAGS} file
                   15208: @cindex @file{etags.fs}
                   15209: @cindex viewing the source of a word in Emacs
1.43      anton    15210: @cindex @code{require}, placement in files
                   15211: @cindex @code{include}, placement in files
1.107     dvdkhlng 15212: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
                   15213: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    15214: contains the definitions of all words defined afterwards. You can then
1.107     dvdkhlng 15215: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1       anton    15216: several tags files at the same time (e.g., one for the Gforth sources
                   15217: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   15218: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   15219: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43      anton    15220: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
                   15221: with @file{etags.fs}, you should avoid putting definitions both before
                   15222: and after @code{require} etc., otherwise you will see the same file
                   15223: visited several times by commands like @code{tags-search}.
1.1       anton    15224: 
1.107     dvdkhlng 15225: @c ----------------------------------
                   15226: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
                   15227: @section Hilighting
                   15228: @cindex hilighting Forth code in Emacs
                   15229: @cindex highlighting Forth code in Emacs
                   15230: @file{gforth.el} comes with a custom source hilighting engine.  When
                   15231: you open a file in @code{forth-mode}, it will be completely parsed,
                   15232: assigning faces to keywords, comments, strings etc.  While you edit
                   15233: the file, modified regions get parsed and updated on-the-fly. 
                   15234: 
                   15235: Use the variable `forth-hilight-level' to change the level of
                   15236: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
                   15237: you set the hilighting level to 0, the parser will still work in the
                   15238: background, collecting information about whether regions of text are
                   15239: ``compiled'' or ``interpreted''.  Those information are required for
                   15240: auto-indentation to work properly.  Set `forth-disable-parser' to
                   15241: non-nil if your computer is too slow to handle parsing.  This will
                   15242: have an impact on the smartness of the auto-indentation engine,
                   15243: though.
                   15244: 
                   15245: Sometimes Forth sources define new features that should be hilighted,
                   15246: new control structures, defining-words etc.  You can use the variable
                   15247: `forth-custom-words' to make @code{forth-mode} hilight additional
                   15248: words and constructs.  See the docstring of `forth-words' for details
                   15249: (in Emacs, type @kbd{C-h v forth-words}).
                   15250: 
                   15251: `forth-custom-words' is meant to be customized in your
                   15252: @file{.emacs} file.  To customize hilighing in a file-specific manner,
                   15253: set `forth-local-words' in a local-variables section at the end of
                   15254: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
                   15255: 
                   15256: Example:
                   15257: @example
                   15258: 0 [IF]
                   15259:    Local Variables:
                   15260:    forth-local-words:
                   15261:       ((("t:") definition-starter (font-lock-keyword-face . 1)
                   15262:         "[ \t\n]" t name (font-lock-function-name-face . 3))
                   15263:        ((";t") definition-ender (font-lock-keyword-face . 1)))
                   15264:    End:
                   15265: [THEN]
                   15266: @end example
                   15267: 
                   15268: @c ----------------------------------
                   15269: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
                   15270: @section Auto-Indentation
                   15271: @cindex auto-indentation of Forth code in Emacs
                   15272: @cindex indentation of Forth code in Emacs
                   15273: @code{forth-mode} automatically tries to indent lines in a smart way,
                   15274: whenever you type @key{TAB} or break a line with @kbd{C-m}.
                   15275: 
                   15276: Simple customization can be achieved by setting
                   15277: `forth-indent-level' and `forth-minor-indent-level' in your
                   15278: @file{.emacs} file. For historical reasons @file{gforth.el} indents
                   15279: per default by multiples of 4 columns.  To use the more traditional
                   15280: 3-column indentation, add the following lines to your @file{.emacs}:
                   15281: 
                   15282: @example
                   15283: (add-hook 'forth-mode-hook (function (lambda ()
                   15284:    ;; customize variables here:
                   15285:    (setq forth-indent-level 3)
                   15286:    (setq forth-minor-indent-level 1)
                   15287: )))
                   15288: @end example
                   15289: 
                   15290: If you want indentation to recognize non-default words, customize it
                   15291: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
                   15292: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
                   15293: v forth-indent-words}).
                   15294: 
                   15295: To customize indentation in a file-specific manner, set
                   15296: `forth-local-indent-words' in a local-variables section at the end of
                   15297: your source file (@pxref{Local Variables in Files, Variables,,emacs,
                   15298: Emacs Manual}).
                   15299: 
                   15300: Example:
                   15301: @example
                   15302: 0 [IF]
                   15303:    Local Variables:
                   15304:    forth-local-indent-words:
                   15305:       ((("t:") (0 . 2) (0 . 2))
                   15306:        ((";t") (-2 . 0) (0 . -2)))
                   15307:    End:
                   15308: [THEN]
                   15309: @end example
                   15310: 
                   15311: @c ----------------------------------
1.109     anton    15312: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
1.107     dvdkhlng 15313: @section Blocks Files
                   15314: @cindex blocks files, use with Emacs
                   15315: @code{forth-mode} Autodetects blocks files by checking whether the
                   15316: length of the first line exceeds 1023 characters.  It then tries to
                   15317: convert the file into normal text format.  When you save the file, it
                   15318: will be written to disk as normal stream-source file.
                   15319: 
                   15320: If you want to write blocks files, use @code{forth-blocks-mode}.  It
                   15321: inherits all the features from @code{forth-mode}, plus some additions:
1.41      anton    15322: 
1.107     dvdkhlng 15323: @itemize @bullet
                   15324: @item
                   15325: Files are written to disk in blocks file format.
                   15326: @item
                   15327: Screen numbers are displayed in the mode line (enumerated beginning
                   15328: with the value of `forth-block-base')
                   15329: @item
                   15330: Warnings are displayed when lines exceed 64 characters.
                   15331: @item
                   15332: The beginning of the currently edited block is marked with an
                   15333: overlay-arrow. 
                   15334: @end itemize
1.41      anton    15335: 
1.107     dvdkhlng 15336: There are some restrictions you should be aware of.  When you open a
                   15337: blocks file that contains tabulator or newline characters, these
                   15338: characters will be translated into spaces when the file is written
                   15339: back to disk.  If tabs or newlines are encountered during blocks file
                   15340: reading, an error is output to the echo area. So have a look at the
                   15341: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1       anton    15342: 
1.107     dvdkhlng 15343: Please consult the docstring of @code{forth-blocks-mode} for more
                   15344: information by typing @kbd{C-h v forth-blocks-mode}).
1.1       anton    15345: 
1.26      crook    15346: @c ******************************************************************
1.1       anton    15347: @node Image Files, Engine, Emacs and Gforth, Top
                   15348: @chapter Image Files
1.26      crook    15349: @cindex image file
                   15350: @cindex @file{.fi} files
1.1       anton    15351: @cindex precompiled Forth code
                   15352: @cindex dictionary in persistent form
                   15353: @cindex persistent form of dictionary
                   15354: 
                   15355: An image file is a file containing an image of the Forth dictionary,
                   15356: i.e., compiled Forth code and data residing in the dictionary.  By
                   15357: convention, we use the extension @code{.fi} for image files.
                   15358: 
                   15359: @menu
1.18      anton    15360: * Image Licensing Issues::      Distribution terms for images.
                   15361: * Image File Background::       Why have image files?
1.67      anton    15362: * Non-Relocatable Image Files::  don't always work.
1.18      anton    15363: * Data-Relocatable Image Files::  are better.
1.67      anton    15364: * Fully Relocatable Image Files::  better yet.
1.18      anton    15365: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    15366: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    15367: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    15368: @end menu
                   15369: 
1.18      anton    15370: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   15371: @section Image Licensing Issues
                   15372: @cindex license for images
                   15373: @cindex image license
                   15374: 
                   15375: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   15376: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   15377: original image; i.e., according to copyright law it is a derived work of
                   15378: the original image.
                   15379: 
                   15380: Since Gforth is distributed under the GNU GPL, the newly created image
                   15381: falls under the GNU GPL, too. In particular, this means that if you
                   15382: distribute the image, you have to make all of the sources for the image
1.113     anton    15383: available, including those you wrote.  For details see @ref{Copying, ,
1.18      anton    15384: GNU General Public License (Section 3)}.
                   15385: 
                   15386: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   15387: contains only code compiled from the sources you gave it; if none of
                   15388: these sources is under the GPL, the terms discussed above do not apply
                   15389: to the image. However, if your image needs an engine (a gforth binary)
                   15390: that is under the GPL, you should make sure that you distribute both in
                   15391: a way that is at most a @emph{mere aggregation}, if you don't want the
                   15392: terms of the GPL to apply to the image.
                   15393: 
                   15394: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    15395: @section Image File Background
                   15396: @cindex image file background
                   15397: 
1.80      anton    15398: Gforth consists not only of primitives (in the engine), but also of
1.1       anton    15399: definitions written in Forth. Since the Forth compiler itself belongs to
                   15400: those definitions, it is not possible to start the system with the
1.80      anton    15401: engine and the Forth source alone. Therefore we provide the Forth
1.26      crook    15402: code as an image file in nearly executable form. When Gforth starts up,
                   15403: a C routine loads the image file into memory, optionally relocates the
                   15404: addresses, then sets up the memory (stacks etc.) according to
                   15405: information in the image file, and (finally) starts executing Forth
                   15406: code.
1.1       anton    15407: 
1.204     anton    15408: The default image file is @file{gforth.fi} (in the @code{GFORTHPATH}).
                   15409: You can use a different image by using the @code{-i},
                   15410: @code{--image-file} or @code{--appl-image} options (@pxref{Invoking
                   15411: Gforth}), e.g.:
                   15412: 
                   15413: @example
                   15414: gforth-fast -i myimage.fi
                   15415: @end example
                   15416: 
                   15417: There are different variants of image files, and they represent
                   15418: different compromises between the goals of making it easy to generate
                   15419: image files and making them portable.
1.1       anton    15420: 
                   15421: @cindex relocation at run-time
1.26      crook    15422: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    15423: run-time. This avoids many of the complications discussed below (image
                   15424: files are data relocatable without further ado), but costs performance
1.204     anton    15425: (one addition per memory access) and makes it difficult to pass
                   15426: addresses between Forth and library calls or other programs.
1.1       anton    15427: 
                   15428: @cindex relocation at load-time
1.26      crook    15429: By contrast, the Gforth loader performs relocation at image load time. The
                   15430: loader also has to replace tokens that represent primitive calls with the
1.1       anton    15431: appropriate code-field addresses (or code addresses in the case of
                   15432: direct threading).
                   15433: 
                   15434: There are three kinds of image files, with different degrees of
                   15435: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   15436: image files.
                   15437: 
                   15438: @cindex image file loader
                   15439: @cindex relocating loader
                   15440: @cindex loader for image files
                   15441: These image file variants have several restrictions in common; they are
                   15442: caused by the design of the image file loader:
                   15443: 
                   15444: @itemize @bullet
                   15445: @item
                   15446: There is only one segment; in particular, this means, that an image file
                   15447: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    15448: them). The contents of the stacks are not represented, either.
1.1       anton    15449: 
                   15450: @item
                   15451: The only kinds of relocation supported are: adding the same offset to
                   15452: all cells that represent data addresses; and replacing special tokens
                   15453: with code addresses or with pieces of machine code.
                   15454: 
                   15455: If any complex computations involving addresses are performed, the
                   15456: results cannot be represented in the image file. Several applications that
                   15457: use such computations come to mind:
1.204     anton    15458: 
1.1       anton    15459: @itemize @minus
                   15460: @item
                   15461: Hashing addresses (or data structures which contain addresses) for table
                   15462: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   15463: purpose, you will have no problem, because the hash tables are
                   15464: recomputed automatically when the system is started. If you use your own
                   15465: hash tables, you will have to do something similar.
                   15466: 
                   15467: @item
                   15468: There's a cute implementation of doubly-linked lists that uses
                   15469: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   15470: in the image file, and restore the doubly-linked representation on
                   15471: startup.@footnote{In my opinion, though, you should think thrice before
                   15472: using a doubly-linked list (whatever implementation).}
                   15473: 
                   15474: @item
                   15475: The code addresses of run-time routines like @code{docol:} cannot be
                   15476: represented in the image file (because their tokens would be replaced by
                   15477: machine code in direct threaded implementations). As a workaround,
                   15478: compute these addresses at run-time with @code{>code-address} from the
                   15479: executions tokens of appropriate words (see the definitions of
1.80      anton    15480: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1       anton    15481: 
                   15482: @item
                   15483: On many architectures addresses are represented in machine code in some
                   15484: shifted or mangled form. You cannot put @code{CODE} words that contain
                   15485: absolute addresses in this form in a relocatable image file. Workarounds
                   15486: are representing the address in some relative form (e.g., relative to
                   15487: the CFA, which is present in some register), or loading the address from
                   15488: a place where it is stored in a non-mangled form.
                   15489: @end itemize
                   15490: @end itemize
                   15491: 
                   15492: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   15493: @section Non-Relocatable Image Files
                   15494: @cindex non-relocatable image files
1.26      crook    15495: @cindex image file, non-relocatable
1.1       anton    15496: 
1.204     anton    15497: These files are simple memory dumps of the dictionary. They are
                   15498: specific to the executable (i.e., @file{gforth} file) they were
                   15499: created with. What's worse, they are specific to the place on which
                   15500: the dictionary resided when the image was created. Now, there is no
1.1       anton    15501: guarantee that the dictionary will reside at the same place the next
                   15502: time you start Gforth, so there's no guarantee that a non-relocatable
1.204     anton    15503: image will work the next time (Gforth will complain instead of
                   15504: crashing, though).  Indeed, on OSs with (enabled) address-space
                   15505: randomization non-relocatable images are unlikely to work.
1.1       anton    15506: 
1.204     anton    15507: You can create a non-relocatable image file with @code{savesystem}, e.g.:
1.1       anton    15508: 
1.204     anton    15509: @example
                   15510: gforth app.fs -e "savesystem app.fi bye"
                   15511: @end example
1.44      crook    15512: 
1.1       anton    15513: doc-savesystem
                   15514: 
1.44      crook    15515: 
1.1       anton    15516: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   15517: @section Data-Relocatable Image Files
                   15518: @cindex data-relocatable image files
1.26      crook    15519: @cindex image file, data-relocatable
1.1       anton    15520: 
1.204     anton    15521: These files contain relocatable data addresses, but fixed code
                   15522: addresses (instead of tokens). They are specific to the executable
                   15523: (i.e., @file{gforth} file) they were created with.  Also, they disable
                   15524: dynamic native code generation (typically a factor of 2 in speed).
                   15525: You get a data-relocatable image, if you pass the engine you want to
                   15526: use through the @code{GFORTHD} environment variable to @file{gforthmi}
                   15527: (@pxref{gforthmi}), e.g.
                   15528: 
                   15529: @example
                   15530: GFORTHD="/usr/bin/gforth-fast --no-dynamic" gforthmi myimage.fi source.fs
                   15531: @end example
                   15532: 
                   15533: Note that the @code{--no-dynamic} is required here for the image to
                   15534: work (otherwise it will contain references to dynamically generated
                   15535: code that is not saved in the image).
                   15536: 
1.1       anton    15537: 
                   15538: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   15539: @section Fully Relocatable Image Files
                   15540: @cindex fully relocatable image files
1.26      crook    15541: @cindex image file, fully relocatable
1.1       anton    15542: 
                   15543: @cindex @file{kern*.fi}, relocatability
                   15544: @cindex @file{gforth.fi}, relocatability
                   15545: These image files have relocatable data addresses, and tokens for code
                   15546: addresses. They can be used with different binaries (e.g., with and
                   15547: without debugging) on the same machine, and even across machines with
1.204     anton    15548: the same data formats (byte order, cell size, floating point format),
                   15549: and they work with dynamic native code generation.  However, they are
                   15550: usually specific to the version of Gforth they were created with. The
                   15551: files @file{gforth.fi} and @file{kernl*.fi} are fully relocatable.
1.1       anton    15552: 
                   15553: There are two ways to create a fully relocatable image file:
                   15554: 
                   15555: @menu
1.29      crook    15556: * gforthmi::                    The normal way
1.1       anton    15557: * cross.fs::                    The hard way
                   15558: @end menu
                   15559: 
                   15560: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   15561: @subsection @file{gforthmi}
                   15562: @cindex @file{comp-i.fs}
                   15563: @cindex @file{gforthmi}
                   15564: 
                   15565: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    15566: image @i{file} that contains everything you would load by invoking
                   15567: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    15568: @example
1.29      crook    15569: gforthmi @i{file} @i{options}
1.1       anton    15570: @end example
                   15571: 
                   15572: E.g., if you want to create an image @file{asm.fi} that has the file
                   15573: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   15574: like this:
                   15575: 
                   15576: @example
                   15577: gforthmi asm.fi asm.fs
                   15578: @end example
                   15579: 
1.27      crook    15580: @file{gforthmi} is implemented as a sh script and works like this: It
                   15581: produces two non-relocatable images for different addresses and then
                   15582: compares them. Its output reflects this: first you see the output (if
1.62      crook    15583: any) of the two Gforth invocations that produce the non-relocatable image
1.27      crook    15584: files, then you see the output of the comparing program: It displays the
                   15585: offset used for data addresses and the offset used for code addresses;
1.1       anton    15586: moreover, for each cell that cannot be represented correctly in the
1.44      crook    15587: image files, it displays a line like this:
1.1       anton    15588: 
                   15589: @example
                   15590:      78DC         BFFFFA50         BFFFFA40
                   15591: @end example
                   15592: 
                   15593: This means that at offset $78dc from @code{forthstart}, one input image
                   15594: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   15595: cannot be represented correctly in the output image, you should examine
                   15596: these places in the dictionary and verify that these cells are dead
                   15597: (i.e., not read before they are written).
1.39      anton    15598: 
                   15599: @cindex --application, @code{gforthmi} option
                   15600: If you insert the option @code{--application} in front of the image file
                   15601: name, you will get an image that uses the @code{--appl-image} option
                   15602: instead of the @code{--image-file} option (@pxref{Invoking
                   15603: Gforth}). When you execute such an image on Unix (by typing the image
                   15604: name as command), the Gforth engine will pass all options to the image
                   15605: instead of trying to interpret them as engine options.
1.1       anton    15606: 
1.27      crook    15607: If you type @file{gforthmi} with no arguments, it prints some usage
                   15608: instructions.
                   15609: 
1.1       anton    15610: @cindex @code{savesystem} during @file{gforthmi}
                   15611: @cindex @code{bye} during @file{gforthmi}
                   15612: @cindex doubly indirect threaded code
1.44      crook    15613: @cindex environment variables
                   15614: @cindex @code{GFORTHD} -- environment variable
                   15615: @cindex @code{GFORTH} -- environment variable
1.1       anton    15616: @cindex @code{gforth-ditc}
1.29      crook    15617: There are a few wrinkles: After processing the passed @i{options}, the
1.204     anton    15618: words @code{savesystem} and @code{bye} must be visible. A special
                   15619: doubly indirect threaded version of the @file{gforth} executable is
                   15620: used for creating the non-relocatable images; you can pass the exact
                   15621: filename of this executable through the environment variable
                   15622: @code{GFORTHD} (default: @file{gforth-ditc}); if you pass a version
                   15623: that is not doubly indirect threaded, you will not get a fully
                   15624: relocatable image, but a data-relocatable image
                   15625: (@pxref{Data-Relocatable Image Files}), because there is no code
                   15626: address offset). The normal @file{gforth} executable is used for
                   15627: creating the relocatable image; you can pass the exact filename of
                   15628: this executable through the environment variable @code{GFORTH}.
1.1       anton    15629: 
                   15630: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   15631: @subsection @file{cross.fs}
                   15632: @cindex @file{cross.fs}
                   15633: @cindex cross-compiler
                   15634: @cindex metacompiler
1.47      crook    15635: @cindex target compiler
1.1       anton    15636: 
                   15637: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47      crook    15638: programming language (@pxref{Cross Compiler}).
1.1       anton    15639: 
1.47      crook    15640: @code{cross} allows you to create image files for machines with
1.1       anton    15641: different data sizes and data formats than the one used for generating
                   15642: the image file. You can also use it to create an application image that
                   15643: does not contain a Forth compiler. These features are bought with
                   15644: restrictions and inconveniences in programming. E.g., addresses have to
                   15645: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   15646: order to make the code relocatable.
                   15647: 
                   15648: 
                   15649: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   15650: @section Stack and Dictionary Sizes
                   15651: @cindex image file, stack and dictionary sizes
                   15652: @cindex dictionary size default
                   15653: @cindex stack size default
                   15654: 
                   15655: If you invoke Gforth with a command line flag for the size
                   15656: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   15657: dictionary. If you save the dictionary with @code{savesystem} or create
                   15658: an image with @file{gforthmi}, this size will become the default
                   15659: for the resulting image file. E.g., the following will create a
1.21      crook    15660: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    15661: 
                   15662: @example
                   15663: gforthmi gforth.fi -m 1M
                   15664: @end example
                   15665: 
                   15666: In other words, if you want to set the default size for the dictionary
                   15667: and the stacks of an image, just invoke @file{gforthmi} with the
                   15668: appropriate options when creating the image.
                   15669: 
                   15670: @cindex stack size, cache-friendly
                   15671: Note: For cache-friendly behaviour (i.e., good performance), you should
                   15672: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   15673: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   15674: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   15675: 
                   15676: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   15677: @section Running Image Files
                   15678: @cindex running image files
                   15679: @cindex invoking image files
                   15680: @cindex image file invocation
                   15681: 
                   15682: @cindex -i, invoke image file
                   15683: @cindex --image file, invoke image file
1.29      crook    15684: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    15685: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   15686: @example
1.29      crook    15687: gforth -i @i{image}
1.1       anton    15688: @end example
                   15689: 
                   15690: @cindex executable image file
1.26      crook    15691: @cindex image file, executable
1.1       anton    15692: If your operating system supports starting scripts with a line of the
                   15693: form @code{#! ...}, you just have to type the image file name to start
                   15694: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    15695: just a convention). I.e., to run Gforth with the image file @i{image},
                   15696: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    15697: This works because every @code{.fi} file starts with a line of this
                   15698: format:
                   15699: 
                   15700: @example
                   15701: #! /usr/local/bin/gforth-0.4.0 -i
                   15702: @end example
                   15703: 
                   15704: The file and pathname for the Gforth engine specified on this line is
                   15705: the specific Gforth executable that it was built against; i.e. the value
                   15706: of the environment variable @code{GFORTH} at the time that
                   15707: @file{gforthmi} was executed.
1.1       anton    15708: 
1.27      crook    15709: You can make use of the same shell capability to make a Forth source
                   15710: file into an executable. For example, if you place this text in a file:
1.26      crook    15711: 
                   15712: @example
                   15713: #! /usr/local/bin/gforth
                   15714: 
                   15715: ." Hello, world" CR
                   15716: bye
                   15717: @end example
                   15718: 
                   15719: @noindent
1.27      crook    15720: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    15721: directly from the command line. The sequence @code{#!} is used in two
                   15722: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    15723: system@footnote{The Unix kernel actually recognises two types of files:
                   15724: executable files and files of data, where the data is processed by an
                   15725: interpreter that is specified on the ``interpreter line'' -- the first
                   15726: line of the file, starting with the sequence #!. There may be a small
                   15727: limit (e.g., 32) on the number of characters that may be specified on
                   15728: the interpreter line.} secondly it is treated as a comment character by
                   15729: Gforth. Because of the second usage, a space is required between
1.80      anton    15730: @code{#!} and the path to the executable (moreover, some Unixes
                   15731: require the sequence @code{#! /}).
1.27      crook    15732: 
1.239     anton    15733: Most Unix systems (including Linux) support exactly one option after
                   15734: the binary name.  If that is not enough, you can use the following
1.240   ! dvdkhlng 15735: trick:
1.239     anton    15736: 
                   15737: @example
                   15738: #! /bin/sh
                   15739: : ## ; 0 [if]
                   15740: exec gforth -m 10M -d 1M $0 "$@"
                   15741: [then]
                   15742: ." Hello, world" cr
                   15743: bye \ caution: this prevents (further) processing of "$@"
                   15744: @end example
                   15745: 
                   15746: First this script is interpreted as shell script, which treats the
                   15747: first two lines as (mostly) comments, then performs the third line,
                   15748: which invokes gforth with this script (@code{$0}) as parameter and its
                   15749: parameters as additional parameters (@code{"$@"}).  Then this script
                   15750: is interpreted as Forth script, which first defines a colon definition
1.240   ! dvdkhlng 15751: @code{##}, then ignores everything up to @code{[then]} and finally
1.239     anton    15752: processes the following Forth code.  You can also use
                   15753: 
                   15754: @example
                   15755: #0 [if]
                   15756: @end example
                   15757: 
                   15758: in the second line, but this works only in Gforth-0.7.0 and later.
                   15759: 
                   15760: The @file{gforthmi} approach is the fastest one, the shell-based one
                   15761: is slowest (needs to start an additional shell).  An additional
                   15762: advantage of the shell approach is that it is unnecessary to know
                   15763: where the Gforth binary resides, as long as it is in the @code{$PATH}.
1.26      crook    15764: 
1.1       anton    15765: doc-#!
                   15766: 
1.44      crook    15767: 
1.1       anton    15768: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   15769: @section Modifying the Startup Sequence
                   15770: @cindex startup sequence for image file
                   15771: @cindex image file initialization sequence
                   15772: @cindex initialization sequence of image file
                   15773: 
1.120     anton    15774: You can add your own initialization to the startup sequence of an image
                   15775: through the deferred word @code{'cold}. @code{'cold} is invoked just
                   15776: before the image-specific command line processing (i.e., loading files
                   15777: and evaluating (@code{-e}) strings) starts.
1.1       anton    15778: 
                   15779: A sequence for adding your initialization usually looks like this:
                   15780: 
                   15781: @example
                   15782: :noname
                   15783:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   15784:     ... \ your stuff
                   15785: ; IS 'cold
                   15786: @end example
                   15787: 
1.157     anton    15788: After @code{'cold}, Gforth processes the image options
                   15789: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
                   15790: another deferred word.  This normally prints Gforth's startup message
                   15791: and does nothing else.
                   15792: 
1.1       anton    15793: @cindex turnkey image files
1.26      crook    15794: @cindex image file, turnkey applications
1.157     anton    15795: So, if you want to make a turnkey image (i.e., an image for an
                   15796: application instead of an extended Forth system), you can do this in
                   15797: two ways:
                   15798: 
                   15799: @itemize @bullet
                   15800: 
                   15801: @item
                   15802: If you want to do your interpretation of the OS command-line
                   15803: arguments, hook into @code{'cold}.  In that case you probably also
                   15804: want to build the image with @code{gforthmi --application}
                   15805: (@pxref{gforthmi}) to keep the engine from processing OS command line
                   15806: options.  You can then do your own command-line processing with
                   15807: @code{next-arg} 
                   15808: 
                   15809: @item
                   15810: If you want to have the normal Gforth processing of OS command-line
                   15811: arguments, hook into @code{bootmessage}.
                   15812: 
                   15813: @end itemize
                   15814: 
                   15815: In either case, you probably do not want the word that you execute in
                   15816: these hooks to exit normally, but use @code{bye} or @code{throw}.
                   15817: Otherwise the Gforth startup process would continue and eventually
                   15818: present the Forth command line to the user.
1.26      crook    15819: 
                   15820: doc-'cold
1.157     anton    15821: doc-bootmessage
1.44      crook    15822: 
1.1       anton    15823: @c ******************************************************************
1.113     anton    15824: @node Engine, Cross Compiler, Image Files, Top
1.1       anton    15825: @chapter Engine
                   15826: @cindex engine
                   15827: @cindex virtual machine
                   15828: 
1.26      crook    15829: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    15830: may be helpful for finding your way in the Gforth sources.
                   15831: 
1.109     anton    15832: The ideas in this section have also been published in the following
                   15833: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
                   15834: Forth-Tagung '93; M. Anton Ertl,
                   15835: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
                   15836: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
                   15837: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
                   15838: Threaded code variations and optimizations (extended version)}},
                   15839: Forth-Tagung '02.
1.1       anton    15840: 
                   15841: @menu
                   15842: * Portability::                 
                   15843: * Threading::                   
                   15844: * Primitives::                  
                   15845: * Performance::                 
                   15846: @end menu
                   15847: 
                   15848: @node Portability, Threading, Engine, Engine
                   15849: @section Portability
                   15850: @cindex engine portability
                   15851: 
1.26      crook    15852: An important goal of the Gforth Project is availability across a wide
                   15853: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   15854: achieved this goal by manually coding the engine in assembly language
                   15855: for several then-popular processors. This approach is very
                   15856: labor-intensive and the results are short-lived due to progress in
                   15857: computer architecture.
1.1       anton    15858: 
                   15859: @cindex C, using C for the engine
                   15860: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   15861: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   15862: particularly popular for UNIX-based Forths due to the large variety of
                   15863: architectures of UNIX machines. Unfortunately an implementation in C
                   15864: does not mix well with the goals of efficiency and with using
                   15865: traditional techniques: Indirect or direct threading cannot be expressed
                   15866: in C, and switch threading, the fastest technique available in C, is
                   15867: significantly slower. Another problem with C is that it is very
                   15868: cumbersome to express double integer arithmetic.
                   15869: 
                   15870: @cindex GNU C for the engine
                   15871: @cindex long long
                   15872: Fortunately, there is a portable language that does not have these
                   15873: limitations: GNU C, the version of C processed by the GNU C compiler
                   15874: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   15875: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   15876: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   15877: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   15878: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109     anton    15879: double numbers on many systems.  GNU C is freely available on all
1.1       anton    15880: important (and many unimportant) UNIX machines, VMS, 80386s running
                   15881: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   15882: on all these machines.
                   15883: 
                   15884: Writing in a portable language has the reputation of producing code that
                   15885: is slower than assembly. For our Forth engine we repeatedly looked at
                   15886: the code produced by the compiler and eliminated most compiler-induced
                   15887: inefficiencies by appropriate changes in the source code.
                   15888: 
                   15889: @cindex explicit register declarations
                   15890: @cindex --enable-force-reg, configuration flag
                   15891: @cindex -DFORCE_REG
                   15892: However, register allocation cannot be portably influenced by the
                   15893: programmer, leading to some inefficiencies on register-starved
                   15894: machines. We use explicit register declarations (@pxref{Explicit Reg
                   15895: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   15896: improve the speed on some machines. They are turned on by using the
                   15897: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   15898: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   15899: machine, but also on the compiler version: On some machines some
                   15900: compiler versions produce incorrect code when certain explicit register
                   15901: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   15902: 
                   15903: @node Threading, Primitives, Portability, Engine
                   15904: @section Threading
                   15905: @cindex inner interpreter implementation
                   15906: @cindex threaded code implementation
                   15907: 
                   15908: @cindex labels as values
                   15909: GNU C's labels as values extension (available since @code{gcc-2.0},
                   15910: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    15911: makes it possible to take the address of @i{label} by writing
                   15912: @code{&&@i{label}}.  This address can then be used in a statement like
                   15913: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    15914: @code{goto x}.
                   15915: 
1.26      crook    15916: @cindex @code{NEXT}, indirect threaded
1.1       anton    15917: @cindex indirect threaded inner interpreter
                   15918: @cindex inner interpreter, indirect threaded
1.26      crook    15919: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    15920: @example
                   15921: cfa = *ip++;
                   15922: ca = *cfa;
                   15923: goto *ca;
                   15924: @end example
                   15925: @cindex instruction pointer
                   15926: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   15927: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   15928: execution token and points to the code field of the next word to be
                   15929: executed; The @code{ca} (code address) fetched from there points to some
                   15930: executable code, e.g., a primitive or the colon definition handler
                   15931: @code{docol}.
                   15932: 
1.26      crook    15933: @cindex @code{NEXT}, direct threaded
1.1       anton    15934: @cindex direct threaded inner interpreter
                   15935: @cindex inner interpreter, direct threaded
                   15936: Direct threading is even simpler:
                   15937: @example
                   15938: ca = *ip++;
                   15939: goto *ca;
                   15940: @end example
                   15941: 
                   15942: Of course we have packaged the whole thing neatly in macros called
1.26      crook    15943: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    15944: 
                   15945: @menu
                   15946: * Scheduling::                  
                   15947: * Direct or Indirect Threaded?::  
1.109     anton    15948: * Dynamic Superinstructions::   
1.1       anton    15949: * DOES>::                       
                   15950: @end menu
                   15951: 
                   15952: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   15953: @subsection Scheduling
                   15954: @cindex inner interpreter optimization
                   15955: 
                   15956: There is a little complication: Pipelined and superscalar processors,
                   15957: i.e., RISC and some modern CISC machines can process independent
                   15958: instructions while waiting for the results of an instruction. The
                   15959: compiler usually reorders (schedules) the instructions in a way that
                   15960: achieves good usage of these delay slots. However, on our first tries
                   15961: the compiler did not do well on scheduling primitives. E.g., for
                   15962: @code{+} implemented as
                   15963: @example
                   15964: n=sp[0]+sp[1];
                   15965: sp++;
                   15966: sp[0]=n;
                   15967: NEXT;
                   15968: @end example
1.81      anton    15969: the @code{NEXT} comes strictly after the other code, i.e., there is
                   15970: nearly no scheduling. After a little thought the problem becomes clear:
                   15971: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21      crook    15972: addresses (and the version of @code{gcc} we used would not know it even
                   15973: if it was possible), so it could not move the load of the cfa above the
                   15974: store to the TOS. Indeed the pointers could be the same, if code on or
                   15975: very near the top of stack were executed. In the interest of speed we
                   15976: chose to forbid this probably unused ``feature'' and helped the compiler
1.81      anton    15977: in scheduling: @code{NEXT} is divided into several parts:
                   15978: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
                   15979: like:
1.1       anton    15980: @example
1.81      anton    15981: NEXT_P0;
1.1       anton    15982: n=sp[0]+sp[1];
                   15983: sp++;
                   15984: NEXT_P1;
                   15985: sp[0]=n;
                   15986: NEXT_P2;
                   15987: @end example
                   15988: 
1.81      anton    15989: There are various schemes that distribute the different operations of
                   15990: NEXT between these parts in several ways; in general, different schemes
                   15991: perform best on different processors.  We use a scheme for most
                   15992: architectures that performs well for most processors of this
1.109     anton    15993: architecture; in the future we may switch to benchmarking and chosing
1.81      anton    15994: the scheme on installation time.
                   15995: 
1.1       anton    15996: 
1.109     anton    15997: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1       anton    15998: @subsection Direct or Indirect Threaded?
                   15999: @cindex threading, direct or indirect?
                   16000: 
1.109     anton    16001: Threaded forth code consists of references to primitives (simple machine
                   16002: code routines like @code{+}) and to non-primitives (e.g., colon
                   16003: definitions, variables, constants); for a specific class of
                   16004: non-primitives (e.g., variables) there is one code routine (e.g.,
                   16005: @code{dovar}), but each variable needs a separate reference to its data.
                   16006: 
                   16007: Traditionally Forth has been implemented as indirect threaded code,
                   16008: because this allows to use only one cell to reference a non-primitive
                   16009: (basically you point to the data, and find the code address there).
                   16010: 
                   16011: @cindex primitive-centric threaded code
                   16012: However, threaded code in Gforth (since 0.6.0) uses two cells for
                   16013: non-primitives, one for the code address, and one for the data address;
                   16014: the data pointer is an immediate argument for the virtual machine
                   16015: instruction represented by the code address.  We call this
                   16016: @emph{primitive-centric} threaded code, because all code addresses point
                   16017: to simple primitives.  E.g., for a variable, the code address is for
                   16018: @code{lit} (also used for integer literals like @code{99}).
                   16019: 
                   16020: Primitive-centric threaded code allows us to use (faster) direct
                   16021: threading as dispatch method, completely portably (direct threaded code
                   16022: in Gforth before 0.6.0 required architecture-specific code).  It also
                   16023: eliminates the performance problems related to I-cache consistency that
                   16024: 386 implementations have with direct threaded code, and allows
                   16025: additional optimizations.
                   16026: 
                   16027: @cindex hybrid direct/indirect threaded code
                   16028: There is a catch, however: the @var{xt} parameter of @code{execute} can
                   16029: occupy only one cell, so how do we pass non-primitives with their code
                   16030: @emph{and} data addresses to them?  Our answer is to use indirect
                   16031: threaded dispatch for @code{execute} and other words that use a
                   16032: single-cell xt.  So, normal threaded code in colon definitions uses
                   16033: direct threading, and @code{execute} and similar words, which dispatch
                   16034: to xts on the data stack, use indirect threaded code.  We call this
                   16035: @emph{hybrid direct/indirect} threaded code.
                   16036: 
                   16037: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
                   16038: @cindex gforth engine
                   16039: @cindex gforth-fast engine
                   16040: The engines @command{gforth} and @command{gforth-fast} use hybrid
                   16041: direct/indirect threaded code.  This means that with these engines you
                   16042: cannot use @code{,} to compile an xt.  Instead, you have to use
                   16043: @code{compile,}.
                   16044: 
                   16045: @cindex gforth-itc engine
1.115     anton    16046: If you want to compile xts with @code{,}, use @command{gforth-itc}.
                   16047: This engine uses plain old indirect threaded code.  It still compiles in
                   16048: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109     anton    16049: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115     anton    16050: ... [}).  If you want to do that, you have to use @command{gforth-itc}
1.109     anton    16051: and execute @code{' , is compile,}.  Your program can check if it is
                   16052: running on a hybrid direct/indirect threaded engine or a pure indirect
                   16053: threaded engine with @code{threading-method} (@pxref{Threading Words}).
                   16054: 
                   16055: 
                   16056: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
                   16057: @subsection Dynamic Superinstructions
                   16058: @cindex Dynamic superinstructions with replication
                   16059: @cindex Superinstructions
                   16060: @cindex Replication
                   16061: 
                   16062: The engines @command{gforth} and @command{gforth-fast} use another
                   16063: optimization: Dynamic superinstructions with replication.  As an
                   16064: example, consider the following colon definition:
                   16065: 
                   16066: @example
                   16067: : squared ( n1 -- n2 )
                   16068:   dup * ;
                   16069: @end example
                   16070: 
                   16071: Gforth compiles this into the threaded code sequence
                   16072: 
                   16073: @example
                   16074: dup
                   16075: *
                   16076: ;s
                   16077: @end example
                   16078: 
                   16079: In normal direct threaded code there is a code address occupying one
                   16080: cell for each of these primitives.  Each code address points to a
                   16081: machine code routine, and the interpreter jumps to this machine code in
                   16082: order to execute the primitive.  The routines for these three
                   16083: primitives are (in @command{gforth-fast} on the 386):
                   16084: 
                   16085: @example
                   16086: Code dup  
                   16087: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
                   16088: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
                   16089: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
                   16090: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   16091: end-code
                   16092: Code *  
                   16093: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
                   16094: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
                   16095: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
                   16096: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
                   16097: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   16098: end-code
                   16099: Code ;s  
                   16100: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
                   16101: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
                   16102: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
                   16103: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   16104: end-code
                   16105: @end example
                   16106: 
                   16107: With dynamic superinstructions and replication the compiler does not
                   16108: just lay down the threaded code, but also copies the machine code
                   16109: fragments, usually without the jump at the end.
                   16110: 
                   16111: @example
                   16112: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
                   16113: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
                   16114: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
                   16115: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
                   16116: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
                   16117: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
                   16118: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
                   16119: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
                   16120: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
                   16121: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
                   16122: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   16123: @end example
                   16124: 
                   16125: Only when a threaded-code control-flow change happens (e.g., in
                   16126: @code{;s}), the jump is appended.  This optimization eliminates many of
                   16127: these jumps and makes the rest much more predictable.  The speedup
                   16128: depends on the processor and the application; on the Athlon and Pentium
                   16129: III this optimization typically produces a speedup by a factor of 2.
                   16130: 
                   16131: The code addresses in the direct-threaded code are set to point to the
                   16132: appropriate points in the copied machine code, in this example like
                   16133: this:
1.1       anton    16134: 
1.109     anton    16135: @example
                   16136: primitive  code address
                   16137:    dup       $4057D27D
                   16138:    *         $4057D286
                   16139:    ;s        $4057D292
                   16140: @end example
                   16141: 
                   16142: Thus there can be threaded-code jumps to any place in this piece of
                   16143: code.  This also simplifies decompilation quite a bit.
                   16144: 
                   16145: @cindex --no-dynamic command-line option
                   16146: @cindex --no-super command-line option
                   16147: You can disable this optimization with @option{--no-dynamic}.  You can
                   16148: use the copying without eliminating the jumps (i.e., dynamic
                   16149: replication, but without superinstructions) with @option{--no-super};
                   16150: this gives the branch prediction benefit alone; the effect on
1.110     anton    16151: performance depends on the CPU; on the Athlon and Pentium III the
                   16152: speedup is a little less than for dynamic superinstructions with
                   16153: replication.
                   16154: 
                   16155: @cindex patching threaded code
                   16156: One use of these options is if you want to patch the threaded code.
                   16157: With superinstructions, many of the dispatch jumps are eliminated, so
                   16158: patching often has no effect.  These options preserve all the dispatch
                   16159: jumps.
1.109     anton    16160: 
                   16161: @cindex --dynamic command-line option
1.110     anton    16162: On some machines dynamic superinstructions are disabled by default,
                   16163: because it is unsafe on these machines.  However, if you feel
                   16164: adventurous, you can enable it with @option{--dynamic}.
1.109     anton    16165: 
                   16166: @node DOES>,  , Dynamic Superinstructions, Threading
1.1       anton    16167: @subsection DOES>
                   16168: @cindex @code{DOES>} implementation
                   16169: 
1.26      crook    16170: @cindex @code{dodoes} routine
                   16171: @cindex @code{DOES>}-code
1.1       anton    16172: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   16173: the chunk of code executed by every word defined by a
1.109     anton    16174: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
                   16175: this is only needed if the xt of the word is @code{execute}d. The main
                   16176: problem here is: How to find the Forth code to be executed, i.e. the
                   16177: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
                   16178: solutions:
1.1       anton    16179: 
1.21      crook    16180: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109     anton    16181: @code{DOES>}-code address is stored in the cell after the code address
                   16182: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
                   16183: illegal in the Forth-79 and all later standards, because in fig-Forth
                   16184: this address lies in the body (which is illegal in these
                   16185: standards). However, by making the code field larger for all words this
                   16186: solution becomes legal again.  We use this approach.  Leaving a cell
                   16187: unused in most words is a bit wasteful, but on the machines we are
                   16188: targeting this is hardly a problem.
                   16189: 
1.1       anton    16190: 
                   16191: @node Primitives, Performance, Threading, Engine
                   16192: @section Primitives
                   16193: @cindex primitives, implementation
                   16194: @cindex virtual machine instructions, implementation
                   16195: 
                   16196: @menu
                   16197: * Automatic Generation::        
                   16198: * TOS Optimization::            
                   16199: * Produced code::               
                   16200: @end menu
                   16201: 
                   16202: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   16203: @subsection Automatic Generation
                   16204: @cindex primitives, automatic generation
                   16205: 
                   16206: @cindex @file{prims2x.fs}
1.109     anton    16207: 
1.1       anton    16208: Since the primitives are implemented in a portable language, there is no
                   16209: longer any need to minimize the number of primitives. On the contrary,
                   16210: having many primitives has an advantage: speed. In order to reduce the
                   16211: number of errors in primitives and to make programming them easier, we
1.109     anton    16212: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
                   16213: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
                   16214: generates most (and sometimes all) of the C code for a primitive from
                   16215: the stack effect notation.  The source for a primitive has the following
                   16216: form:
1.1       anton    16217: 
                   16218: @cindex primitive source format
                   16219: @format
1.58      anton    16220: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
1.29      crook    16221: [@code{""}@i{glossary entry}@code{""}]
                   16222: @i{C code}
1.1       anton    16223: [@code{:}
1.29      crook    16224: @i{Forth code}]
1.1       anton    16225: @end format
                   16226: 
                   16227: The items in brackets are optional. The category and glossary fields
                   16228: are there for generating the documentation, the Forth code is there
                   16229: for manual implementations on machines without GNU C. E.g., the source
                   16230: for the primitive @code{+} is:
                   16231: @example
1.58      anton    16232: +    ( n1 n2 -- n )   core    plus
1.1       anton    16233: n = n1+n2;
                   16234: @end example
                   16235: 
                   16236: This looks like a specification, but in fact @code{n = n1+n2} is C
                   16237: code. Our primitive generation tool extracts a lot of information from
                   16238: the stack effect notations@footnote{We use a one-stack notation, even
                   16239: though we have separate data and floating-point stacks; The separate
                   16240: notation can be generated easily from the unified notation.}: The number
                   16241: of items popped from and pushed on the stack, their type, and by what
                   16242: name they are referred to in the C code. It then generates a C code
                   16243: prelude and postlude for each primitive. The final C code for @code{+}
                   16244: looks like this:
                   16245: 
                   16246: @example
1.46      pazsan   16247: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
1.1       anton    16248: /*  */                          /* documentation */
1.81      anton    16249: NAME("+")                       /* debugging output (with -DDEBUG) */
1.1       anton    16250: @{
                   16251: DEF_CA                          /* definition of variable ca (indirect threading) */
                   16252: Cell n1;                        /* definitions of variables */
                   16253: Cell n2;
                   16254: Cell n;
1.81      anton    16255: NEXT_P0;                        /* NEXT part 0 */
1.1       anton    16256: n1 = (Cell) sp[1];              /* input */
                   16257: n2 = (Cell) TOS;
                   16258: sp += 1;                        /* stack adjustment */
                   16259: @{
                   16260: n = n1+n2;                      /* C code taken from the source */
                   16261: @}
                   16262: NEXT_P1;                        /* NEXT part 1 */
                   16263: TOS = (Cell)n;                  /* output */
                   16264: NEXT_P2;                        /* NEXT part 2 */
                   16265: @}
                   16266: @end example
                   16267: 
                   16268: This looks long and inefficient, but the GNU C compiler optimizes quite
                   16269: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   16270: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   16271: using them as intermediate storage also adds no cost.
                   16272: 
1.26      crook    16273: There are also other optimizations that are not illustrated by this
                   16274: example: assignments between simple variables are usually for free (copy
1.1       anton    16275: propagation). If one of the stack items is not used by the primitive
                   16276: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   16277: (dead code elimination). On the other hand, there are some things that
                   16278: the compiler does not do, therefore they are performed by
                   16279: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   16280: a stack item to the place where it just came from (e.g., @code{over}).
                   16281: 
                   16282: While programming a primitive is usually easy, there are a few cases
                   16283: where the programmer has to take the actions of the generator into
                   16284: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    16285: fall through to @code{NEXT}.
1.109     anton    16286: 
                   16287: For more information
1.1       anton    16288: 
                   16289: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   16290: @subsection TOS Optimization
                   16291: @cindex TOS optimization for primitives
                   16292: @cindex primitives, keeping the TOS in a register
                   16293: 
                   16294: An important optimization for stack machine emulators, e.g., Forth
                   16295: engines, is keeping  one or more of the top stack items in
1.29      crook    16296: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   16297: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    16298: @itemize @bullet
                   16299: @item
1.29      crook    16300: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    16301: due to fewer loads from and stores to the stack.
1.29      crook    16302: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   16303: @i{y<n}, due to additional moves between registers.
1.1       anton    16304: @end itemize
                   16305: 
                   16306: @cindex -DUSE_TOS
                   16307: @cindex -DUSE_NO_TOS
                   16308: In particular, keeping one item in a register is never a disadvantage,
                   16309: if there are enough registers. Keeping two items in registers is a
                   16310: disadvantage for frequent words like @code{?branch}, constants,
                   16311: variables, literals and @code{i}. Therefore our generator only produces
                   16312: code that keeps zero or one items in registers. The generated C code
                   16313: covers both cases; the selection between these alternatives is made at
                   16314: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   16315: code for @code{+} is just a simple variable name in the one-item case,
                   16316: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   16317: GNU C compiler tries to keep simple variables like @code{TOS} in
                   16318: registers, and it usually succeeds, if there are enough registers.
                   16319: 
                   16320: @cindex -DUSE_FTOS
                   16321: @cindex -DUSE_NO_FTOS
                   16322: The primitive generator performs the TOS optimization for the
                   16323: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   16324: operations the benefit of this optimization is even larger:
                   16325: floating-point operations take quite long on most processors, but can be
                   16326: performed in parallel with other operations as long as their results are
                   16327: not used. If the FP-TOS is kept in a register, this works. If
                   16328: it is kept on the stack, i.e., in memory, the store into memory has to
                   16329: wait for the result of the floating-point operation, lengthening the
                   16330: execution time of the primitive considerably.
                   16331: 
                   16332: The TOS optimization makes the automatic generation of primitives a
                   16333: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   16334: @code{TOS} is not sufficient. There are some special cases to
                   16335: consider:
                   16336: @itemize @bullet
                   16337: @item In the case of @code{dup ( w -- w w )} the generator must not
                   16338: eliminate the store to the original location of the item on the stack,
                   16339: if the TOS optimization is turned on.
                   16340: @item Primitives with stack effects of the form @code{--}
1.29      crook    16341: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   16342: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    16343: must load the TOS from the stack at the end. But for the null stack
                   16344: effect @code{--} no stores or loads should be generated.
                   16345: @end itemize
                   16346: 
                   16347: @node Produced code,  , TOS Optimization, Primitives
                   16348: @subsection Produced code
                   16349: @cindex primitives, assembly code listing
                   16350: 
                   16351: @cindex @file{engine.s}
                   16352: To see what assembly code is produced for the primitives on your machine
                   16353: with your compiler and your flag settings, type @code{make engine.s} and
1.81      anton    16354: look at the resulting file @file{engine.s}.  Alternatively, you can also
                   16355: disassemble the code of primitives with @code{see} on some architectures.
1.1       anton    16356: 
                   16357: @node  Performance,  , Primitives, Engine
                   16358: @section Performance
                   16359: @cindex performance of some Forth interpreters
                   16360: @cindex engine performance
                   16361: @cindex benchmarking Forth systems
                   16362: @cindex Gforth performance
                   16363: 
                   16364: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112     anton    16365: impossible to write a significantly faster threaded-code engine.
1.1       anton    16366: 
                   16367: On register-starved machines like the 386 architecture processors
                   16368: improvements are possible, because @code{gcc} does not utilize the
                   16369: registers as well as a human, even with explicit register declarations;
                   16370: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   16371: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   16372: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40      anton    16373: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
                   16374: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
                   16375: registers fit in real registers (and we can even afford to use the TOS
                   16376: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112     anton    16377: earlier results.  And dynamic superinstructions provide another speedup
                   16378: (but only around a factor 1.2 on the 486).
1.1       anton    16379: 
                   16380: @cindex Win32Forth performance
                   16381: @cindex NT Forth performance
                   16382: @cindex eforth performance
                   16383: @cindex ThisForth performance
                   16384: @cindex PFE performance
                   16385: @cindex TILE performance
1.81      anton    16386: The potential advantage of assembly language implementations is not
1.112     anton    16387: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81      anton    16388: (direct threaded, compiled with @code{gcc-2.95.1} and
                   16389: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
                   16390: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
                   16391: (with and without peephole (aka pinhole) optimization of the threaded
                   16392: code); all these systems were written in assembly language. We also
                   16393: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
                   16394: with @code{gcc-2.6.3} with the default configuration for Linux:
                   16395: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
                   16396: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
                   16397: employs peephole optimization of the threaded code) and TILE (compiled
                   16398: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
                   16399: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
                   16400: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
                   16401: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
                   16402: then extended it to run the benchmarks, added the peephole optimizer,
                   16403: ran the benchmarks and reported the results.
1.40      anton    16404: 
1.1       anton    16405: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   16406: matrix multiplication come from the Stanford integer benchmarks and have
                   16407: been translated into Forth by Martin Fraeman; we used the versions
                   16408: included in the TILE Forth package, but with bigger data set sizes; and
                   16409: a recursive Fibonacci number computation for benchmarking calling
                   16410: performance. The following table shows the time taken for the benchmarks
                   16411: scaled by the time taken by Gforth (in other words, it shows the speedup
                   16412: factor that Gforth achieved over the other systems).
                   16413: 
                   16414: @example
1.112     anton    16415: relative       Win32-    NT       eforth       This-      
                   16416: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
                   16417: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
                   16418: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
                   16419: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
                   16420: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
1.1       anton    16421: @end example
                   16422: 
1.26      crook    16423: You may be quite surprised by the good performance of Gforth when
                   16424: compared with systems written in assembly language. One important reason
                   16425: for the disappointing performance of these other systems is probably
                   16426: that they are not written optimally for the 486 (e.g., they use the
                   16427: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   16428: but costly method for relocating the Forth image: like @code{cforth}, it
                   16429: computes the actual addresses at run time, resulting in two address
                   16430: computations per @code{NEXT} (@pxref{Image File Background}).
                   16431: 
1.1       anton    16432: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   16433: explained with the self-imposed restriction of the latter systems to
                   16434: standard C, which makes efficient threading impossible (however, the
1.4       anton    16435: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    16436: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   16437: Moreover, current C compilers have a hard time optimizing other aspects
                   16438: of the ThisForth and the TILE source.
                   16439: 
1.26      crook    16440: The performance of Gforth on 386 architecture processors varies widely
                   16441: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   16442: allocate any of the virtual machine registers into real machine
                   16443: registers by itself and would not work correctly with explicit register
1.112     anton    16444: declarations, giving a significantly slower engine (on a 486DX2/66
                   16445: running the Sieve) than the one measured above.
1.1       anton    16446: 
1.26      crook    16447: Note that there have been several releases of Win32Forth since the
                   16448: release presented here, so the results presented above may have little
1.40      anton    16449: predictive value for the performance of Win32Forth today (results for
                   16450: the current release on an i486DX2/66 are welcome).
1.1       anton    16451: 
                   16452: @cindex @file{Benchres}
1.66      anton    16453: In
                   16454: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
                   16455: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1       anton    16456: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66      anton    16457: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
                   16458: several native code systems; that version of Gforth is slower on a 486
1.112     anton    16459: than the version used here. You can find a newer version of these
                   16460: measurements at
1.47      crook    16461: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1       anton    16462: find numbers for Gforth on various machines in @file{Benchres}.
                   16463: 
1.26      crook    16464: @c ******************************************************************
1.113     anton    16465: @c @node Binding to System Library, Cross Compiler, Engine, Top
                   16466: @c @chapter Binding to System Library
1.13      pazsan   16467: 
1.113     anton    16468: @c ****************************************************************
                   16469: @node Cross Compiler, Bugs, Engine, Top
1.14      pazsan   16470: @chapter Cross Compiler
1.47      crook    16471: @cindex @file{cross.fs}
                   16472: @cindex cross-compiler
                   16473: @cindex metacompiler
                   16474: @cindex target compiler
1.13      pazsan   16475: 
1.46      pazsan   16476: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
                   16477: mostly written in Forth, including crucial parts like the outer
                   16478: interpreter and compiler, it needs compiled Forth code to get
                   16479: started. The cross compiler allows to create new images for other
                   16480: architectures, even running under another Forth system.
1.13      pazsan   16481: 
                   16482: @menu
1.67      anton    16483: * Using the Cross Compiler::    
                   16484: * How the Cross Compiler Works::  
1.13      pazsan   16485: @end menu
                   16486: 
1.21      crook    16487: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   16488: @section Using the Cross Compiler
1.46      pazsan   16489: 
                   16490: The cross compiler uses a language that resembles Forth, but isn't. The
                   16491: main difference is that you can execute Forth code after definition,
                   16492: while you usually can't execute the code compiled by cross, because the
                   16493: code you are compiling is typically for a different computer than the
                   16494: one you are compiling on.
                   16495: 
1.81      anton    16496: @c anton: This chapter is somewhat different from waht I would expect: I
                   16497: @c would expect an explanation of the cross language and how to create an
                   16498: @c application image with it.  The section explains some aspects of
                   16499: @c creating a Gforth kernel.
                   16500: 
1.46      pazsan   16501: The Makefile is already set up to allow you to create kernels for new
                   16502: architectures with a simple make command. The generic kernels using the
                   16503: GCC compiled virtual machine are created in the normal build process
                   16504: with @code{make}. To create a embedded Gforth executable for e.g. the
                   16505: 8086 processor (running on a DOS machine), type
                   16506: 
                   16507: @example
                   16508: make kernl-8086.fi
                   16509: @end example
                   16510: 
                   16511: This will use the machine description from the @file{arch/8086}
                   16512: directory to create a new kernel. A machine file may look like that:
                   16513: 
                   16514: @example
                   16515: \ Parameter for target systems                         06oct92py
                   16516: 
                   16517:     4 Constant cell             \ cell size in bytes
                   16518:     2 Constant cell<<           \ cell shift to bytes
                   16519:     5 Constant cell>bit         \ cell shift to bits
                   16520:     8 Constant bits/char        \ bits per character
                   16521:     8 Constant bits/byte        \ bits per byte [default: 8]
                   16522:     8 Constant float            \ bytes per float
                   16523:     8 Constant /maxalign        \ maximum alignment in bytes
                   16524: false Constant bigendian        \ byte order
                   16525: ( true=big, false=little )
                   16526: 
                   16527: include machpc.fs               \ feature list
                   16528: @end example
                   16529: 
                   16530: This part is obligatory for the cross compiler itself, the feature list
                   16531: is used by the kernel to conditionally compile some features in and out,
                   16532: depending on whether the target supports these features.
                   16533: 
                   16534: There are some optional features, if you define your own primitives,
                   16535: have an assembler, or need special, nonstandard preparation to make the
1.81      anton    16536: boot process work. @code{asm-include} includes an assembler,
1.46      pazsan   16537: @code{prims-include} includes primitives, and @code{>boot} prepares for
                   16538: booting.
                   16539: 
                   16540: @example
                   16541: : asm-include    ." Include assembler" cr
                   16542:   s" arch/8086/asm.fs" included ;
                   16543: 
                   16544: : prims-include  ." Include primitives" cr
                   16545:   s" arch/8086/prim.fs" included ;
                   16546: 
                   16547: : >boot          ." Prepare booting" cr
                   16548:   s" ' boot >body into-forth 1+ !" evaluate ;
                   16549: @end example
                   16550: 
                   16551: These words are used as sort of macro during the cross compilation in
1.81      anton    16552: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46      pazsan   16553: be possible --- but more complicated --- to write a new kernel project
                   16554: file, too.
                   16555: 
                   16556: @file{kernel/main.fs} expects the machine description file name on the
                   16557: stack; the cross compiler itself (@file{cross.fs}) assumes that either
                   16558: @code{mach-file} leaves a counted string on the stack, or
                   16559: @code{machine-file} leaves an address, count pair of the filename on the
                   16560: stack.
                   16561: 
                   16562: The feature list is typically controlled using @code{SetValue}, generic
                   16563: files that are used by several projects can use @code{DefaultValue}
                   16564: instead. Both functions work like @code{Value}, when the value isn't
                   16565: defined, but @code{SetValue} works like @code{to} if the value is
                   16566: defined, and @code{DefaultValue} doesn't set anything, if the value is
                   16567: defined.
                   16568: 
                   16569: @example
                   16570: \ generic mach file for pc gforth                       03sep97jaw
                   16571: 
                   16572: true DefaultValue NIL  \ relocating
                   16573: 
                   16574: >ENVIRON
                   16575: 
                   16576: true DefaultValue file          \ controls the presence of the
                   16577:                                 \ file access wordset
                   16578: true DefaultValue OS            \ flag to indicate a operating system
                   16579: 
                   16580: true DefaultValue prims         \ true: primitives are c-code
                   16581: 
                   16582: true DefaultValue floating      \ floating point wordset is present
                   16583: 
                   16584: true DefaultValue glocals       \ gforth locals are present
                   16585:                                 \ will be loaded
                   16586: true DefaultValue dcomps        \ double number comparisons
                   16587: 
                   16588: true DefaultValue hash          \ hashing primitives are loaded/present
                   16589: 
                   16590: true DefaultValue xconds        \ used together with glocals,
                   16591:                                 \ special conditionals supporting gforths'
                   16592:                                 \ local variables
                   16593: true DefaultValue header        \ save a header information
                   16594: 
                   16595: true DefaultValue backtrace     \ enables backtrace code
                   16596: 
                   16597: false DefaultValue ec
                   16598: false DefaultValue crlf
                   16599: 
                   16600: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
                   16601: 
                   16602: &16 KB          DefaultValue stack-size
                   16603: &15 KB &512 +   DefaultValue fstack-size
                   16604: &15 KB          DefaultValue rstack-size
                   16605: &14 KB &512 +   DefaultValue lstack-size
                   16606: @end example
1.13      pazsan   16607: 
1.48      anton    16608: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
1.14      pazsan   16609: @section How the Cross Compiler Works
1.13      pazsan   16610: 
                   16611: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    16612: @appendix Bugs
1.1       anton    16613: @cindex bug reporting
                   16614: 
1.21      crook    16615: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    16616: 
1.103     anton    16617: If you find a bug, please submit a bug report through
                   16618: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21      crook    16619: 
                   16620: @itemize @bullet
                   16621: @item
1.81      anton    16622: A program (or a sequence of keyboard commands) that reproduces the bug.
                   16623: @item
                   16624: A description of what you think constitutes the buggy behaviour.
                   16625: @item
1.21      crook    16626: The Gforth version used (it is announced at the start of an
                   16627: interactive Gforth session).
                   16628: @item
                   16629: The machine and operating system (on Unix
                   16630: systems @code{uname -a} will report this information).
                   16631: @item
1.81      anton    16632: The installation options (you can find the configure options at the
                   16633: start of @file{config.status}) and configuration (@code{configure}
                   16634: output or @file{config.cache}).
1.21      crook    16635: @item
                   16636: A complete list of changes (if any) you (or your installer) have made to the
                   16637: Gforth sources.
                   16638: @end itemize
1.1       anton    16639: 
                   16640: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   16641: to Report Bugs, gcc.info, GNU C Manual}.
                   16642: 
                   16643: 
1.21      crook    16644: @node Origin, Forth-related information, Bugs, Top
                   16645: @appendix Authors and Ancestors of Gforth
1.1       anton    16646: 
                   16647: @section Authors and Contributors
                   16648: @cindex authors of Gforth
                   16649: @cindex contributors to Gforth
                   16650: 
                   16651: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81      anton    16652: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
                   16653: lot to the manual.  Assemblers and disassemblers were contributed by
1.161     anton    16654: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
                   16655: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
                   16656: and Stuart Ramsden inspired us with their continuous feedback. Lennart
                   16657: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
                   16658: working on automatic support for calling C libraries. Helpful comments
                   16659: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
                   16660: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
                   16661: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
                   16662: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
                   16663: comments from many others; thank you all, sorry for not listing you
                   16664: here (but digging through my mailbox to extract your names is on my
                   16665: to-do list).
1.1       anton    16666: 
                   16667: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   16668: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    16669: was developed across the Internet, and its authors did not meet
1.20      pazsan   16670: physically for the first 4 years of development.
1.1       anton    16671: 
                   16672: @section Pedigree
1.26      crook    16673: @cindex pedigree of Gforth
1.1       anton    16674: 
1.81      anton    16675: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
                   16676: significant part of the design of Gforth was prescribed by ANS Forth.
1.1       anton    16677: 
1.20      pazsan   16678: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    16679: 32 bit native code version of VolksForth for the Atari ST, written
                   16680: mostly by Dietrich Weineck.
                   16681: 
1.81      anton    16682: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
                   16683: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147     anton    16684: the mid-80s and ported to the Atari ST in 1986.  It descends from fig-Forth.
1.1       anton    16685: 
1.147     anton    16686: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   16687: @c Forth-83 standard. !! Pedigree? When?
1.1       anton    16688: 
                   16689: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   16690: 1979. Robert Selzer and Bill Ragsdale developed the original
                   16691: implementation of fig-Forth for the 6502 based on microForth.
                   16692: 
                   16693: The principal architect of microForth was Dean Sanderson. microForth was
                   16694: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   16695: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   16696: Z80.
                   16697: 
                   16698: All earlier Forth systems were custom-made, usually by Charles Moore,
                   16699: who discovered (as he puts it) Forth during the late 60s. The first full
                   16700: Forth existed in 1971.
                   16701: 
1.81      anton    16702: A part of the information in this section comes from
1.228     anton    16703: @cite{@uref{http://www.forth.com/resources/evolution/index.html,The
1.81      anton    16704: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147     anton    16705: Charles H. Moore, presented at the HOPL-II conference and preprinted
                   16706: in SIGPLAN Notices 28(3), 1993.  You can find more historical and
                   16707: genealogical information about Forth there.  For a more general (and
                   16708: graphical) Forth family tree look see
                   16709: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
                   16710: Forth Family Tree and Timeline}.
1.1       anton    16711: 
1.81      anton    16712: @c ------------------------------------------------------------------
1.113     anton    16713: @node Forth-related information, Licenses, Origin, Top
1.21      crook    16714: @appendix Other Forth-related information
                   16715: @cindex Forth-related information
                   16716: 
1.81      anton    16717: @c anton: I threw most of this stuff out, because it can be found through
                   16718: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21      crook    16719: 
                   16720: @cindex comp.lang.forth
                   16721: @cindex frequently asked questions
1.81      anton    16722: There is an active news group (comp.lang.forth) discussing Forth
                   16723: (including Gforth) and Forth-related issues. Its
                   16724: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
                   16725: (frequently asked questions and their answers) contains a lot of
                   16726: information on Forth.  You should read it before posting to
                   16727: comp.lang.forth.
1.21      crook    16728: 
1.81      anton    16729: The ANS Forth standard is most usable in its
                   16730: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21      crook    16731: 
1.113     anton    16732: @c ---------------------------------------------------
                   16733: @node  Licenses, Word Index, Forth-related information, Top
                   16734: @appendix Licenses
                   16735: 
                   16736: @menu
                   16737: * GNU Free Documentation License::  License for copying this manual.
1.192     anton    16738: * Copying::                     GPL (for copying this software).
1.113     anton    16739: @end menu
                   16740: 
1.192     anton    16741: @node GNU Free Documentation License, Copying, Licenses, Licenses
                   16742: @appendixsec GNU Free Documentation License
1.113     anton    16743: @include fdl.texi
                   16744: 
1.192     anton    16745: @node Copying,  , GNU Free Documentation License, Licenses
                   16746: @appendixsec GNU GENERAL PUBLIC LICENSE
1.113     anton    16747: @include gpl.texi
                   16748: 
                   16749: 
                   16750: 
1.81      anton    16751: @c ------------------------------------------------------------------
1.113     anton    16752: @node Word Index, Concept Index, Licenses, Top
1.1       anton    16753: @unnumbered Word Index
                   16754: 
1.26      crook    16755: This index is a list of Forth words that have ``glossary'' entries
                   16756: within this manual. Each word is listed with its stack effect and
                   16757: wordset.
1.1       anton    16758: 
                   16759: @printindex fn
                   16760: 
1.81      anton    16761: @c anton: the name index seems superfluous given the word and concept indices.
                   16762: 
                   16763: @c @node Name Index, Concept Index, Word Index, Top
                   16764: @c @unnumbered Name Index
1.41      anton    16765: 
1.81      anton    16766: @c This index is a list of Forth words that have ``glossary'' entries
                   16767: @c within this manual.
1.41      anton    16768: 
1.81      anton    16769: @c @printindex ky
1.41      anton    16770: 
1.113     anton    16771: @c -------------------------------------------------------
1.81      anton    16772: @node Concept Index,  , Word Index, Top
1.1       anton    16773: @unnumbered Concept and Word Index
                   16774: 
1.26      crook    16775: Not all entries listed in this index are present verbatim in the
                   16776: text. This index also duplicates, in abbreviated form, all of the words
                   16777: listed in the Word Index (only the names are listed for the words here).
1.1       anton    16778: 
                   16779: @printindex cp
                   16780: 
                   16781: @bye
1.81      anton    16782: 
                   16783: 
1.1       anton    16784: 

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