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

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.208     anton      64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008,2009 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.71      anton     277: * Supplying names::             Passing definition names as strings
1.67      anton     278: * User-defined Defining Words::  
1.170     pazsan    279: * Deferred Words::              Allow forward references
1.67      anton     280: * Aliases::                     
1.47      crook     281: 
1.63      anton     282: User-defined Defining Words
                    283: 
                    284: * CREATE..DOES> applications::  
                    285: * CREATE..DOES> details::       
                    286: * Advanced does> usage example::  
1.155     anton     287: * Const-does>::                 
1.63      anton     288: 
1.47      crook     289: Interpretation and Compilation Semantics
                    290: 
1.67      anton     291: * Combined words::              
1.12      anton     292: 
1.71      anton     293: Tokens for Words
                    294: 
                    295: * Execution token::             represents execution/interpretation semantics
                    296: * Compilation token::           represents compilation semantics
                    297: * Name token::                  represents named words
                    298: 
1.82      anton     299: Compiling words
                    300: 
                    301: * Literals::                    Compiling data values
                    302: * Macros::                      Compiling words
                    303: 
1.21      crook     304: The Text Interpreter
                    305: 
1.67      anton     306: * Input Sources::               
                    307: * Number Conversion::           
                    308: * Interpret/Compile states::    
                    309: * Interpreter Directives::      
1.21      crook     310: 
1.26      crook     311: Word Lists
                    312: 
1.75      anton     313: * Vocabularies::                
1.67      anton     314: * Why use word lists?::         
1.75      anton     315: * Word list example::           
1.26      crook     316: 
                    317: Files
                    318: 
1.48      anton     319: * Forth source files::          
                    320: * General files::               
1.167     anton     321: * Redirection::                 
1.48      anton     322: * Search Paths::                
                    323: 
                    324: Search Paths
                    325: 
1.75      anton     326: * Source Search Paths::         
1.26      crook     327: * General Search Paths::        
                    328: 
                    329: Other I/O
                    330: 
1.32      anton     331: * Simple numeric output::       Predefined formats
                    332: * Formatted numeric output::    Formatted (pictured) output
                    333: * String Formats::              How Forth stores strings in memory
1.67      anton     334: * Displaying characters and strings::  Other stuff
1.178     anton     335: * Terminal output::             Cursor positioning etc.
1.181     anton     336: * Single-key input::            
                    337: * Line input and conversion::   
1.112     anton     338: * Pipes::                       How to create your own pipes
1.149     pazsan    339: * Xchars and Unicode::          Non-ASCII characters
1.26      crook     340: 
                    341: Locals
                    342: 
                    343: * Gforth locals::               
                    344: * ANS Forth locals::            
                    345: 
                    346: Gforth locals
                    347: 
                    348: * Where are locals visible by name?::  
                    349: * How long do locals live?::    
1.78      anton     350: * Locals programming style::    
                    351: * Locals implementation::       
1.26      crook     352: 
1.12      anton     353: Structures
                    354: 
                    355: * Why explicit structure support?::  
                    356: * Structure Usage::             
                    357: * Structure Naming Convention::  
                    358: * Structure Implementation::    
                    359: * Structure Glossary::          
1.183     anton     360: * Forth200x Structures::        
1.12      anton     361: 
                    362: Object-oriented Forth
                    363: 
1.48      anton     364: * Why object-oriented programming?::  
                    365: * Object-Oriented Terminology::  
                    366: * Objects::                     
                    367: * OOF::                         
                    368: * Mini-OOF::                    
1.23      crook     369: * Comparison with other object models::  
1.12      anton     370: 
1.24      anton     371: The @file{objects.fs} model
1.12      anton     372: 
                    373: * Properties of the Objects model::  
                    374: * Basic Objects Usage::         
1.41      anton     375: * The Objects base class::      
1.12      anton     376: * Creating objects::            
                    377: * Object-Oriented Programming Style::  
                    378: * Class Binding::               
                    379: * Method conveniences::         
                    380: * Classes and Scoping::         
1.41      anton     381: * Dividing classes::            
1.12      anton     382: * Object Interfaces::           
                    383: * Objects Implementation::      
                    384: * Objects Glossary::            
                    385: 
1.24      anton     386: The @file{oof.fs} model
1.12      anton     387: 
1.67      anton     388: * Properties of the OOF model::  
                    389: * Basic OOF Usage::             
                    390: * The OOF base class::          
                    391: * Class Declaration::           
                    392: * Class Implementation::        
1.12      anton     393: 
1.24      anton     394: The @file{mini-oof.fs} model
1.23      crook     395: 
1.48      anton     396: * Basic Mini-OOF Usage::        
                    397: * Mini-OOF Example::            
                    398: * Mini-OOF Implementation::     
1.23      crook     399: 
1.78      anton     400: Programming Tools
                    401: 
1.150     anton     402: * Examining::                   Data and Code.
                    403: * Forgetting words::            Usually before reloading.
1.78      anton     404: * Debugging::                   Simple and quick.
                    405: * Assertions::                  Making your programs self-checking.
                    406: * Singlestep Debugger::         Executing your program word by word.
                    407: 
1.155     anton     408: C Interface
                    409: 
                    410: * Calling C Functions::         
                    411: * Declaring C Functions::       
1.180     anton     412: * Calling C function pointers::  
1.196     anton     413: * Defining library interfaces::  
                    414: * Declaring OS-level libraries::  
1.155     anton     415: * Callbacks::                   
1.178     anton     416: * C interface internals::       
1.155     anton     417: * Low-Level C Interface Words::  
                    418: 
1.78      anton     419: Assembler and Code Words
                    420: 
                    421: * Code and ;code::              
                    422: * Common Assembler::            Assembler Syntax
                    423: * Common Disassembler::         
                    424: * 386 Assembler::               Deviations and special cases
                    425: * Alpha Assembler::             Deviations and special cases
                    426: * MIPS assembler::              Deviations and special cases
1.167     anton     427: * PowerPC assembler::           Deviations and special cases
1.193     dvdkhlng  428: * ARM Assembler::               Deviations and special cases
1.78      anton     429: * Other assemblers::            How to write them
                    430: 
1.12      anton     431: Tools
                    432: 
                    433: * ANS Report::                  Report the words used, sorted by wordset.
1.127     anton     434: * Stack depth changes::         Where does this stack item come from?
1.12      anton     435: 
                    436: ANS conformance
                    437: 
                    438: * The Core Words::              
                    439: * The optional Block word set::  
                    440: * The optional Double Number word set::  
                    441: * The optional Exception word set::  
                    442: * The optional Facility word set::  
                    443: * The optional File-Access word set::  
                    444: * The optional Floating-Point word set::  
                    445: * The optional Locals word set::  
                    446: * The optional Memory-Allocation word set::  
                    447: * The optional Programming-Tools word set::  
                    448: * The optional Search-Order word set::  
                    449: 
                    450: The Core Words
                    451: 
                    452: * core-idef::                   Implementation Defined Options                   
                    453: * core-ambcond::                Ambiguous Conditions                
                    454: * core-other::                  Other System Documentation                  
                    455: 
                    456: The optional Block word set
                    457: 
                    458: * block-idef::                  Implementation Defined Options
                    459: * block-ambcond::               Ambiguous Conditions               
                    460: * block-other::                 Other System Documentation                 
                    461: 
                    462: The optional Double Number word set
                    463: 
                    464: * double-ambcond::              Ambiguous Conditions              
                    465: 
                    466: The optional Exception word set
                    467: 
                    468: * exception-idef::              Implementation Defined Options              
                    469: 
                    470: The optional Facility word set
                    471: 
                    472: * facility-idef::               Implementation Defined Options               
                    473: * facility-ambcond::            Ambiguous Conditions            
                    474: 
                    475: The optional File-Access word set
                    476: 
                    477: * file-idef::                   Implementation Defined Options
                    478: * file-ambcond::                Ambiguous Conditions                
                    479: 
                    480: The optional Floating-Point word set
                    481: 
                    482: * floating-idef::               Implementation Defined Options
                    483: * floating-ambcond::            Ambiguous Conditions            
                    484: 
                    485: The optional Locals word set
                    486: 
                    487: * locals-idef::                 Implementation Defined Options                 
                    488: * locals-ambcond::              Ambiguous Conditions              
                    489: 
                    490: The optional Memory-Allocation word set
                    491: 
                    492: * memory-idef::                 Implementation Defined Options                 
                    493: 
                    494: The optional Programming-Tools word set
                    495: 
                    496: * programming-idef::            Implementation Defined Options            
                    497: * programming-ambcond::         Ambiguous Conditions         
                    498: 
                    499: The optional Search-Order word set
                    500: 
                    501: * search-idef::                 Implementation Defined Options                 
                    502: * search-ambcond::              Ambiguous Conditions              
                    503: 
1.109     anton     504: Emacs and Gforth
                    505: 
                    506: * Installing gforth.el::        Making Emacs aware of Forth.
                    507: * Emacs Tags::                  Viewing the source of a word in Emacs.
                    508: * Hilighting::                  Making Forth code look prettier.
                    509: * Auto-Indentation::            Customizing auto-indentation.
                    510: * Blocks Files::                Reading and writing blocks files.
                    511: 
1.12      anton     512: Image Files
                    513: 
1.24      anton     514: * Image Licensing Issues::      Distribution terms for images.
                    515: * Image File Background::       Why have image files?
1.67      anton     516: * Non-Relocatable Image Files::  don't always work.
1.24      anton     517: * Data-Relocatable Image Files::  are better.
1.67      anton     518: * Fully Relocatable Image Files::  better yet.
1.24      anton     519: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.32      anton     520: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.24      anton     521: * Modifying the Startup Sequence::  and turnkey applications.
1.12      anton     522: 
                    523: Fully Relocatable Image Files
                    524: 
1.27      crook     525: * gforthmi::                    The normal way
1.12      anton     526: * cross.fs::                    The hard way
                    527: 
                    528: Engine
                    529: 
                    530: * Portability::                 
                    531: * Threading::                   
                    532: * Primitives::                  
                    533: * Performance::                 
                    534: 
                    535: Threading
                    536: 
                    537: * Scheduling::                  
                    538: * Direct or Indirect Threaded?::  
1.109     anton     539: * Dynamic Superinstructions::   
1.12      anton     540: * DOES>::                       
                    541: 
                    542: Primitives
                    543: 
                    544: * Automatic Generation::        
                    545: * TOS Optimization::            
                    546: * Produced code::               
1.13      pazsan    547: 
                    548: Cross Compiler
                    549: 
1.67      anton     550: * Using the Cross Compiler::    
                    551: * How the Cross Compiler Works::  
1.13      pazsan    552: 
1.113     anton     553: Licenses
                    554: 
                    555: * GNU Free Documentation License::  License for copying this manual.
1.192     anton     556: * Copying::                     GPL (for copying this software).
1.113     anton     557: 
1.24      anton     558: @end detailmenu
1.1       anton     559: @end menu
                    560: 
1.113     anton     561: @c ----------------------------------------------------------
1.1       anton     562: @iftex
                    563: @unnumbered Preface
                    564: @cindex Preface
1.21      crook     565: This manual documents Gforth. Some introductory material is provided for
                    566: readers who are unfamiliar with Forth or who are migrating to Gforth
                    567: from other Forth compilers. However, this manual is primarily a
                    568: reference manual.
1.1       anton     569: @end iftex
                    570: 
1.28      crook     571: @comment TODO much more blurb here.
1.26      crook     572: 
                    573: @c ******************************************************************
1.113     anton     574: @node Goals, Gforth Environment, Top, Top
1.26      crook     575: @comment node-name,     next,           previous, up
                    576: @chapter Goals of Gforth
                    577: @cindex goals of the Gforth project
                    578: The goal of the Gforth Project is to develop a standard model for
                    579: ANS Forth. This can be split into several subgoals:
                    580: 
                    581: @itemize @bullet
                    582: @item
                    583: Gforth should conform to the ANS Forth Standard.
                    584: @item
                    585: It should be a model, i.e. it should define all the
                    586: implementation-dependent things.
                    587: @item
                    588: It should become standard, i.e. widely accepted and used. This goal
                    589: is the most difficult one.
                    590: @end itemize
                    591: 
                    592: To achieve these goals Gforth should be
                    593: @itemize @bullet
                    594: @item
                    595: Similar to previous models (fig-Forth, F83)
                    596: @item
                    597: Powerful. It should provide for all the things that are considered
                    598: necessary today and even some that are not yet considered necessary.
                    599: @item
                    600: Efficient. It should not get the reputation of being exceptionally
                    601: slow.
                    602: @item
                    603: Free.
                    604: @item
                    605: Available on many machines/easy to port.
                    606: @end itemize
                    607: 
                    608: Have we achieved these goals? Gforth conforms to the ANS Forth
                    609: standard. It may be considered a model, but we have not yet documented
                    610: which parts of the model are stable and which parts we are likely to
                    611: change. It certainly has not yet become a de facto standard, but it
                    612: appears to be quite popular. It has some similarities to and some
                    613: differences from previous models. It has some powerful features, but not
                    614: yet everything that we envisioned. We certainly have achieved our
1.65      anton     615: execution speed goals (@pxref{Performance})@footnote{However, in 1998
                    616: the bar was raised when the major commercial Forth vendors switched to
                    617: native code compilers.}.  It is free and available on many machines.
1.29      crook     618: 
1.26      crook     619: @c ******************************************************************
1.48      anton     620: @node Gforth Environment, Tutorial, Goals, Top
1.29      crook     621: @chapter Gforth Environment
                    622: @cindex Gforth environment
1.21      crook     623: 
1.45      crook     624: Note: ultimately, the Gforth man page will be auto-generated from the
1.29      crook     625: material in this chapter.
1.21      crook     626: 
                    627: @menu
1.29      crook     628: * Invoking Gforth::             Getting in
                    629: * Leaving Gforth::              Getting out
                    630: * Command-line editing::        
1.48      anton     631: * Environment variables::       that affect how Gforth starts up
1.29      crook     632: * Gforth Files::                What gets installed and where
1.112     anton     633: * Gforth in pipes::             
1.204     anton     634: * Startup speed::               When 14ms is not fast enough ...
1.21      crook     635: @end menu
                    636: 
1.49      anton     637: For related information about the creation of images see @ref{Image Files}.
1.29      crook     638: 
1.21      crook     639: @comment ----------------------------------------------
1.48      anton     640: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29      crook     641: @section Invoking Gforth
                    642: @cindex invoking Gforth
                    643: @cindex running Gforth
                    644: @cindex command-line options
                    645: @cindex options on the command line
                    646: @cindex flags on the command line
1.21      crook     647: 
1.30      anton     648: Gforth is made up of two parts; an executable ``engine'' (named
1.109     anton     649: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30      anton     650: will usually just say @code{gforth} -- this automatically loads the
                    651: default image file @file{gforth.fi}. In many other cases the default
                    652: Gforth image will be invoked like this:
1.21      crook     653: @example
1.30      anton     654: gforth [file | -e forth-code] ...
1.21      crook     655: @end example
1.29      crook     656: @noindent
                    657: This interprets the contents of the files and the Forth code in the order they
                    658: are given.
1.21      crook     659: 
1.109     anton     660: In addition to the @command{gforth} engine, there is also an engine
                    661: called @command{gforth-fast}, which is faster, but gives less
                    662: informative error messages (@pxref{Error messages}) and may catch some
1.166     anton     663: errors (in particular, stack underflows and integer division errors)
                    664: later or not at all.  You should use it for debugged,
1.109     anton     665: performance-critical programs.
                    666: 
                    667: Moreover, there is an engine called @command{gforth-itc}, which is
                    668: useful in some backwards-compatibility situations (@pxref{Direct or
                    669: Indirect Threaded?}).
1.30      anton     670: 
1.29      crook     671: In general, the command line looks like this:
1.21      crook     672: 
                    673: @example
1.30      anton     674: gforth[-fast] [engine options] [image options]
1.21      crook     675: @end example
                    676: 
1.30      anton     677: The engine options must come before the rest of the command
1.29      crook     678: line. They are:
1.26      crook     679: 
1.29      crook     680: @table @code
                    681: @cindex -i, command-line option
                    682: @cindex --image-file, command-line option
                    683: @item --image-file @i{file}
                    684: @itemx -i @i{file}
                    685: Loads the Forth image @i{file} instead of the default
                    686: @file{gforth.fi} (@pxref{Image Files}).
1.21      crook     687: 
1.39      anton     688: @cindex --appl-image, command-line option
                    689: @item --appl-image @i{file}
                    690: Loads the image @i{file} and leaves all further command-line arguments
1.65      anton     691: to the image (instead of processing them as engine options).  This is
                    692: useful for building executable application images on Unix, built with
1.39      anton     693: @code{gforthmi --application ...}.
                    694: 
1.29      crook     695: @cindex --path, command-line option
                    696: @cindex -p, command-line option
                    697: @item --path @i{path}
                    698: @itemx -p @i{path}
                    699: Uses @i{path} for searching the image file and Forth source code files
                    700: instead of the default in the environment variable @code{GFORTHPATH} or
                    701: the path specified at installation time (e.g.,
                    702: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
                    703: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21      crook     704: 
1.29      crook     705: @cindex --dictionary-size, command-line option
                    706: @cindex -m, command-line option
                    707: @cindex @i{size} parameters for command-line options
                    708: @cindex size of the dictionary and the stacks
                    709: @item --dictionary-size @i{size}
                    710: @itemx -m @i{size}
                    711: Allocate @i{size} space for the Forth dictionary space instead of
                    712: using the default specified in the image (typically 256K). The
                    713: @i{size} specification for this and subsequent options consists of
                    714: an integer and a unit (e.g.,
                    715: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
                    716: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
                    717: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
                    718: @code{e} is used.
1.21      crook     719: 
1.29      crook     720: @cindex --data-stack-size, command-line option
                    721: @cindex -d, command-line option
                    722: @item --data-stack-size @i{size}
                    723: @itemx -d @i{size}
                    724: Allocate @i{size} space for the data stack instead of using the
                    725: default specified in the image (typically 16K).
1.21      crook     726: 
1.29      crook     727: @cindex --return-stack-size, command-line option
                    728: @cindex -r, command-line option
                    729: @item --return-stack-size @i{size}
                    730: @itemx -r @i{size}
                    731: Allocate @i{size} space for the return stack instead of using the
                    732: default specified in the image (typically 15K).
1.21      crook     733: 
1.29      crook     734: @cindex --fp-stack-size, command-line option
                    735: @cindex -f, command-line option
                    736: @item --fp-stack-size @i{size}
                    737: @itemx -f @i{size}
                    738: Allocate @i{size} space for the floating point stack instead of
                    739: using the default specified in the image (typically 15.5K). In this case
                    740: the unit specifier @code{e} refers to floating point numbers.
1.21      crook     741: 
1.48      anton     742: @cindex --locals-stack-size, command-line option
                    743: @cindex -l, command-line option
                    744: @item --locals-stack-size @i{size}
                    745: @itemx -l @i{size}
                    746: Allocate @i{size} space for the locals stack instead of using the
                    747: default specified in the image (typically 14.5K).
                    748: 
1.176     anton     749: @cindex --vm-commit, command-line option
                    750: @cindex overcommit memory for dictionary and stacks
                    751: @cindex memory overcommit for dictionary and stacks
                    752: @item --vm-commit
                    753: Normally, Gforth tries to start up even if there is not enough virtual
                    754: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
                    755: on OSs that support it); so you can ask for a really big dictionary
                    756: and/or stacks, and as long as you don't use more virtual memory than
                    757: is available, everything will be fine (but if you use more, processes
                    758: get killed).  With this option you just use the default allocation
                    759: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
                    760: means that you cannot and should not ask for as big dictionary and
                    761: stacks, but once Gforth successfully starts up, out-of-memory won't
                    762: kill it.
                    763: 
1.48      anton     764: @cindex -h, command-line option
                    765: @cindex --help, command-line option
                    766: @item --help
                    767: @itemx -h
                    768: Print a message about the command-line options
                    769: 
                    770: @cindex -v, command-line option
                    771: @cindex --version, command-line option
                    772: @item --version
                    773: @itemx -v
                    774: Print version and exit
                    775: 
                    776: @cindex --debug, command-line option
                    777: @item --debug
                    778: Print some information useful for debugging on startup.
                    779: 
                    780: @cindex --offset-image, command-line option
                    781: @item --offset-image
                    782: Start the dictionary at a slightly different position than would be used
                    783: otherwise (useful for creating data-relocatable images,
                    784: @pxref{Data-Relocatable Image Files}).
                    785: 
                    786: @cindex --no-offset-im, command-line option
                    787: @item --no-offset-im
                    788: Start the dictionary at the normal position.
                    789: 
                    790: @cindex --clear-dictionary, command-line option
                    791: @item --clear-dictionary
                    792: Initialize all bytes in the dictionary to 0 before loading the image
                    793: (@pxref{Data-Relocatable Image Files}).
                    794: 
                    795: @cindex --die-on-signal, command-line-option
                    796: @item --die-on-signal
                    797: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
                    798: or the segmentation violation SIGSEGV) by translating it into a Forth
                    799: @code{THROW}. With this option, Gforth exits if it receives such a
                    800: signal. This option is useful when the engine and/or the image might be
                    801: severely broken (such that it causes another signal before recovering
                    802: from the first); this option avoids endless loops in such cases.
1.109     anton     803: 
1.119     anton     804: @cindex --no-dynamic, command-line option
                    805: @cindex --dynamic, command-line option
1.109     anton     806: @item --no-dynamic
                    807: @item --dynamic
                    808: Disable or enable dynamic superinstructions with replication
                    809: (@pxref{Dynamic Superinstructions}).
                    810: 
1.119     anton     811: @cindex --no-super, command-line option
1.109     anton     812: @item --no-super
1.110     anton     813: Disable dynamic superinstructions, use just dynamic replication; this is
                    814: useful if you want to patch threaded code (@pxref{Dynamic
                    815: Superinstructions}).
1.119     anton     816: 
                    817: @cindex --ss-number, command-line option
                    818: @item --ss-number=@var{N}
                    819: Use only the first @var{N} static superinstructions compiled into the
                    820: engine (default: use them all; note that only @code{gforth-fast} has
                    821: any).  This option is useful for measuring the performance impact of
                    822: static superinstructions.
                    823: 
                    824: @cindex --ss-min-..., command-line options
                    825: @item --ss-min-codesize
                    826: @item --ss-min-ls
                    827: @item --ss-min-lsu
                    828: @item --ss-min-nexts
                    829: Use specified metric for determining the cost of a primitive or static
                    830: superinstruction for static superinstruction selection.  @code{Codesize}
                    831: is the native code size of the primive or static superinstruction,
                    832: @code{ls} is the number of loads and stores, @code{lsu} is the number of
                    833: loads, stores, and updates, and @code{nexts} is the number of dispatches
                    834: (not taking dynamic superinstructions into account), i.e. every
                    835: primitive or static superinstruction has cost 1. Default:
                    836: @code{codesize} if you use dynamic code generation, otherwise
                    837: @code{nexts}.
                    838: 
                    839: @cindex --ss-greedy, command-line option
                    840: @item --ss-greedy
                    841: This option is useful for measuring the performance impact of static
                    842: superinstructions.  By default, an optimal shortest-path algorithm is
                    843: used for selecting static superinstructions.  With @option{--ss-greedy}
                    844: this algorithm is modified to assume that anything after the static
                    845: superinstruction currently under consideration is not combined into
                    846: static superinstructions.  With @option{--ss-min-nexts} this produces
                    847: the same result as a greedy algorithm that always selects the longest
                    848: superinstruction available at the moment.  E.g., if there are
                    849: superinstructions AB and BCD, then for the sequence A B C D the optimal
                    850: algorithm will select A BCD and the greedy algorithm will select AB C D.
                    851: 
                    852: @cindex --print-metrics, command-line option
                    853: @item --print-metrics
                    854: Prints some metrics used during static superinstruction selection:
                    855: @code{code size} is the actual size of the dynamically generated code.
                    856: @code{Metric codesize} is the sum of the codesize metrics as seen by
                    857: static superinstruction selection; there is a difference from @code{code
                    858: size}, because not all primitives and static superinstructions are
                    859: compiled into dynamically generated code, and because of markers.  The
                    860: other metrics correspond to the @option{ss-min-...} options.  This
                    861: option is useful for evaluating the effects of the @option{--ss-...}
                    862: options.
1.109     anton     863: 
1.48      anton     864: @end table
                    865: 
                    866: @cindex loading files at startup
                    867: @cindex executing code on startup
                    868: @cindex batch processing with Gforth
                    869: As explained above, the image-specific command-line arguments for the
                    870: default image @file{gforth.fi} consist of a sequence of filenames and
                    871: @code{-e @var{forth-code}} options that are interpreted in the sequence
                    872: in which they are given. The @code{-e @var{forth-code}} or
1.121     anton     873: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
                    874: option takes only one argument; if you want to evaluate more Forth
                    875: words, you have to quote them or use @code{-e} several times. To exit
1.48      anton     876: after processing the command line (instead of entering interactive mode)
1.121     anton     877: append @code{-e bye} to the command line.  You can also process the
                    878: command-line arguments with a Forth program (@pxref{OS command line
                    879: arguments}).
1.48      anton     880: 
                    881: @cindex versions, invoking other versions of Gforth
                    882: If you have several versions of Gforth installed, @code{gforth} will
                    883: invoke the version that was installed last. @code{gforth-@i{version}}
                    884: invokes a specific version. If your environment contains the variable
                    885: @code{GFORTHPATH}, you may want to override it by using the
                    886: @code{--path} option.
                    887: 
                    888: Not yet implemented:
                    889: On startup the system first executes the system initialization file
                    890: (unless the option @code{--no-init-file} is given; note that the system
                    891: resulting from using this option may not be ANS Forth conformant). Then
                    892: the user initialization file @file{.gforth.fs} is executed, unless the
1.62      crook     893: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48      anton     894: then in @file{~}, then in the normal path (see above).
                    895: 
                    896: 
                    897: 
                    898: @comment ----------------------------------------------
                    899: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
                    900: @section Leaving Gforth
                    901: @cindex Gforth - leaving
                    902: @cindex leaving Gforth
                    903: 
                    904: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
                    905: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
                    906: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49      anton     907: data are discarded.  For ways of saving the state of the system before
                    908: leaving Gforth see @ref{Image Files}.
1.48      anton     909: 
                    910: doc-bye
                    911: 
                    912: 
                    913: @comment ----------------------------------------------
1.65      anton     914: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48      anton     915: @section Command-line editing
                    916: @cindex command-line editing
                    917: 
                    918: Gforth maintains a history file that records every line that you type to
                    919: the text interpreter. This file is preserved between sessions, and is
                    920: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
                    921: repeatedly you can recall successively older commands from this (or
                    922: previous) session(s). The full list of command-line editing facilities is:
                    923: 
                    924: @itemize @bullet
                    925: @item
                    926: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
                    927: commands from the history buffer.
                    928: @item
                    929: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
                    930: from the history buffer.
                    931: @item
                    932: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
                    933: @item
                    934: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
                    935: @item
                    936: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
                    937: closing up the line.
                    938: @item
                    939: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
                    940: @item
                    941: @kbd{Ctrl-a} to move the cursor to the start of the line.
                    942: @item
                    943: @kbd{Ctrl-e} to move the cursor to the end of the line.
                    944: @item
                    945: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
                    946: line.
                    947: @item
                    948: @key{TAB} to step through all possible full-word completions of the word
                    949: currently being typed.
                    950: @item
1.65      anton     951: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
                    952: using @code{bye}). 
                    953: @item
                    954: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
                    955: character under the cursor.
1.48      anton     956: @end itemize
                    957: 
                    958: When editing, displayable characters are inserted to the left of the
                    959: cursor position; the line is always in ``insert'' (as opposed to
                    960: ``overstrike'') mode.
                    961: 
                    962: @cindex history file
                    963: @cindex @file{.gforth-history}
                    964: On Unix systems, the history file is @file{~/.gforth-history} by
                    965: default@footnote{i.e. it is stored in the user's home directory.}. You
                    966: can find out the name and location of your history file using:
                    967: 
                    968: @example 
                    969: history-file type \ Unix-class systems
                    970: 
                    971: history-file type \ Other systems
                    972: history-dir  type
                    973: @end example
                    974: 
                    975: If you enter long definitions by hand, you can use a text editor to
                    976: paste them out of the history file into a Forth source file for reuse at
                    977: a later time.
                    978: 
                    979: Gforth never trims the size of the history file, so you should do this
                    980: periodically, if necessary.
                    981: 
                    982: @comment this is all defined in history.fs
                    983: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
                    984: @comment chosen?
                    985: 
                    986: 
                    987: @comment ----------------------------------------------
1.65      anton     988: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48      anton     989: @section Environment variables
                    990: @cindex environment variables
                    991: 
                    992: Gforth uses these environment variables:
                    993: 
                    994: @itemize @bullet
                    995: @item
                    996: @cindex @code{GFORTHHIST} -- environment variable
                    997: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
                    998: open/create the history file, @file{.gforth-history}. Default:
                    999: @code{$HOME}.
                   1000: 
                   1001: @item
                   1002: @cindex @code{GFORTHPATH} -- environment variable
                   1003: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
                   1004: for Forth source-code files.
                   1005: 
                   1006: @item
1.147     anton    1007: @cindex @code{LANG} -- environment variable
                   1008: @code{LANG} -- see @code{LC_CTYPE}
                   1009: 
                   1010: @item
                   1011: @cindex @code{LC_ALL} -- environment variable
                   1012: @code{LC_ALL} -- see @code{LC_CTYPE}
                   1013: 
                   1014: @item
                   1015: @cindex @code{LC_CTYPE} -- environment variable
                   1016: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
                   1017: startup, Gforth uses the UTF-8 encoding for strings internally and
                   1018: expects its input and produces its output in UTF-8 encoding, otherwise
                   1019: the encoding is 8bit (see @pxref{Xchars and Unicode}).  If this
                   1020: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
                   1021: that is unset, in @code{LANG}.
                   1022: 
                   1023: @item
1.129     anton    1024: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
                   1025: 
                   1026: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
                   1027: of @code{system} before passing it to C's @code{system()}.  Default:
1.130     anton    1028: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs.  The prefix
1.129     anton    1029: and the command are directly concatenated, so if a space between them is
                   1030: necessary, append it to the prefix.
                   1031: 
                   1032: @item
1.48      anton    1033: @cindex @code{GFORTH} -- environment variable
1.49      anton    1034: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1035: 
                   1036: @item
                   1037: @cindex @code{GFORTHD} -- environment variable
1.62      crook    1038: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48      anton    1039: 
                   1040: @item
                   1041: @cindex @code{TMP}, @code{TEMP} - environment variable
                   1042: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
                   1043: location for the history file.
                   1044: @end itemize
                   1045: 
                   1046: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
                   1047: @comment mentioning these.
                   1048: 
                   1049: All the Gforth environment variables default to sensible values if they
                   1050: are not set.
                   1051: 
                   1052: 
                   1053: @comment ----------------------------------------------
1.112     anton    1054: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48      anton    1055: @section Gforth files
                   1056: @cindex Gforth files
                   1057: 
                   1058: When you install Gforth on a Unix system, it installs files in these
                   1059: locations by default:
                   1060: 
                   1061: @itemize @bullet
                   1062: @item
                   1063: @file{/usr/local/bin/gforth}
                   1064: @item
                   1065: @file{/usr/local/bin/gforthmi}
                   1066: @item
                   1067: @file{/usr/local/man/man1/gforth.1} - man page.
                   1068: @item
                   1069: @file{/usr/local/info} - the Info version of this manual.
                   1070: @item
                   1071: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
                   1072: @item
                   1073: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
                   1074: @item
                   1075: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
                   1076: @item
                   1077: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
                   1078: @end itemize
                   1079: 
                   1080: You can select different places for installation by using
                   1081: @code{configure} options (listed with @code{configure --help}).
                   1082: 
                   1083: @comment ----------------------------------------------
1.112     anton    1084: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
                   1085: @section Gforth in pipes
                   1086: @cindex pipes, Gforth as part of
                   1087: 
                   1088: Gforth can be used in pipes created elsewhere (described here).  It can
                   1089: also create pipes on its own (@pxref{Pipes}).
                   1090: 
                   1091: @cindex input from pipes
                   1092: If you pipe into Gforth, your program should read with @code{read-file}
                   1093: or @code{read-line} from @code{stdin} (@pxref{General files}).
                   1094: @code{Key} does not recognize the end of input.  Words like
                   1095: @code{accept} echo the input and are therefore usually not useful for
                   1096: reading from a pipe.  You have to invoke the Forth program with an OS
                   1097: command-line option, as you have no chance to use the Forth command line
                   1098: (the text interpreter would try to interpret the pipe input).
                   1099: 
                   1100: @cindex output in pipes
                   1101: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
                   1102: 
                   1103: @cindex silent exiting from Gforth
                   1104: When you write to a pipe that has been closed at the other end, Gforth
                   1105: receives a SIGPIPE signal (``pipe broken'').  Gforth translates this
                   1106: into the exception @code{broken-pipe-error}.  If your application does
                   1107: not catch that exception, the system catches it and exits, usually
                   1108: silently (unless you were working on the Forth command line; then it
                   1109: prints an error message and exits).  This is usually the desired
                   1110: behaviour.
                   1111: 
                   1112: If you do not like this behaviour, you have to catch the exception
                   1113: yourself, and react to it.
                   1114: 
                   1115: Here's an example of an invocation of Gforth that is usable in a pipe:
                   1116: 
                   1117: @example
                   1118: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
                   1119:  type repeat ; foo bye"
                   1120: @end example
                   1121: 
                   1122: This example just copies the input verbatim to the output.  A very
                   1123: simple pipe containing this example looks like this:
                   1124: 
                   1125: @example
                   1126: cat startup.fs |
                   1127: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
                   1128:  type repeat ; foo bye"|
                   1129: head
                   1130: @end example
                   1131: 
                   1132: @cindex stderr and pipes
                   1133: Pipes involving Gforth's @code{stderr} output do not work.
                   1134: 
                   1135: @comment ----------------------------------------------
                   1136: @node Startup speed,  , Gforth in pipes, Gforth Environment
1.48      anton    1137: @section Startup speed
                   1138: @cindex Startup speed
                   1139: @cindex speed, startup
                   1140: 
                   1141: If Gforth is used for CGI scripts or in shell scripts, its startup
1.204     anton    1142: speed may become a problem.  On a 3GHz Core 2 Duo E8400 under 64-bit
                   1143: Linux 2.6.27.8 with libc-2.7, @code{gforth-fast -e bye} takes 13.1ms
                   1144: user and 1.2ms system time (@code{gforth -e bye} is faster on startup
                   1145: with about 3.4ms user time and 1.2ms system time, because it subsumes
                   1146: some of the options discussed below).
1.48      anton    1147: 
                   1148: If startup speed is a problem, you may consider the following ways to
                   1149: improve it; or you may consider ways to reduce the number of startups
1.204     anton    1150: (for example, by using Fast-CGI).  Note that the first steps below
                   1151: improve the startup time at the cost of run-time (including
                   1152: compile-time), so whether they are profitable depends on the balance
                   1153: of these times in your application.
                   1154: 
                   1155: An easy step that influences Gforth startup speed is the use of a
                   1156: number of options that increase run-time, but decrease image-loading
                   1157: time.
                   1158: 
                   1159: The first of these that you should try is @code{--ss-number=0
                   1160: --ss-states=1} because this option buys relatively little run-time
                   1161: speedup and costs quite a bit of time at startup.  @code{gforth-fast
                   1162: --ss-number=0 --ss-states=1 -e bye} takes about 2.8ms user and 1.5ms
                   1163: system time.
1.48      anton    1164: 
1.204     anton    1165: The next option is @code{--no-dynamic} which has a substantial impact
                   1166: on run-time (about a factor of 2 on several platforms), but still
                   1167: makes startup speed a little faster: @code{gforth-fast --ss-number=0
                   1168: --ss-states=1 --no-dynamic -e bye} consumes about 2.6ms user and 1.2ms
                   1169: system time.
                   1170: 
                   1171: The next step to improve startup speed is to use a data-relocatable
                   1172: image (@pxref{Data-Relocatable Image Files}).  This avoids the
                   1173: relocation cost for the code in the image (but not for the data).
                   1174: Note that the image is then specific to the particular binary you are
                   1175: using (i.e., whether it is @code{gforth}, @code{gforth-fast}, and even
                   1176: the particular build).  You create the data-relocatable image that
                   1177: works with @code{./gforth-fast} with @code{GFORTHD="./gforth-fast
                   1178: --no-dynamic" gforthmi gforthdr.fi} (the @code{--no-dynamic} is
                   1179: required here or the image will not work).  And you run it with
                   1180: @code{gforth-fast -i gforthdr.fi ... -e bye} (the flags discussed
                   1181: above don't matter here, because they only come into play on
                   1182: relocatable code).  @code{gforth-fast -i gforthdr.fi -e bye} takes
                   1183: about 1.1ms user and 1.2ms system time.
                   1184: 
                   1185: One step further is to avoid all relocation cost and part of the
                   1186: copy-on-write cost through using a non-relocatable image
                   1187: (@pxref{Non-Relocatable Image Files}).  However, this has the
                   1188: disadvantage that it does not work on operating systems with address
                   1189: space randomization (the default in, e.g., Linux nowadays), or if the
                   1190: dictionary moves for any other reason (e.g., because of a change of
                   1191: the OS kernel or an updated library), so we cannot really recommend
                   1192: it.  You create a non-relocatable image with @code{gforth-fast
                   1193: --no-dynamic -e "savesystem gforthnr.fi bye"} (the @code{--no-dynamic}
                   1194: is required here, too).  And you run it with @code{gforth-fast -i
                   1195: gforthnr.fi ... -e bye} (again the flags discussed above don't
                   1196: matter).  @code{gforth-fast -i gforthdr.fi -e bye} takes
                   1197: about 0.9ms user and 0.9ms system time.
                   1198: 
                   1199: If the script you want to execute contains a significant amount of
                   1200: code, it may be profitable to compile it into the image to avoid the
                   1201: cost of compiling it at startup time.
1.48      anton    1202: 
                   1203: @c ******************************************************************
                   1204: @node Tutorial, Introduction, Gforth Environment, Top
                   1205: @chapter Forth Tutorial
                   1206: @cindex Tutorial
                   1207: @cindex Forth Tutorial
                   1208: 
1.67      anton    1209: @c Topics from nac's Introduction that could be mentioned:
                   1210: @c press <ret> after each line
                   1211: @c Prompt
                   1212: @c numbers vs. words in dictionary on text interpretation
                   1213: @c what happens on redefinition
                   1214: @c parsing words (in particular, defining words)
                   1215: 
1.83      anton    1216: The difference of this chapter from the Introduction
                   1217: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
                   1218: be used while sitting in front of a computer, and covers much more
                   1219: material, but does not explain how the Forth system works.
                   1220: 
1.62      crook    1221: This tutorial can be used with any ANS-compliant Forth; any
1.206     anton    1222: Gforth-specific features are marked as such and you can skip them if
                   1223: you work with another Forth.  This tutorial does not explain all
                   1224: features of Forth, just enough to get you started and give you some
                   1225: ideas about the facilities available in Forth.  Read the rest of the
                   1226: manual when you are through this.
1.48      anton    1227: 
                   1228: The intended way to use this tutorial is that you work through it while
                   1229: sitting in front of the console, take a look at the examples and predict
                   1230: what they will do, then try them out; if the outcome is not as expected,
                   1231: find out why (e.g., by trying out variations of the example), so you
                   1232: understand what's going on.  There are also some assignments that you
                   1233: should solve.
                   1234: 
                   1235: This tutorial assumes that you have programmed before and know what,
                   1236: e.g., a loop is.
                   1237: 
                   1238: @c !! explain compat library
                   1239: 
                   1240: @menu
                   1241: * Starting Gforth Tutorial::    
                   1242: * Syntax Tutorial::             
                   1243: * Crash Course Tutorial::       
                   1244: * Stack Tutorial::              
                   1245: * Arithmetics Tutorial::        
                   1246: * Stack Manipulation Tutorial::  
                   1247: * Using files for Forth code Tutorial::  
                   1248: * Comments Tutorial::           
                   1249: * Colon Definitions Tutorial::  
                   1250: * Decompilation Tutorial::      
                   1251: * Stack-Effect Comments Tutorial::  
                   1252: * Types Tutorial::              
                   1253: * Factoring Tutorial::          
                   1254: * Designing the stack effect Tutorial::  
                   1255: * Local Variables Tutorial::    
                   1256: * Conditional execution Tutorial::  
                   1257: * Flags and Comparisons Tutorial::  
                   1258: * General Loops Tutorial::      
                   1259: * Counted loops Tutorial::      
                   1260: * Recursion Tutorial::          
                   1261: * Leaving definitions or loops Tutorial::  
                   1262: * Return Stack Tutorial::       
                   1263: * Memory Tutorial::             
                   1264: * Characters and Strings Tutorial::  
                   1265: * Alignment Tutorial::          
1.190     anton    1266: * Floating Point Tutorial::     
1.87      anton    1267: * Files Tutorial::              
1.48      anton    1268: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1269: * Execution Tokens Tutorial::   
                   1270: * Exceptions Tutorial::         
                   1271: * Defining Words Tutorial::     
                   1272: * Arrays and Records Tutorial::  
                   1273: * POSTPONE Tutorial::           
                   1274: * Literal Tutorial::            
                   1275: * Advanced macros Tutorial::    
                   1276: * Compilation Tokens Tutorial::  
                   1277: * Wordlists and Search Order Tutorial::  
                   1278: @end menu
                   1279: 
                   1280: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1281: @section Starting Gforth
1.66      anton    1282: @cindex starting Gforth tutorial
1.48      anton    1283: You can start Gforth by typing its name:
                   1284: 
                   1285: @example
                   1286: gforth
                   1287: @end example
                   1288: 
                   1289: That puts you into interactive mode; you can leave Gforth by typing
                   1290: @code{bye}.  While in Gforth, you can edit the command line and access
                   1291: the command line history with cursor keys, similar to bash.
                   1292: 
                   1293: 
                   1294: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1295: @section Syntax
1.66      anton    1296: @cindex syntax tutorial
1.48      anton    1297: 
1.171     anton    1298: A @dfn{word} is a sequence of arbitrary characters (except white
1.48      anton    1299: space).  Words are separated by white space.  E.g., each of the
                   1300: following lines contains exactly one word:
                   1301: 
                   1302: @example
                   1303: word
                   1304: !@@#$%^&*()
                   1305: 1234567890
                   1306: 5!a
                   1307: @end example
                   1308: 
1.205     anton    1309: A frequent beginner's error is to leave out necessary white space,
1.48      anton    1310: resulting in an error like @samp{Undefined word}; so if you see such an
                   1311: error, check if you have put spaces wherever necessary.
                   1312: 
                   1313: @example
                   1314: ." hello, world" \ correct
                   1315: ."hello, world"  \ gives an "Undefined word" error
                   1316: @end example
                   1317: 
1.65      anton    1318: Gforth and most other Forth systems ignore differences in case (they are
1.48      anton    1319: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1320: your system is case-sensitive, you may have to type all the examples
                   1321: given here in upper case.
                   1322: 
                   1323: 
                   1324: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1325: @section Crash Course
                   1326: 
1.209     anton    1327: Forth does not prevent you from shooting yourself in the foot.  Let's
                   1328: try a few ways to crash Gforth:
1.48      anton    1329: 
                   1330: @example
                   1331: 0 0 !
                   1332: here execute
                   1333: ' catch >body 20 erase abort
                   1334: ' (quit) >body 20 erase
                   1335: @end example
                   1336: 
1.209     anton    1337: The last two examples are guaranteed to destroy important parts of
                   1338: Gforth (and most other systems), so you better leave Gforth afterwards
                   1339: (if it has not finished by itself).  On some systems you may have to
                   1340: kill gforth from outside (e.g., in Unix with @code{kill}).
                   1341: 
                   1342: You will find out later what these lines do and then you will get an
                   1343: idea why they produce crashes.
1.48      anton    1344: 
                   1345: Now that you know how to produce crashes (and that there's not much to
                   1346: them), let's learn how to produce meaningful programs.
                   1347: 
                   1348: 
                   1349: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1350: @section Stack
1.66      anton    1351: @cindex stack tutorial
1.48      anton    1352: 
                   1353: The most obvious feature of Forth is the stack.  When you type in a
1.205     anton    1354: number, it is pushed on the stack.  You can display the contents of the
1.48      anton    1355: stack with @code{.s}.
                   1356: 
                   1357: @example
                   1358: 1 2 .s
                   1359: 3 .s
                   1360: @end example
                   1361: 
                   1362: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1363: appear in @code{.s} output as they appeared in the input.
                   1364: 
1.205     anton    1365: You can print the top element of the stack with @code{.}.
1.48      anton    1366: 
                   1367: @example
                   1368: 1 2 3 . . .
                   1369: @end example
                   1370: 
                   1371: In general, words consume their stack arguments (@code{.s} is an
                   1372: exception).
                   1373: 
1.141     anton    1374: @quotation Assignment
1.48      anton    1375: What does the stack contain after @code{5 6 7 .}?
1.141     anton    1376: @end quotation
1.48      anton    1377: 
                   1378: 
                   1379: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1380: @section Arithmetics
1.66      anton    1381: @cindex arithmetics tutorial
1.48      anton    1382: 
                   1383: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1384: operate on the top two stack items:
                   1385: 
                   1386: @example
1.67      anton    1387: 2 2 .s
                   1388: + .s
                   1389: .
1.48      anton    1390: 2 1 - .
                   1391: 7 3 mod .
                   1392: @end example
                   1393: 
                   1394: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1395: as in the corresponding infix expression (this is generally the case in
                   1396: Forth).
                   1397: 
                   1398: Parentheses are superfluous (and not available), because the order of
                   1399: the words unambiguously determines the order of evaluation and the
                   1400: operands:
                   1401: 
                   1402: @example
                   1403: 3 4 + 5 * .
                   1404: 3 4 5 * + .
                   1405: @end example
                   1406: 
1.141     anton    1407: @quotation Assignment
1.48      anton    1408: What are the infix expressions corresponding to the Forth code above?
                   1409: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1410: known as Postfix or RPN (Reverse Polish Notation).}.
1.141     anton    1411: @end quotation
1.48      anton    1412: 
                   1413: To change the sign, use @code{negate}:
                   1414: 
                   1415: @example
                   1416: 2 negate .
                   1417: @end example
                   1418: 
1.141     anton    1419: @quotation Assignment
1.48      anton    1420: Convert -(-3)*4-5 to Forth.
1.141     anton    1421: @end quotation
1.48      anton    1422: 
                   1423: @code{/mod} performs both @code{/} and @code{mod}.
                   1424: 
                   1425: @example
                   1426: 7 3 /mod . .
                   1427: @end example
                   1428: 
1.66      anton    1429: Reference: @ref{Arithmetic}.
                   1430: 
                   1431: 
1.48      anton    1432: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1433: @section Stack Manipulation
1.66      anton    1434: @cindex stack manipulation tutorial
1.48      anton    1435: 
                   1436: Stack manipulation words rearrange the data on the stack.
                   1437: 
                   1438: @example
                   1439: 1 .s drop .s
                   1440: 1 .s dup .s drop drop .s
                   1441: 1 2 .s over .s drop drop drop
                   1442: 1 2 .s swap .s drop drop
                   1443: 1 2 3 .s rot .s drop drop drop
                   1444: @end example
                   1445: 
                   1446: These are the most important stack manipulation words.  There are also
                   1447: variants that manipulate twice as many stack items:
                   1448: 
                   1449: @example
                   1450: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1451: @end example
                   1452: 
                   1453: Two more stack manipulation words are:
                   1454: 
                   1455: @example
                   1456: 1 2 .s nip .s drop
                   1457: 1 2 .s tuck .s 2drop drop
                   1458: @end example
                   1459: 
1.141     anton    1460: @quotation Assignment
1.48      anton    1461: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1462: manipulation words.
                   1463: 
                   1464: @example
                   1465: Given:          How do you get:
                   1466: 1 2 3           3 2 1           
                   1467: 1 2 3           1 2 3 2                 
                   1468: 1 2 3           1 2 3 3                 
                   1469: 1 2 3           1 3 3           
                   1470: 1 2 3           2 1 3           
                   1471: 1 2 3 4         4 3 2 1         
                   1472: 1 2 3           1 2 3 1 2 3             
                   1473: 1 2 3 4         1 2 3 4 1 2             
                   1474: 1 2 3
                   1475: 1 2 3           1 2 3 4                 
                   1476: 1 2 3           1 3             
                   1477: @end example
1.141     anton    1478: @end quotation
1.48      anton    1479: 
                   1480: @example
                   1481: 5 dup * .
                   1482: @end example
                   1483: 
1.141     anton    1484: @quotation Assignment
1.48      anton    1485: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1486: Write a piece of Forth code that expects two numbers on the stack
                   1487: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1488: @code{(a-b)(a+1)}.
1.141     anton    1489: @end quotation
1.48      anton    1490: 
1.66      anton    1491: Reference: @ref{Stack Manipulation}.
                   1492: 
                   1493: 
1.48      anton    1494: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1495: @section Using files for Forth code
1.66      anton    1496: @cindex loading Forth code, tutorial
                   1497: @cindex files containing Forth code, tutorial
1.48      anton    1498: 
                   1499: While working at the Forth command line is convenient for one-line
                   1500: examples and short one-off code, you probably want to store your source
                   1501: code in files for convenient editing and persistence.  You can use your
                   1502: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102     anton    1503: Gforth}) to create @var{file.fs} and use
1.48      anton    1504: 
                   1505: @example
1.102     anton    1506: s" @var{file.fs}" included
1.48      anton    1507: @end example
                   1508: 
                   1509: to load it into your Forth system.  The file name extension I use for
                   1510: Forth files is @samp{.fs}.
                   1511: 
                   1512: You can easily start Gforth with some files loaded like this:
                   1513: 
                   1514: @example
1.102     anton    1515: gforth @var{file1.fs} @var{file2.fs}
1.48      anton    1516: @end example
                   1517: 
                   1518: If an error occurs during loading these files, Gforth terminates,
                   1519: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1520: a Gforth command line.  Starting the Forth system every time gives you a
                   1521: clean start every time, without interference from the results of earlier
                   1522: tries.
                   1523: 
                   1524: I often put all the tests in a file, then load the code and run the
                   1525: tests with
                   1526: 
                   1527: @example
1.102     anton    1528: gforth @var{code.fs} @var{tests.fs} -e bye
1.48      anton    1529: @end example
                   1530: 
                   1531: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1532: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1533: restart this command without ado.
                   1534: 
                   1535: The advantage of this approach is that the tests can be repeated easily
                   1536: every time the program ist changed, making it easy to catch bugs
                   1537: introduced by the change.
                   1538: 
1.66      anton    1539: Reference: @ref{Forth source files}.
                   1540: 
1.48      anton    1541: 
                   1542: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1543: @section Comments
1.66      anton    1544: @cindex comments tutorial
1.48      anton    1545: 
                   1546: @example
                   1547: \ That's a comment; it ends at the end of the line
                   1548: ( Another comment; it ends here: )  .s
                   1549: @end example
                   1550: 
                   1551: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1552: separated with white space from the following text.
                   1553: 
                   1554: @example
                   1555: \This gives an "Undefined word" error
                   1556: @end example
                   1557: 
                   1558: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1559: nest @code{(}-comments; and you cannot comment out text containing a
                   1560: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1561: avoid @code{)} in word names.}.
                   1562: 
                   1563: I use @code{\}-comments for descriptive text and for commenting out code
                   1564: of one or more line; I use @code{(}-comments for describing the stack
                   1565: effect, the stack contents, or for commenting out sub-line pieces of
                   1566: code.
                   1567: 
                   1568: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1569: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1570: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1571: with @kbd{M-q}.
                   1572: 
1.66      anton    1573: Reference: @ref{Comments}.
                   1574: 
1.48      anton    1575: 
                   1576: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1577: @section Colon Definitions
1.66      anton    1578: @cindex colon definitions, tutorial
                   1579: @cindex definitions, tutorial
                   1580: @cindex procedures, tutorial
                   1581: @cindex functions, tutorial
1.48      anton    1582: 
                   1583: are similar to procedures and functions in other programming languages.
                   1584: 
                   1585: @example
                   1586: : squared ( n -- n^2 )
                   1587:    dup * ;
                   1588: 5 squared .
                   1589: 7 squared .
                   1590: @end example
                   1591: 
                   1592: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1593: following comment describes its stack effect.  The words @code{dup *}
                   1594: are not executed, but compiled into the definition.  @code{;} ends the
                   1595: colon definition.
                   1596: 
                   1597: The newly-defined word can be used like any other word, including using
                   1598: it in other definitions:
                   1599: 
                   1600: @example
                   1601: : cubed ( n -- n^3 )
                   1602:    dup squared * ;
                   1603: -5 cubed .
                   1604: : fourth-power ( n -- n^4 )
                   1605:    squared squared ;
                   1606: 3 fourth-power .
                   1607: @end example
                   1608: 
1.141     anton    1609: @quotation Assignment
1.48      anton    1610: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1611: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1612: test your tests on the originals first).  Don't let the
                   1613: @samp{redefined}-Messages spook you, they are just warnings.
1.141     anton    1614: @end quotation
1.48      anton    1615: 
1.66      anton    1616: Reference: @ref{Colon Definitions}.
                   1617: 
1.48      anton    1618: 
                   1619: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1620: @section Decompilation
1.66      anton    1621: @cindex decompilation tutorial
                   1622: @cindex see tutorial
1.48      anton    1623: 
                   1624: You can decompile colon definitions with @code{see}:
                   1625: 
                   1626: @example
                   1627: see squared
                   1628: see cubed
                   1629: @end example
                   1630: 
                   1631: In Gforth @code{see} shows you a reconstruction of the source code from
                   1632: the executable code.  Informations that were present in the source, but
                   1633: not in the executable code, are lost (e.g., comments).
                   1634: 
1.65      anton    1635: You can also decompile the predefined words:
                   1636: 
                   1637: @example
                   1638: see .
                   1639: see +
                   1640: @end example
                   1641: 
                   1642: 
1.48      anton    1643: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1644: @section Stack-Effect Comments
1.66      anton    1645: @cindex stack-effect comments, tutorial
                   1646: @cindex --, tutorial
1.48      anton    1647: By convention the comment after the name of a definition describes the
1.171     anton    1648: stack effect: The part in front of the @samp{--} describes the state of
1.48      anton    1649: the stack before the execution of the definition, i.e., the parameters
                   1650: that are passed into the colon definition; the part behind the @samp{--}
                   1651: is the state of the stack after the execution of the definition, i.e.,
                   1652: the results of the definition.  The stack comment only shows the top
                   1653: stack items that the definition accesses and/or changes.
                   1654: 
                   1655: You should put a correct stack effect on every definition, even if it is
                   1656: just @code{( -- )}.  You should also add some descriptive comment to
                   1657: more complicated words (I usually do this in the lines following
                   1658: @code{:}).  If you don't do this, your code becomes unreadable (because
1.117     anton    1659: you have to work through every definition before you can understand
1.48      anton    1660: any).
                   1661: 
1.141     anton    1662: @quotation Assignment
1.48      anton    1663: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1664: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1665: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
1.65      anton    1666: are done, you can compare your stack effects to those in this manual
1.48      anton    1667: (@pxref{Word Index}).
1.141     anton    1668: @end quotation
1.48      anton    1669: 
                   1670: Sometimes programmers put comments at various places in colon
                   1671: definitions that describe the contents of the stack at that place (stack
                   1672: comments); i.e., they are like the first part of a stack-effect
                   1673: comment. E.g.,
                   1674: 
                   1675: @example
                   1676: : cubed ( n -- n^3 )
                   1677:    dup squared  ( n n^2 ) * ;
                   1678: @end example
                   1679: 
                   1680: In this case the stack comment is pretty superfluous, because the word
                   1681: is simple enough.  If you think it would be a good idea to add such a
                   1682: comment to increase readability, you should also consider factoring the
                   1683: word into several simpler words (@pxref{Factoring Tutorial,,
1.60      anton    1684: Factoring}), which typically eliminates the need for the stack comment;
1.48      anton    1685: however, if you decide not to refactor it, then having such a comment is
                   1686: better than not having it.
                   1687: 
                   1688: The names of the stack items in stack-effect and stack comments in the
                   1689: standard, in this manual, and in many programs specify the type through
                   1690: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1691: frequent prefixes are:
                   1692: 
                   1693: @table @code
                   1694: @item n
                   1695: signed integer
                   1696: @item u
                   1697: unsigned integer
                   1698: @item c
                   1699: character
                   1700: @item f
                   1701: Boolean flags, i.e. @code{false} or @code{true}.
                   1702: @item a-addr,a-
                   1703: Cell-aligned address
                   1704: @item c-addr,c-
                   1705: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1706: @item xt
                   1707: Execution token, same size as Cell
                   1708: @item w,x
                   1709: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1710: 16 bits (depending on your platform and Forth system). A cell is more
                   1711: commonly known as machine word, but the term @emph{word} already means
                   1712: something different in Forth.
                   1713: @item d
                   1714: signed double-cell integer
                   1715: @item ud
                   1716: unsigned double-cell integer
                   1717: @item r
                   1718: Float (on the FP stack)
                   1719: @end table
                   1720: 
                   1721: You can find a more complete list in @ref{Notation}.
                   1722: 
1.141     anton    1723: @quotation Assignment
1.48      anton    1724: Write stack-effect comments for all definitions you have written up to
                   1725: now.
1.141     anton    1726: @end quotation
1.48      anton    1727: 
                   1728: 
                   1729: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1730: @section Types
1.66      anton    1731: @cindex types tutorial
1.48      anton    1732: 
                   1733: In Forth the names of the operations are not overloaded; so similar
                   1734: operations on different types need different names; e.g., @code{+} adds
                   1735: integers, and you have to use @code{f+} to add floating-point numbers.
                   1736: The following prefixes are often used for related operations on
                   1737: different types:
                   1738: 
                   1739: @table @code
                   1740: @item (none)
                   1741: signed integer
                   1742: @item u
                   1743: unsigned integer
                   1744: @item c
                   1745: character
                   1746: @item d
                   1747: signed double-cell integer
                   1748: @item ud, du
                   1749: unsigned double-cell integer
                   1750: @item 2
                   1751: two cells (not-necessarily double-cell numbers)
                   1752: @item m, um
                   1753: mixed single-cell and double-cell operations
                   1754: @item f
                   1755: floating-point (note that in stack comments @samp{f} represents flags,
1.210     anton    1756: and @samp{r} represents FP numbers; also, you need to include the
                   1757: exponent part in literal FP numbers, @pxref{Floating Point Tutorial}).
1.48      anton    1758: @end table
                   1759: 
                   1760: If there are no differences between the signed and the unsigned variant
                   1761: (e.g., for @code{+}), there is only the prefix-less variant.
                   1762: 
                   1763: Forth does not perform type checking, neither at compile time, nor at
1.210     anton    1764: run time.  If you use the wrong operation, the data are interpreted
1.48      anton    1765: incorrectly:
                   1766: 
                   1767: @example
                   1768: -1 u.
                   1769: @end example
                   1770: 
                   1771: If you have only experience with type-checked languages until now, and
                   1772: have heard how important type-checking is, don't panic!  In my
                   1773: experience (and that of other Forthers), type errors in Forth code are
                   1774: usually easy to find (once you get used to it), the increased vigilance
                   1775: of the programmer tends to catch some harder errors in addition to most
                   1776: type errors, and you never have to work around the type system, so in
                   1777: most situations the lack of type-checking seems to be a win (projects to
                   1778: add type checking to Forth have not caught on).
                   1779: 
                   1780: 
                   1781: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   1782: @section Factoring
1.66      anton    1783: @cindex factoring tutorial
1.48      anton    1784: 
                   1785: If you try to write longer definitions, you will soon find it hard to
                   1786: keep track of the stack contents.  Therefore, good Forth programmers
                   1787: tend to write only short definitions (e.g., three lines).  The art of
                   1788: finding meaningful short definitions is known as factoring (as in
                   1789: factoring polynomials).
                   1790: 
                   1791: Well-factored programs offer additional advantages: smaller, more
                   1792: general words, are easier to test and debug and can be reused more and
                   1793: better than larger, specialized words.
                   1794: 
                   1795: So, if you run into difficulties with stack management, when writing
                   1796: code, try to define meaningful factors for the word, and define the word
                   1797: in terms of those.  Even if a factor contains only two words, it is
                   1798: often helpful.
                   1799: 
1.65      anton    1800: Good factoring is not easy, and it takes some practice to get the knack
                   1801: for it; but even experienced Forth programmers often don't find the
                   1802: right solution right away, but only when rewriting the program.  So, if
                   1803: you don't come up with a good solution immediately, keep trying, don't
                   1804: despair.
1.48      anton    1805: 
                   1806: @c example !!
                   1807: 
                   1808: 
                   1809: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   1810: @section Designing the stack effect
1.66      anton    1811: @cindex Stack effect design, tutorial
                   1812: @cindex design of stack effects, tutorial
1.48      anton    1813: 
                   1814: In other languages you can use an arbitrary order of parameters for a
1.65      anton    1815: function; and since there is only one result, you don't have to deal with
1.48      anton    1816: the order of results, either.
                   1817: 
1.117     anton    1818: In Forth (and other stack-based languages, e.g., PostScript) the
1.48      anton    1819: parameter and result order of a definition is important and should be
                   1820: designed well.  The general guideline is to design the stack effect such
                   1821: that the word is simple to use in most cases, even if that complicates
                   1822: the implementation of the word.  Some concrete rules are:
                   1823: 
                   1824: @itemize @bullet
                   1825: 
                   1826: @item
                   1827: Words consume all of their parameters (e.g., @code{.}).
                   1828: 
                   1829: @item
                   1830: If there is a convention on the order of parameters (e.g., from
                   1831: mathematics or another programming language), stick with it (e.g.,
                   1832: @code{-}).
                   1833: 
                   1834: @item
                   1835: If one parameter usually requires only a short computation (e.g., it is
                   1836: a constant), pass it on the top of the stack.  Conversely, parameters
                   1837: that usually require a long sequence of code to compute should be passed
                   1838: as the bottom (i.e., first) parameter.  This makes the code easier to
1.171     anton    1839: read, because the reader does not need to keep track of the bottom item
1.48      anton    1840: through a long sequence of code (or, alternatively, through stack
1.49      anton    1841: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    1842: address on top of the stack because it is usually simpler to compute
                   1843: than the stored value (often the address is just a variable).
                   1844: 
                   1845: @item
                   1846: Similarly, results that are usually consumed quickly should be returned
                   1847: on the top of stack, whereas a result that is often used in long
                   1848: computations should be passed as bottom result.  E.g., the file words
                   1849: like @code{open-file} return the error code on the top of stack, because
                   1850: it is usually consumed quickly by @code{throw}; moreover, the error code
                   1851: has to be checked before doing anything with the other results.
                   1852: 
                   1853: @end itemize
                   1854: 
                   1855: These rules are just general guidelines, don't lose sight of the overall
                   1856: goal to make the words easy to use.  E.g., if the convention rule
                   1857: conflicts with the computation-length rule, you might decide in favour
                   1858: of the convention if the word will be used rarely, and in favour of the
                   1859: computation-length rule if the word will be used frequently (because
                   1860: with frequent use the cost of breaking the computation-length rule would
                   1861: be quite high, and frequent use makes it easier to remember an
                   1862: unconventional order).
                   1863: 
                   1864: @c example !! structure package
                   1865: 
1.65      anton    1866: 
1.48      anton    1867: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   1868: @section Local Variables
1.66      anton    1869: @cindex local variables, tutorial
1.48      anton    1870: 
                   1871: You can define local variables (@emph{locals}) in a colon definition:
                   1872: 
                   1873: @example
                   1874: : swap @{ a b -- b a @}
                   1875:   b a ;
                   1876: 1 2 swap .s 2drop
                   1877: @end example
                   1878: 
                   1879: (If your Forth system does not support this syntax, include
1.187     anton    1880: @file{compat/anslocal.fs} first).
1.48      anton    1881: 
                   1882: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   1883: takes two cells from the stack, puts the top of stack in @code{b} and
                   1884: the next stack element in @code{a}.  @code{--} starts a comment ending
                   1885: with @code{@}}.  After the locals definition, using the name of the
                   1886: local will push its value on the stack.  You can leave the comment
                   1887: part (@code{-- b a}) away:
                   1888: 
                   1889: @example
                   1890: : swap ( x1 x2 -- x2 x1 )
                   1891:   @{ a b @} b a ;
                   1892: @end example
                   1893: 
                   1894: In Gforth you can have several locals definitions, anywhere in a colon
                   1895: definition; in contrast, in a standard program you can have only one
                   1896: locals definition per colon definition, and that locals definition must
1.163     anton    1897: be outside any control structure.
1.48      anton    1898: 
                   1899: With locals you can write slightly longer definitions without running
                   1900: into stack trouble.  However, I recommend trying to write colon
                   1901: definitions without locals for exercise purposes to help you gain the
                   1902: essential factoring skills.
                   1903: 
1.141     anton    1904: @quotation Assignment
1.48      anton    1905: Rewrite your definitions until now with locals
1.141     anton    1906: @end quotation
1.48      anton    1907: 
1.66      anton    1908: Reference: @ref{Locals}.
                   1909: 
1.48      anton    1910: 
                   1911: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   1912: @section Conditional execution
1.66      anton    1913: @cindex conditionals, tutorial
                   1914: @cindex if, tutorial
1.48      anton    1915: 
                   1916: In Forth you can use control structures only inside colon definitions.
                   1917: An @code{if}-structure looks like this:
                   1918: 
                   1919: @example
                   1920: : abs ( n1 -- +n2 )
                   1921:     dup 0 < if
                   1922:         negate
                   1923:     endif ;
                   1924: 5 abs .
                   1925: -5 abs .
                   1926: @end example
                   1927: 
                   1928: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   1929: the following code is performed, otherwise execution continues after the
1.51      pazsan   1930: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.171     anton    1931: elements and produces a flag:
1.48      anton    1932: 
                   1933: @example
                   1934: 1 2 < .
                   1935: 2 1 < .
                   1936: 1 1 < .
                   1937: @end example
                   1938: 
                   1939: Actually the standard name for @code{endif} is @code{then}.  This
                   1940: tutorial presents the examples using @code{endif}, because this is often
                   1941: less confusing for people familiar with other programming languages
                   1942: where @code{then} has a different meaning.  If your system does not have
                   1943: @code{endif}, define it with
                   1944: 
                   1945: @example
                   1946: : endif postpone then ; immediate
                   1947: @end example
                   1948: 
                   1949: You can optionally use an @code{else}-part:
                   1950: 
                   1951: @example
                   1952: : min ( n1 n2 -- n )
                   1953:   2dup < if
                   1954:     drop
                   1955:   else
                   1956:     nip
                   1957:   endif ;
                   1958: 2 3 min .
                   1959: 3 2 min .
                   1960: @end example
                   1961: 
1.141     anton    1962: @quotation Assignment
1.48      anton    1963: Write @code{min} without @code{else}-part (hint: what's the definition
                   1964: of @code{nip}?).
1.141     anton    1965: @end quotation
1.48      anton    1966: 
1.66      anton    1967: Reference: @ref{Selection}.
                   1968: 
1.48      anton    1969: 
                   1970: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   1971: @section Flags and Comparisons
1.66      anton    1972: @cindex flags tutorial
                   1973: @cindex comparison tutorial
1.48      anton    1974: 
                   1975: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   1976: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   1977: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   1978: treated as true flag.
                   1979: 
                   1980: @example
                   1981: false .
                   1982: true .
                   1983: true hex u. decimal
                   1984: @end example
                   1985: 
                   1986: Comparison words produce canonical flags:
                   1987: 
                   1988: @example
                   1989: 1 1 = .
                   1990: 1 0= .
                   1991: 0 1 < .
                   1992: 0 0 < .
                   1993: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   1994: -1 1 < .
                   1995: @end example
                   1996: 
1.66      anton    1997: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
                   1998: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
                   1999: these combinations are standard (for details see the standard,
                   2000: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48      anton    2001: 
1.171     anton    2002: You can use @code{and or xor invert} as operations on canonical flags.
                   2003: Actually they are bitwise operations:
1.48      anton    2004: 
                   2005: @example
                   2006: 1 2 and .
                   2007: 1 2 or .
                   2008: 1 3 xor .
                   2009: 1 invert .
                   2010: @end example
                   2011: 
                   2012: You can convert a zero/non-zero flag into a canonical flag with
                   2013: @code{0<>} (and complement it on the way with @code{0=}).
                   2014: 
                   2015: @example
                   2016: 1 0= .
                   2017: 1 0<> .
                   2018: @end example
                   2019: 
1.65      anton    2020: You can use the all-bits-set feature of canonical flags and the bitwise
1.48      anton    2021: operation of the Boolean operations to avoid @code{if}s:
                   2022: 
                   2023: @example
                   2024: : foo ( n1 -- n2 )
                   2025:   0= if
                   2026:     14
                   2027:   else
                   2028:     0
                   2029:   endif ;
                   2030: 0 foo .
                   2031: 1 foo .
                   2032: 
                   2033: : foo ( n1 -- n2 )
                   2034:   0= 14 and ;
                   2035: 0 foo .
                   2036: 1 foo .
                   2037: @end example
                   2038: 
1.141     anton    2039: @quotation Assignment
1.48      anton    2040: Write @code{min} without @code{if}.
1.141     anton    2041: @end quotation
1.48      anton    2042: 
1.66      anton    2043: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
                   2044: @ref{Bitwise operations}.
                   2045: 
1.48      anton    2046: 
                   2047: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   2048: @section General Loops
1.66      anton    2049: @cindex loops, indefinite, tutorial
1.48      anton    2050: 
                   2051: The endless loop is the most simple one:
                   2052: 
                   2053: @example
                   2054: : endless ( -- )
                   2055:   0 begin
                   2056:     dup . 1+
                   2057:   again ;
                   2058: endless
                   2059: @end example
                   2060: 
                   2061: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   2062: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   2063: 
                   2064: A loop with one exit at any place looks like this:
                   2065: 
                   2066: @example
                   2067: : log2 ( +n1 -- n2 )
                   2068: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2069:   assert( dup 0> )
                   2070:   2/ 0 begin
                   2071:     over 0> while
                   2072:       1+ swap 2/ swap
                   2073:   repeat
                   2074:   nip ;
                   2075: 7 log2 .
                   2076: 8 log2 .
                   2077: @end example
                   2078: 
                   2079: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   2080: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    2081: continues behind the @code{while}.  @code{Repeat} jumps back to
                   2082: @code{begin}, just like @code{again}.
                   2083: 
1.211     anton    2084: In Forth there are a number of combinations/abbreviations, like
                   2085: @code{1+}.  However, @code{2/} is not one of them; it shifts its
                   2086: argument right by one bit (arithmetic shift right), and viewed as
                   2087: division that always rounds towards negative infinity (floored
                   2088: division).  In contrast, @code{/} rounds towards zero on some systems
                   2089: (not on default installations of gforth (>=0.7.0), however).
1.48      anton    2090: 
                   2091: @example
1.211     anton    2092: -5 2 / . \ -2 or -3
                   2093: -5 2/ .  \ -3
1.48      anton    2094: @end example
                   2095: 
                   2096: @code{assert(} is no standard word, but you can get it on systems other
1.198     anton    2097: than Gforth by including @file{compat/assert.fs}.  You can see what it
1.48      anton    2098: does by trying
                   2099: 
                   2100: @example
                   2101: 0 log2 .
                   2102: @end example
                   2103: 
                   2104: Here's a loop with an exit at the end:
                   2105: 
                   2106: @example
                   2107: : log2 ( +n1 -- n2 )
                   2108: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2109:   assert( dup 0 > )
                   2110:   -1 begin
                   2111:     1+ swap 2/ swap
                   2112:     over 0 <=
                   2113:   until
                   2114:   nip ;
                   2115: @end example
                   2116: 
                   2117: @code{Until} consumes a flag; if it is non-zero, execution continues at
                   2118: the @code{begin}, otherwise after the @code{until}.
                   2119: 
1.141     anton    2120: @quotation Assignment
1.48      anton    2121: Write a definition for computing the greatest common divisor.
1.141     anton    2122: @end quotation
1.48      anton    2123: 
1.66      anton    2124: Reference: @ref{Simple Loops}.
                   2125: 
1.48      anton    2126: 
                   2127: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   2128: @section Counted loops
1.66      anton    2129: @cindex loops, counted, tutorial
1.48      anton    2130: 
                   2131: @example
                   2132: : ^ ( n1 u -- n )
1.171     anton    2133: \ n = the uth power of n1
1.48      anton    2134:   1 swap 0 u+do
                   2135:     over *
                   2136:   loop
                   2137:   nip ;
                   2138: 3 2 ^ .
                   2139: 4 3 ^ .
                   2140: @end example
                   2141: 
                   2142: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   2143: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   2144: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2145: times (or not at all, if @code{u3-u4<0}).
                   2146: 
                   2147: You can see the stack effect design rules at work in the stack effect of
                   2148: the loop start words: Since the start value of the loop is more
                   2149: frequently constant than the end value, the start value is passed on
                   2150: the top-of-stack.
                   2151: 
                   2152: You can access the counter of a counted loop with @code{i}:
                   2153: 
                   2154: @example
                   2155: : fac ( u -- u! )
                   2156:   1 swap 1+ 1 u+do
                   2157:     i *
                   2158:   loop ;
                   2159: 5 fac .
                   2160: 7 fac .
                   2161: @end example
                   2162: 
                   2163: There is also @code{+do}, which expects signed numbers (important for
                   2164: deciding whether to enter the loop).
                   2165: 
1.141     anton    2166: @quotation Assignment
1.48      anton    2167: Write a definition for computing the nth Fibonacci number.
1.141     anton    2168: @end quotation
1.48      anton    2169: 
1.65      anton    2170: You can also use increments other than 1:
                   2171: 
                   2172: @example
                   2173: : up2 ( n1 n2 -- )
                   2174:   +do
                   2175:     i .
                   2176:   2 +loop ;
                   2177: 10 0 up2
                   2178: 
                   2179: : down2 ( n1 n2 -- )
                   2180:   -do
                   2181:     i .
                   2182:   2 -loop ;
                   2183: 0 10 down2
                   2184: @end example
1.48      anton    2185: 
1.66      anton    2186: Reference: @ref{Counted Loops}.
                   2187: 
1.48      anton    2188: 
                   2189: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2190: @section Recursion
1.66      anton    2191: @cindex recursion tutorial
1.48      anton    2192: 
                   2193: Usually the name of a definition is not visible in the definition; but
                   2194: earlier definitions are usually visible:
                   2195: 
                   2196: @example
1.166     anton    2197: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48      anton    2198: : / ( n1 n2 -- n )
                   2199:   dup 0= if
                   2200:     -10 throw \ report division by zero
                   2201:   endif
                   2202:   /           \ old version
                   2203: ;
                   2204: 1 0 /
                   2205: @end example
                   2206: 
                   2207: For recursive definitions you can use @code{recursive} (non-standard) or
                   2208: @code{recurse}:
                   2209: 
                   2210: @example
                   2211: : fac1 ( n -- n! ) recursive
                   2212:  dup 0> if
                   2213:    dup 1- fac1 *
                   2214:  else
                   2215:    drop 1
                   2216:  endif ;
                   2217: 7 fac1 .
                   2218: 
                   2219: : fac2 ( n -- n! )
                   2220:  dup 0> if
                   2221:    dup 1- recurse *
                   2222:  else
                   2223:    drop 1
                   2224:  endif ;
                   2225: 8 fac2 .
                   2226: @end example
                   2227: 
1.141     anton    2228: @quotation Assignment
1.48      anton    2229: Write a recursive definition for computing the nth Fibonacci number.
1.141     anton    2230: @end quotation
1.48      anton    2231: 
1.66      anton    2232: Reference (including indirect recursion): @xref{Calls and returns}.
                   2233: 
1.48      anton    2234: 
                   2235: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2236: @section Leaving definitions or loops
1.66      anton    2237: @cindex leaving definitions, tutorial
                   2238: @cindex leaving loops, tutorial
1.48      anton    2239: 
                   2240: @code{EXIT} exits the current definition right away.  For every counted
                   2241: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2242: before the @code{EXIT}:
                   2243: 
                   2244: @c !! real examples
                   2245: @example
                   2246: : ...
                   2247:  ... u+do
                   2248:    ... if
                   2249:      ... unloop exit
                   2250:    endif
                   2251:    ...
                   2252:  loop
                   2253:  ... ;
                   2254: @end example
                   2255: 
                   2256: @code{LEAVE} leaves the innermost counted loop right away:
                   2257: 
                   2258: @example
                   2259: : ...
                   2260:  ... u+do
                   2261:    ... if
                   2262:      ... leave
                   2263:    endif
                   2264:    ...
                   2265:  loop
                   2266:  ... ;
                   2267: @end example
                   2268: 
1.65      anton    2269: @c !! example
1.48      anton    2270: 
1.66      anton    2271: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
                   2272: 
                   2273: 
1.48      anton    2274: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2275: @section Return Stack
1.66      anton    2276: @cindex return stack tutorial
1.48      anton    2277: 
                   2278: In addition to the data stack Forth also has a second stack, the return
                   2279: stack; most Forth systems store the return addresses of procedure calls
                   2280: there (thus its name).  Programmers can also use this stack:
                   2281: 
                   2282: @example
                   2283: : foo ( n1 n2 -- )
                   2284:  .s
                   2285:  >r .s
1.50      anton    2286:  r@@ .
1.48      anton    2287:  >r .s
1.50      anton    2288:  r@@ .
1.48      anton    2289:  r> .
1.50      anton    2290:  r@@ .
1.48      anton    2291:  r> . ;
                   2292: 1 2 foo
                   2293: @end example
                   2294: 
                   2295: @code{>r} takes an element from the data stack and pushes it onto the
                   2296: return stack; conversely, @code{r>} moves an elementm from the return to
                   2297: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148     anton    2298: on the data stack.
1.48      anton    2299: 
                   2300: Forth programmers usually use the return stack for storing data
                   2301: temporarily, if using the data stack alone would be too complex, and
                   2302: factoring and locals are not an option:
                   2303: 
                   2304: @example
                   2305: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2306:  rot >r rot r> ;
                   2307: @end example
                   2308: 
                   2309: The return address of the definition and the loop control parameters of
                   2310: counted loops usually reside on the return stack, so you have to take
                   2311: all items, that you have pushed on the return stack in a colon
                   2312: definition or counted loop, from the return stack before the definition
                   2313: or loop ends.  You cannot access items that you pushed on the return
                   2314: stack outside some definition or loop within the definition of loop.
                   2315: 
                   2316: If you miscount the return stack items, this usually ends in a crash:
                   2317: 
                   2318: @example
                   2319: : crash ( n -- )
                   2320:   >r ;
                   2321: 5 crash
                   2322: @end example
                   2323: 
                   2324: You cannot mix using locals and using the return stack (according to the
                   2325: standard; Gforth has no problem).  However, they solve the same
                   2326: problems, so this shouldn't be an issue.
                   2327: 
1.141     anton    2328: @quotation Assignment
1.48      anton    2329: Can you rewrite any of the definitions you wrote until now in a better
                   2330: way using the return stack?
1.141     anton    2331: @end quotation
1.48      anton    2332: 
1.66      anton    2333: Reference: @ref{Return stack}.
                   2334: 
1.48      anton    2335: 
                   2336: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2337: @section Memory
1.66      anton    2338: @cindex memory access/allocation tutorial
1.48      anton    2339: 
                   2340: You can create a global variable @code{v} with
                   2341: 
                   2342: @example
                   2343: variable v ( -- addr )
                   2344: @end example
                   2345: 
                   2346: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2347: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2348: values into this cell and @code{@@} (fetch) to load the value from the
                   2349: stack into memory:
                   2350: 
                   2351: @example
                   2352: v .
                   2353: 5 v ! .s
1.50      anton    2354: v @@ .
1.48      anton    2355: @end example
                   2356: 
1.65      anton    2357: You can see a raw dump of memory with @code{dump}:
                   2358: 
                   2359: @example
                   2360: v 1 cells .s dump
                   2361: @end example
                   2362: 
                   2363: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
                   2364: generally, address units (aus)) that @code{n1 cells} occupy.  You can
                   2365: also reserve more memory:
1.48      anton    2366: 
                   2367: @example
                   2368: create v2 20 cells allot
1.65      anton    2369: v2 20 cells dump
1.48      anton    2370: @end example
                   2371: 
1.212     anton    2372: creates a variable-like word @code{v2} and reserves 20 uninitialized
                   2373: cells; the address pushed by @code{v2} points to the start of these 20
                   2374: cells (@pxref{CREATE}).  You can use address arithmetic to access
                   2375: these cells:
1.48      anton    2376: 
                   2377: @example
                   2378: 3 v2 5 cells + !
1.65      anton    2379: v2 20 cells dump
1.48      anton    2380: @end example
                   2381: 
                   2382: You can reserve and initialize memory with @code{,}:
                   2383: 
                   2384: @example
                   2385: create v3
                   2386:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2387: v3 @@ .
                   2388: v3 cell+ @@ .
                   2389: v3 2 cells + @@ .
1.65      anton    2390: v3 5 cells dump
1.48      anton    2391: @end example
                   2392: 
1.141     anton    2393: @quotation Assignment
1.48      anton    2394: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2395: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2396: one at @code{addr cell+} etc.
1.141     anton    2397: @end quotation
1.48      anton    2398: 
1.214   ! anton    2399: The difference between @code{variable} and @code{create} is that
        !          2400: @code{variable} allots a cell, and that you cannot allot additional
        !          2401: memory to a variable in standard Forth.
        !          2402: 
1.48      anton    2403: You can also reserve memory without creating a new word:
                   2404: 
                   2405: @example
1.60      anton    2406: here 10 cells allot .
                   2407: here .
1.48      anton    2408: @end example
                   2409: 
1.211     anton    2410: The first @code{here} pushes the start address of the memory area, the
                   2411: second @code{here} the address after the dictionary area.  You should
                   2412: store the start address somewhere, or you will have a hard time
                   2413: finding the memory area again.
1.48      anton    2414: 
                   2415: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2416: the system's data structures for words etc. on Gforth and most other
                   2417: Forth systems.  It is managed like a stack: You can free the memory that
                   2418: you have just @code{allot}ed with
                   2419: 
                   2420: @example
                   2421: -10 cells allot
1.60      anton    2422: here .
1.48      anton    2423: @end example
                   2424: 
                   2425: Note that you cannot do this if you have created a new word in the
                   2426: meantime (because then your @code{allot}ed memory is no longer on the
                   2427: top of the dictionary ``stack'').
                   2428: 
                   2429: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2430: freeing memory in any order:
                   2431: 
                   2432: @example
                   2433: 10 cells allocate throw .s
                   2434: 20 cells allocate throw .s
                   2435: swap
                   2436: free throw
                   2437: free throw
                   2438: @end example
                   2439: 
                   2440: The @code{throw}s deal with errors (e.g., out of memory).
                   2441: 
1.65      anton    2442: And there is also a
                   2443: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   2444: garbage collector}, which eliminates the need to @code{free} memory
                   2445: explicitly.
1.48      anton    2446: 
1.66      anton    2447: Reference: @ref{Memory}.
                   2448: 
1.48      anton    2449: 
                   2450: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2451: @section Characters and Strings
1.66      anton    2452: @cindex strings tutorial
                   2453: @cindex characters tutorial
1.48      anton    2454: 
                   2455: On the stack characters take up a cell, like numbers.  In memory they
                   2456: have their own size (one 8-bit byte on most systems), and therefore
                   2457: require their own words for memory access:
                   2458: 
                   2459: @example
                   2460: create v4 
                   2461:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2462: v4 4 chars + c@@ .
1.65      anton    2463: v4 5 chars dump
1.48      anton    2464: @end example
                   2465: 
                   2466: The preferred representation of strings on the stack is @code{addr
                   2467: u-count}, where @code{addr} is the address of the first character and
                   2468: @code{u-count} is the number of characters in the string.
                   2469: 
                   2470: @example
                   2471: v4 5 type
                   2472: @end example
                   2473: 
                   2474: You get a string constant with
                   2475: 
                   2476: @example
                   2477: s" hello, world" .s
                   2478: type
                   2479: @end example
                   2480: 
                   2481: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2482: is a normal Forth word and must be delimited with white space (try what
                   2483: happens when you remove the space).
                   2484: 
                   2485: However, this interpretive use of @code{s"} is quite restricted: the
                   2486: string exists only until the next call of @code{s"} (some Forth systems
                   2487: keep more than one of these strings, but usually they still have a
1.62      crook    2488: limited lifetime).
1.48      anton    2489: 
                   2490: @example
                   2491: s" hello," s" world" .s
                   2492: type
                   2493: type
                   2494: @end example
                   2495: 
1.62      crook    2496: You can also use @code{s"} in a definition, and the resulting
                   2497: strings then live forever (well, for as long as the definition):
1.48      anton    2498: 
                   2499: @example
                   2500: : foo s" hello," s" world" ;
                   2501: foo .s
                   2502: type
                   2503: type
                   2504: @end example
                   2505: 
1.141     anton    2506: @quotation Assignment
1.48      anton    2507: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2508: Implement @code{type ( addr u -- )}.
1.141     anton    2509: @end quotation
1.48      anton    2510: 
1.66      anton    2511: Reference: @ref{Memory Blocks}.
                   2512: 
                   2513: 
1.190     anton    2514: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
1.48      anton    2515: @section Alignment
1.66      anton    2516: @cindex alignment tutorial
                   2517: @cindex memory alignment tutorial
1.48      anton    2518: 
                   2519: On many processors cells have to be aligned in memory, if you want to
                   2520: access them with @code{@@} and @code{!} (and even if the processor does
1.62      crook    2521: not require alignment, access to aligned cells is faster).
1.48      anton    2522: 
                   2523: @code{Create} aligns @code{here} (i.e., the place where the next
                   2524: allocation will occur, and that the @code{create}d word points to).
                   2525: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2526: address.  Adding a number of @code{cells} to an aligned address produces
                   2527: another aligned address.
                   2528: 
                   2529: However, address arithmetic involving @code{char+} and @code{chars} can
                   2530: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2531: a-addr )} produces the next aligned address:
                   2532: 
                   2533: @example
1.50      anton    2534: v3 char+ aligned .s @@ .
                   2535: v3 char+ .s @@ .
1.48      anton    2536: @end example
                   2537: 
                   2538: Similarly, @code{align} advances @code{here} to the next aligned
                   2539: address:
                   2540: 
                   2541: @example
                   2542: create v5 97 c,
                   2543: here .
                   2544: align here .
                   2545: 1000 ,
                   2546: @end example
                   2547: 
                   2548: Note that you should use aligned addresses even if your processor does
                   2549: not require them, if you want your program to be portable.
                   2550: 
1.66      anton    2551: Reference: @ref{Address arithmetic}.
                   2552: 
1.190     anton    2553: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
                   2554: @section Floating Point
                   2555: @cindex floating point tutorial
                   2556: @cindex FP tutorial
                   2557: 
                   2558: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
                   2559: might expect, but there are a few things worth noting:
                   2560: 
                   2561: The first point is not specific to Forth, but so important and yet not
                   2562: universally known that I mention it here: FP numbers are not reals.
                   2563: Many properties (e.g., arithmetic laws) that reals have and that one
                   2564: expects of all kinds of numbers do not hold for FP numbers.  If you
                   2565: want to use FP computations, you should learn about their problems and
                   2566: how to avoid them; a good starting point is @cite{David Goldberg,
                   2567: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
                   2568: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
                   2569: Computing Surveys 23(1):5@minus{}48, March 1991}.
                   2570: 
                   2571: In Forth source code literal FP numbers need an exponent, e.g.,
1.210     anton    2572: @code{1e0}; this can also be written shorter as @code{1e}, longer as
                   2573: @code{+1.0e+0}, and many variations in between.  The reason for this is
                   2574: that, for historical reasons, Forth interprets a decimal point alone
                   2575: (e.g., @code{1.}) as indicating a double-cell integer.  Examples:
                   2576: 
                   2577: @example
                   2578: 2e 2e f+ f.
                   2579: @end example
                   2580: 
                   2581: Another requirement for literal FP numbers is that the current base is
1.190     anton    2582: decimal; with a hex base @code{1e} is interpreted as an integer.
                   2583: 
                   2584: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
                   2585: ANS Forth system may implement the FP stack on the data stack, but
                   2586: virtually all systems implement a separate FP stack; and programming
                   2587: in a way that accommodates all models is so cumbersome that nobody
                   2588: does it.}  One advantage of this model is that cells are not in the
                   2589: way when accessing FP values, and vice versa.  Forth has a set of
                   2590: words for manipulating the FP stack: @code{fdup fswap fdrop fover
                   2591: frot} and (non-standard) @code{fnip ftuck fpick}.
                   2592: 
                   2593: FP arithmetic words are prefixed with @code{F}.  There is the usual
                   2594: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
                   2595: other functions, e.g., @code{fsqrt fsin fln fmin}.  One word that you
                   2596: might expect is @code{f=}; but @code{f=} is non-standard, because FP
                   2597: computation results are usually inaccurate, so exact comparison is
                   2598: usually a mistake, and one should use approximate comparison.
                   2599: Unfortunately, @code{f~}, the standard word for that purpose, is not
                   2600: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
                   2601: well.
                   2602: 
                   2603: And of course there are words for accessing FP numbers in memory
                   2604: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
                   2605: faligned}).  There are also variants of these words with an @code{sf}
                   2606: and @code{df} prefix for accessing IEEE format single-precision and
                   2607: double-precision numbers in memory; their main purpose is for
                   2608: accessing external FP data (e.g., that has been read from or will be
                   2609: written to a file).
                   2610: 
                   2611: Here is an example of a dot-product word and its use:
                   2612: 
                   2613: @example
                   2614: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   2615:   >r swap 2swap swap 0e r> 0 ?DO
                   2616:     dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
                   2617:   LOOP
                   2618:   2drop 2drop ;
1.48      anton    2619: 
1.190     anton    2620: create v 1.23e f, 4.56e f, 7.89e f,
                   2621: 
                   2622: v 1 floats  v 1 floats  3  v* f.
                   2623: @end example
                   2624: 
                   2625: @quotation Assignment
                   2626: Write a program to solve a quadratic equation.  Then read @cite{Henry
                   2627: G. Baker,
                   2628: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
                   2629: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
                   2630: 33(1):30@minus{}39, January 1998}, and see if you can improve your
                   2631: program.  Finally, find a test case where the original and the
                   2632: improved version produce different results.
                   2633: @end quotation
                   2634: 
                   2635: Reference: @ref{Floating Point}; @ref{Floating point stack};
                   2636: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
                   2637: arithmetic}.
                   2638: 
                   2639: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
1.84      pazsan   2640: @section Files
                   2641: @cindex files tutorial
                   2642: 
                   2643: This section gives a short introduction into how to use files inside
                   2644: Forth. It's broken up into five easy steps:
                   2645: 
                   2646: @enumerate 1
                   2647: @item Opened an ASCII text file for input
                   2648: @item Opened a file for output
                   2649: @item Read input file until string matched (or some other condition matched)
                   2650: @item Wrote some lines from input ( modified or not) to output
                   2651: @item Closed the files.
                   2652: @end enumerate
                   2653: 
1.153     anton    2654: Reference: @ref{General files}.
                   2655: 
1.84      pazsan   2656: @subsection Open file for input
                   2657: 
                   2658: @example
                   2659: s" foo.in"  r/o open-file throw Value fd-in
                   2660: @end example
                   2661: 
                   2662: @subsection Create file for output
                   2663: 
                   2664: @example
                   2665: s" foo.out" w/o create-file throw Value fd-out
                   2666: @end example
                   2667: 
                   2668: The available file modes are r/o for read-only access, r/w for
                   2669: read-write access, and w/o for write-only access. You could open both
                   2670: files with r/w, too, if you like. All file words return error codes; for
                   2671: most applications, it's best to pass there error codes with @code{throw}
                   2672: to the outer error handler.
                   2673: 
                   2674: If you want words for opening and assigning, define them as follows:
                   2675: 
                   2676: @example
                   2677: 0 Value fd-in
                   2678: 0 Value fd-out
                   2679: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
                   2680: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
                   2681: @end example
                   2682: 
                   2683: Usage example:
                   2684: 
                   2685: @example
                   2686: s" foo.in" open-input
                   2687: s" foo.out" open-output
                   2688: @end example
                   2689: 
                   2690: @subsection Scan file for a particular line
                   2691: 
                   2692: @example
                   2693: 256 Constant max-line
                   2694: Create line-buffer  max-line 2 + allot
                   2695: 
                   2696: : scan-file ( addr u -- )
                   2697:   begin
                   2698:       line-buffer max-line fd-in read-line throw
                   2699:   while
                   2700:          >r 2dup line-buffer r> compare 0=
                   2701:      until
                   2702:   else
                   2703:      drop
                   2704:   then
                   2705:   2drop ;
                   2706: @end example
                   2707: 
                   2708: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94      anton    2709: the buffer at addr, and returns the number of bytes read, a flag that is
                   2710: false when the end of file is reached, and an error code.
1.84      pazsan   2711: 
                   2712: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
                   2713: returns zero if both strings are equal. It returns a positive number if
                   2714: the first string is lexically greater, a negative if the second string
                   2715: is lexically greater.
                   2716: 
                   2717: We haven't seen this loop here; it has two exits. Since the @code{while}
                   2718: exits with the number of bytes read on the stack, we have to clean up
                   2719: that separately; that's after the @code{else}.
                   2720: 
                   2721: Usage example:
                   2722: 
                   2723: @example
                   2724: s" The text I search is here" scan-file
                   2725: @end example
                   2726: 
                   2727: @subsection Copy input to output
                   2728: 
                   2729: @example
                   2730: : copy-file ( -- )
                   2731:   begin
                   2732:       line-buffer max-line fd-in read-line throw
                   2733:   while
1.194     anton    2734:       line-buffer swap fd-out write-line throw
1.84      pazsan   2735:   repeat ;
                   2736: @end example
1.194     anton    2737: @c !! does not handle long lines, no newline at end of file
1.84      pazsan   2738: 
                   2739: @subsection Close files
                   2740: 
                   2741: @example
                   2742: fd-in close-file throw
                   2743: fd-out close-file throw
                   2744: @end example
                   2745: 
                   2746: Likewise, you can put that into definitions, too:
                   2747: 
                   2748: @example
                   2749: : close-input ( -- )  fd-in close-file throw ;
                   2750: : close-output ( -- )  fd-out close-file throw ;
                   2751: @end example
                   2752: 
1.141     anton    2753: @quotation Assignment
1.84      pazsan   2754: How could you modify @code{copy-file} so that it copies until a second line is
                   2755: matched? Can you write a program that extracts a section of a text file,
                   2756: given the line that starts and the line that terminates that section?
1.141     anton    2757: @end quotation
1.84      pazsan   2758: 
                   2759: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48      anton    2760: @section Interpretation and Compilation Semantics and Immediacy
1.66      anton    2761: @cindex semantics tutorial
                   2762: @cindex interpretation semantics tutorial
                   2763: @cindex compilation semantics tutorial
                   2764: @cindex immediate, tutorial
1.48      anton    2765: 
                   2766: When a word is compiled, it behaves differently from being interpreted.
                   2767: E.g., consider @code{+}:
                   2768: 
                   2769: @example
                   2770: 1 2 + .
                   2771: : foo + ;
                   2772: @end example
                   2773: 
                   2774: These two behaviours are known as compilation and interpretation
                   2775: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2776: is to append the interpretation semantics to the currently defined word
                   2777: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2778: later, the interpretation semantics of @code{+} (i.e., adding two
                   2779: numbers) will be performed.
                   2780: 
                   2781: However, there are words with non-default compilation semantics, e.g.,
                   2782: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2783: change the compilation semantics of the last defined word to be equal to
                   2784: the interpretation semantics:
                   2785: 
                   2786: @example
                   2787: : [FOO] ( -- )
                   2788:  5 . ; immediate
                   2789: 
                   2790: [FOO]
                   2791: : bar ( -- )
                   2792:   [FOO] ;
                   2793: bar
                   2794: see bar
                   2795: @end example
                   2796: 
1.198     anton    2797: Two conventions to mark words with non-default compilation semantics are
1.48      anton    2798: names with brackets (more frequently used) and to write them all in
                   2799: upper case (less frequently used).
                   2800: 
                   2801: In Gforth (and many other systems) you can also remove the
                   2802: interpretation semantics with @code{compile-only} (the compilation
                   2803: semantics is derived from the original interpretation semantics):
                   2804: 
                   2805: @example
                   2806: : flip ( -- )
                   2807:  6 . ; compile-only \ but not immediate
                   2808: flip
                   2809: 
                   2810: : flop ( -- )
                   2811:  flip ;
                   2812: flop
                   2813: @end example
                   2814: 
                   2815: In this example the interpretation semantics of @code{flop} is equal to
                   2816: the original interpretation semantics of @code{flip}.
                   2817: 
                   2818: The text interpreter has two states: in interpret state, it performs the
                   2819: interpretation semantics of words it encounters; in compile state, it
                   2820: performs the compilation semantics of these words.
                   2821: 
                   2822: Among other things, @code{:} switches into compile state, and @code{;}
                   2823: switches back to interpret state.  They contain the factors @code{]}
                   2824: (switch to compile state) and @code{[} (switch to interpret state), that
                   2825: do nothing but switch the state.
                   2826: 
                   2827: @example
                   2828: : xxx ( -- )
                   2829:   [ 5 . ]
                   2830: ;
                   2831: 
                   2832: xxx
                   2833: see xxx
                   2834: @end example
                   2835: 
                   2836: These brackets are also the source of the naming convention mentioned
                   2837: above.
                   2838: 
1.66      anton    2839: Reference: @ref{Interpretation and Compilation Semantics}.
                   2840: 
1.48      anton    2841: 
                   2842: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2843: @section Execution Tokens
1.66      anton    2844: @cindex execution tokens tutorial
                   2845: @cindex XT tutorial
1.48      anton    2846: 
                   2847: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2848: cell representing the interpretation semantics of a word.  You can
                   2849: execute this semantics with @code{execute}:
                   2850: 
                   2851: @example
                   2852: ' + .s
                   2853: 1 2 rot execute .
                   2854: @end example
                   2855: 
                   2856: The XT is similar to a function pointer in C.  However, parameter
                   2857: passing through the stack makes it a little more flexible:
                   2858: 
                   2859: @example
                   2860: : map-array ( ... addr u xt -- ... )
1.50      anton    2861: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2862: \ at addr and containing u elements
1.48      anton    2863:   @{ xt @}
                   2864:   cells over + swap ?do
1.50      anton    2865:     i @@ xt execute
1.48      anton    2866:   1 cells +loop ;
                   2867: 
                   2868: create a 3 , 4 , 2 , -1 , 4 ,
                   2869: a 5 ' . map-array .s
                   2870: 0 a 5 ' + map-array .
                   2871: s" max-n" environment? drop .s
                   2872: a 5 ' min map-array .
                   2873: @end example
                   2874: 
                   2875: You can use map-array with the XTs of words that consume one element
                   2876: more than they produce.  In theory you can also use it with other XTs,
                   2877: but the stack effect then depends on the size of the array, which is
                   2878: hard to understand.
                   2879: 
1.51      pazsan   2880: Since XTs are cell-sized, you can store them in memory and manipulate
                   2881: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2882: word with @code{compile,}:
                   2883: 
                   2884: @example
                   2885: : foo1 ( n1 n2 -- n )
                   2886:    [ ' + compile, ] ;
                   2887: see foo
                   2888: @end example
                   2889: 
                   2890: This is non-standard, because @code{compile,} has no compilation
                   2891: semantics in the standard, but it works in good Forth systems.  For the
                   2892: broken ones, use
                   2893: 
                   2894: @example
                   2895: : [compile,] compile, ; immediate
                   2896: 
                   2897: : foo1 ( n1 n2 -- n )
                   2898:    [ ' + ] [compile,] ;
                   2899: see foo
                   2900: @end example
                   2901: 
                   2902: @code{'} is a word with default compilation semantics; it parses the
                   2903: next word when its interpretation semantics are executed, not during
                   2904: compilation:
                   2905: 
                   2906: @example
                   2907: : foo ( -- xt )
                   2908:   ' ;
                   2909: see foo
                   2910: : bar ( ... "word" -- ... )
                   2911:   ' execute ;
                   2912: see bar
1.60      anton    2913: 1 2 bar + .
1.48      anton    2914: @end example
                   2915: 
                   2916: You often want to parse a word during compilation and compile its XT so
                   2917: it will be pushed on the stack at run-time.  @code{[']} does this:
                   2918: 
                   2919: @example
                   2920: : xt-+ ( -- xt )
                   2921:   ['] + ;
                   2922: see xt-+
                   2923: 1 2 xt-+ execute .
                   2924: @end example
                   2925: 
                   2926: Many programmers tend to see @code{'} and the word it parses as one
                   2927: unit, and expect it to behave like @code{[']} when compiled, and are
                   2928: confused by the actual behaviour.  If you are, just remember that the
                   2929: Forth system just takes @code{'} as one unit and has no idea that it is
                   2930: a parsing word (attempts to convenience programmers in this issue have
                   2931: usually resulted in even worse pitfalls, see
1.66      anton    2932: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
                   2933: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48      anton    2934: 
                   2935: Note that the state of the interpreter does not come into play when
1.51      pazsan   2936: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    2937: compile state, it still gives you the interpretation semantics.  And
                   2938: whatever that state is, @code{execute} performs the semantics
1.66      anton    2939: represented by the XT (i.e., for XTs produced with @code{'} the
                   2940: interpretation semantics).
                   2941: 
                   2942: Reference: @ref{Tokens for Words}.
1.48      anton    2943: 
                   2944: 
                   2945: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   2946: @section Exceptions
1.66      anton    2947: @cindex exceptions tutorial
1.48      anton    2948: 
                   2949: @code{throw ( n -- )} causes an exception unless n is zero.
                   2950: 
                   2951: @example
                   2952: 100 throw .s
                   2953: 0 throw .s
                   2954: @end example
                   2955: 
                   2956: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   2957: it catches exceptions and pushes the number of the exception on the
                   2958: stack (or 0, if the xt executed without exception).  If there was an
                   2959: exception, the stacks have the same depth as when entering @code{catch}:
                   2960: 
                   2961: @example
                   2962: .s
                   2963: 3 0 ' / catch .s
                   2964: 3 2 ' / catch .s
                   2965: @end example
                   2966: 
1.141     anton    2967: @quotation Assignment
1.48      anton    2968: Try the same with @code{execute} instead of @code{catch}.
1.141     anton    2969: @end quotation
1.48      anton    2970: 
                   2971: @code{Throw} always jumps to the dynamically next enclosing
                   2972: @code{catch}, even if it has to leave several call levels to achieve
                   2973: this:
                   2974: 
                   2975: @example
                   2976: : foo 100 throw ;
                   2977: : foo1 foo ." after foo" ;
1.51      pazsan   2978: : bar ['] foo1 catch ;
1.60      anton    2979: bar .
1.48      anton    2980: @end example
                   2981: 
                   2982: It is often important to restore a value upon leaving a definition, even
                   2983: if the definition is left through an exception.  You can ensure this
                   2984: like this:
                   2985: 
                   2986: @example
                   2987: : ...
                   2988:    save-x
1.51      pazsan   2989:    ['] word-changing-x catch ( ... n )
1.48      anton    2990:    restore-x
                   2991:    ( ... n ) throw ;
                   2992: @end example
                   2993: 
1.172     anton    2994: However, this is still not safe against, e.g., the user pressing
                   2995: @kbd{Ctrl-C} when execution is between the @code{catch} and
                   2996: @code{restore-x}.
                   2997: 
                   2998: Gforth provides an alternative exception handling syntax that is safe
                   2999: against such cases: @code{try ... restore ... endtry}.  If the code
                   3000: between @code{try} and @code{endtry} has an exception, the stack
                   3001: depths are restored, the exception number is pushed on the stack, and
                   3002: the execution continues right after @code{restore}.
1.48      anton    3003: 
1.172     anton    3004: The safer equivalent to the restoration code above is
1.48      anton    3005: 
                   3006: @example
                   3007: : ...
                   3008:   save-x
                   3009:   try
1.92      anton    3010:     word-changing-x 0
1.172     anton    3011:   restore
                   3012:     restore-x
                   3013:   endtry
1.48      anton    3014:   throw ;
                   3015: @end example
                   3016: 
1.66      anton    3017: Reference: @ref{Exception Handling}.
                   3018: 
1.48      anton    3019: 
                   3020: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   3021: @section Defining Words
1.66      anton    3022: @cindex defining words tutorial
                   3023: @cindex does> tutorial
                   3024: @cindex create...does> tutorial
                   3025: 
                   3026: @c before semantics?
1.48      anton    3027: 
                   3028: @code{:}, @code{create}, and @code{variable} are definition words: They
                   3029: define other words.  @code{Constant} is another definition word:
                   3030: 
                   3031: @example
                   3032: 5 constant foo
                   3033: foo .
                   3034: @end example
                   3035: 
                   3036: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   3037: (floating point) with @code{variable} and @code{constant}.
                   3038: 
                   3039: You can also define your own defining words.  E.g.:
                   3040: 
                   3041: @example
                   3042: : variable ( "name" -- )
                   3043:   create 0 , ;
                   3044: @end example
                   3045: 
                   3046: You can also define defining words that create words that do something
                   3047: other than just producing their address:
                   3048: 
                   3049: @example
                   3050: : constant ( n "name" -- )
                   3051:   create ,
                   3052: does> ( -- n )
1.50      anton    3053:   ( addr ) @@ ;
1.48      anton    3054: 
                   3055: 5 constant foo
                   3056: foo .
                   3057: @end example
                   3058: 
                   3059: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   3060: @code{does>} replaces @code{;}, but it also does something else: It
                   3061: changes the last defined word such that it pushes the address of the
                   3062: body of the word and then performs the code after the @code{does>}
                   3063: whenever it is called.
                   3064: 
                   3065: In the example above, @code{constant} uses @code{,} to store 5 into the
                   3066: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   3067: the body onto the stack, then (in the code after the @code{does>})
                   3068: fetches the 5 from there.
                   3069: 
                   3070: The stack comment near the @code{does>} reflects the stack effect of the
                   3071: defined word, not the stack effect of the code after the @code{does>}
                   3072: (the difference is that the code expects the address of the body that
                   3073: the stack comment does not show).
                   3074: 
                   3075: You can use these definition words to do factoring in cases that involve
                   3076: (other) definition words.  E.g., a field offset is always added to an
                   3077: address.  Instead of defining
                   3078: 
                   3079: @example
                   3080: 2 cells constant offset-field1
                   3081: @end example
                   3082: 
                   3083: and using this like
                   3084: 
                   3085: @example
                   3086: ( addr ) offset-field1 +
                   3087: @end example
                   3088: 
                   3089: you can define a definition word
                   3090: 
                   3091: @example
                   3092: : simple-field ( n "name" -- )
                   3093:   create ,
                   3094: does> ( n1 -- n1+n )
1.50      anton    3095:   ( addr ) @@ + ;
1.48      anton    3096: @end example
1.21      crook    3097: 
1.48      anton    3098: Definition and use of field offsets now look like this:
1.21      crook    3099: 
1.48      anton    3100: @example
                   3101: 2 cells simple-field field1
1.60      anton    3102: create mystruct 4 cells allot
                   3103: mystruct .s field1 .s drop
1.48      anton    3104: @end example
1.21      crook    3105: 
1.48      anton    3106: If you want to do something with the word without performing the code
                   3107: after the @code{does>}, you can access the body of a @code{create}d word
                   3108: with @code{>body ( xt -- addr )}:
1.21      crook    3109: 
1.48      anton    3110: @example
                   3111: : value ( n "name" -- )
                   3112:   create ,
                   3113: does> ( -- n1 )
1.50      anton    3114:   @@ ;
1.48      anton    3115: : to ( n "name" -- )
                   3116:   ' >body ! ;
1.21      crook    3117: 
1.48      anton    3118: 5 value foo
                   3119: foo .
                   3120: 7 to foo
                   3121: foo .
                   3122: @end example
1.21      crook    3123: 
1.141     anton    3124: @quotation Assignment
1.48      anton    3125: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   3126: XT (at the start the XT of @code{abort}), and upon execution
                   3127: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   3128: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   3129: recursion is one application of @code{defer}.
1.141     anton    3130: @end quotation
1.29      crook    3131: 
1.66      anton    3132: Reference: @ref{User-defined Defining Words}.
                   3133: 
                   3134: 
1.48      anton    3135: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   3136: @section Arrays and Records
1.66      anton    3137: @cindex arrays tutorial
                   3138: @cindex records tutorial
                   3139: @cindex structs tutorial
1.29      crook    3140: 
1.48      anton    3141: Forth has no standard words for defining data structures such as arrays
                   3142: and records (structs in C terminology), but you can build them yourself
                   3143: based on address arithmetic.  You can also define words for defining
                   3144: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    3145: 
1.48      anton    3146: One of the first projects a Forth newcomer sets out upon when learning
                   3147: about defining words is an array defining word (possibly for
                   3148: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   3149: learn something from it.  However, don't be disappointed when you later
                   3150: learn that you have little use for these words (inappropriate use would
1.198     anton    3151: be even worse).  I have not found a set of useful array words yet;
1.48      anton    3152: the needs are just too diverse, and named, global arrays (the result of
                   3153: naive use of defining words) are often not flexible enough (e.g.,
1.66      anton    3154: consider how to pass them as parameters).  Another such project is a set
                   3155: of words to help dealing with strings.
1.29      crook    3156: 
1.48      anton    3157: On the other hand, there is a useful set of record words, and it has
                   3158: been defined in @file{compat/struct.fs}; these words are predefined in
                   3159: Gforth.  They are explained in depth elsewhere in this manual (see
                   3160: @pxref{Structures}).  The @code{simple-field} example above is
                   3161: simplified variant of fields in this package.
1.21      crook    3162: 
                   3163: 
1.48      anton    3164: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   3165: @section @code{POSTPONE}
1.66      anton    3166: @cindex postpone tutorial
1.21      crook    3167: 
1.48      anton    3168: You can compile the compilation semantics (instead of compiling the
                   3169: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    3170: 
1.48      anton    3171: @example
                   3172: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   3173:  POSTPONE + ; immediate
1.48      anton    3174: : foo ( n1 n2 -- n )
                   3175:  MY-+ ;
                   3176: 1 2 foo .
                   3177: see foo
                   3178: @end example
1.21      crook    3179: 
1.48      anton    3180: During the definition of @code{foo} the text interpreter performs the
                   3181: compilation semantics of @code{MY-+}, which performs the compilation
                   3182: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   3183: 
                   3184: This example also displays separate stack comments for the compilation
                   3185: semantics and for the stack effect of the compiled code.  For words with
                   3186: default compilation semantics these stack effects are usually not
                   3187: displayed; the stack effect of the compilation semantics is always
                   3188: @code{( -- )} for these words, the stack effect for the compiled code is
                   3189: the stack effect of the interpretation semantics.
                   3190: 
                   3191: Note that the state of the interpreter does not come into play when
                   3192: performing the compilation semantics in this way.  You can also perform
                   3193: it interpretively, e.g.:
                   3194: 
                   3195: @example
                   3196: : foo2 ( n1 n2 -- n )
                   3197:  [ MY-+ ] ;
                   3198: 1 2 foo .
                   3199: see foo
                   3200: @end example
1.21      crook    3201: 
1.48      anton    3202: However, there are some broken Forth systems where this does not always
1.62      crook    3203: work, and therefore this practice was been declared non-standard in
1.48      anton    3204: 1999.
                   3205: @c !! repair.fs
                   3206: 
                   3207: Here is another example for using @code{POSTPONE}:
1.44      crook    3208: 
1.48      anton    3209: @example
                   3210: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   3211:  POSTPONE negate POSTPONE + ; immediate compile-only
                   3212: : bar ( n1 n2 -- n )
                   3213:   MY-- ;
                   3214: 2 1 bar .
                   3215: see bar
                   3216: @end example
1.21      crook    3217: 
1.48      anton    3218: You can define @code{ENDIF} in this way:
1.21      crook    3219: 
1.48      anton    3220: @example
                   3221: : ENDIF ( Compilation: orig -- )
                   3222:   POSTPONE then ; immediate
                   3223: @end example
1.21      crook    3224: 
1.141     anton    3225: @quotation Assignment
1.48      anton    3226: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   3227: @code{2dup}, but compiles @code{over over}.
1.141     anton    3228: @end quotation
1.29      crook    3229: 
1.66      anton    3230: @c !! @xref{Macros} for reference
                   3231: 
                   3232: 
1.48      anton    3233: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3234: @section @code{Literal}
1.66      anton    3235: @cindex literal tutorial
1.29      crook    3236: 
1.48      anton    3237: You cannot @code{POSTPONE} numbers:
1.21      crook    3238: 
1.48      anton    3239: @example
                   3240: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3241: @end example
                   3242: 
1.48      anton    3243: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3244: 
1.48      anton    3245: @example
                   3246: : [FOO] ( compilation: --; run-time: -- n )
                   3247:   500 POSTPONE literal ; immediate
1.29      crook    3248: 
1.60      anton    3249: : flip [FOO] ;
1.48      anton    3250: flip .
                   3251: see flip
                   3252: @end example
1.29      crook    3253: 
1.48      anton    3254: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3255: semantics are executed) and pushes it at run-time (when the code it
                   3256: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3257: number computed at compile time into the current word:
1.29      crook    3258: 
1.48      anton    3259: @example
                   3260: : bar ( -- n )
                   3261:   [ 2 2 + ] literal ;
                   3262: see bar
                   3263: @end example
1.29      crook    3264: 
1.141     anton    3265: @quotation Assignment
1.48      anton    3266: Write @code{]L} which allows writing the example above as @code{: bar (
                   3267: -- n ) [ 2 2 + ]L ;}
1.141     anton    3268: @end quotation
1.48      anton    3269: 
1.66      anton    3270: @c !! @xref{Macros} for reference
                   3271: 
1.48      anton    3272: 
                   3273: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3274: @section Advanced macros
1.66      anton    3275: @cindex macros, advanced tutorial
                   3276: @cindex run-time code generation, tutorial
1.48      anton    3277: 
1.66      anton    3278: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
                   3279: Execution Tokens}.  It frequently performs @code{execute}, a relatively
                   3280: expensive operation in some Forth implementations.  You can use
1.48      anton    3281: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3282: and produce a word that contains the word to be performed directly:
                   3283: 
                   3284: @c use ]] ... [[
                   3285: @example
                   3286: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3287: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3288: \ array beginning at addr and containing u elements
                   3289:   @{ xt @}
                   3290:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3291:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3292:   1 cells POSTPONE literal POSTPONE +loop ;
                   3293: 
                   3294: : sum-array ( addr u -- n )
                   3295:  0 rot rot [ ' + compile-map-array ] ;
                   3296: see sum-array
                   3297: a 5 sum-array .
                   3298: @end example
                   3299: 
                   3300: You can use the full power of Forth for generating the code; here's an
                   3301: example where the code is generated in a loop:
                   3302: 
                   3303: @example
                   3304: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3305: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3306:   POSTPONE tuck POSTPONE @@
1.48      anton    3307:   POSTPONE literal POSTPONE * POSTPONE +
                   3308:   POSTPONE swap POSTPONE cell+ ;
                   3309: 
                   3310: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3311: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3312:   0 postpone literal postpone swap
                   3313:   [ ' compile-vmul-step compile-map-array ]
                   3314:   postpone drop ;
                   3315: see compile-vmul
                   3316: 
                   3317: : a-vmul ( addr -- n )
1.51      pazsan   3318: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3319:  [ a 5 compile-vmul ] ;
                   3320: see a-vmul
                   3321: a a-vmul .
                   3322: @end example
                   3323: 
                   3324: This example uses @code{compile-map-array} to show off, but you could
1.66      anton    3325: also use @code{map-array} instead (try it now!).
1.48      anton    3326: 
                   3327: You can use this technique for efficient multiplication of large
                   3328: matrices.  In matrix multiplication, you multiply every line of one
                   3329: matrix with every column of the other matrix.  You can generate the code
                   3330: for one line once, and use it for every column.  The only downside of
                   3331: this technique is that it is cumbersome to recover the memory consumed
                   3332: by the generated code when you are done (and in more complicated cases
                   3333: it is not possible portably).
                   3334: 
1.66      anton    3335: @c !! @xref{Macros} for reference
                   3336: 
                   3337: 
1.48      anton    3338: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3339: @section Compilation Tokens
1.66      anton    3340: @cindex compilation tokens, tutorial
                   3341: @cindex CT, tutorial
1.48      anton    3342: 
                   3343: This section is Gforth-specific.  You can skip it.
                   3344: 
                   3345: @code{' word compile,} compiles the interpretation semantics.  For words
                   3346: with default compilation semantics this is the same as performing the
                   3347: compilation semantics.  To represent the compilation semantics of other
                   3348: words (e.g., words like @code{if} that have no interpretation
                   3349: semantics), Gforth has the concept of a compilation token (CT,
                   3350: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3351: You can perform the compilation semantics represented by a CT with
                   3352: @code{execute}:
1.29      crook    3353: 
1.48      anton    3354: @example
                   3355: : foo2 ( n1 n2 -- n )
                   3356:    [ comp' + execute ] ;
                   3357: see foo
                   3358: @end example
1.29      crook    3359: 
1.48      anton    3360: You can compile the compilation semantics represented by a CT with
                   3361: @code{postpone,}:
1.30      anton    3362: 
1.48      anton    3363: @example
                   3364: : foo3 ( -- )
                   3365:   [ comp' + postpone, ] ;
                   3366: see foo3
                   3367: @end example
1.30      anton    3368: 
1.51      pazsan   3369: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3370: @code{comp'} is particularly useful for words that have no
                   3371: interpretation semantics:
1.29      crook    3372: 
1.30      anton    3373: @example
1.48      anton    3374: ' if
1.60      anton    3375: comp' if .s 2drop
1.30      anton    3376: @end example
                   3377: 
1.66      anton    3378: Reference: @ref{Tokens for Words}.
                   3379: 
1.29      crook    3380: 
1.48      anton    3381: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3382: @section Wordlists and Search Order
1.66      anton    3383: @cindex wordlists tutorial
                   3384: @cindex search order, tutorial
1.48      anton    3385: 
                   3386: The dictionary is not just a memory area that allows you to allocate
                   3387: memory with @code{allot}, it also contains the Forth words, arranged in
                   3388: several wordlists.  When searching for a word in a wordlist,
                   3389: conceptually you start searching at the youngest and proceed towards
                   3390: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3391: you define a word with the same name as an older word, the new word
                   3392: shadows the older word.
                   3393: 
                   3394: Which wordlists are searched in which order is determined by the search
                   3395: order.  You can display the search order with @code{order}.  It displays
                   3396: first the search order, starting with the wordlist searched first, then
                   3397: it displays the wordlist that will contain newly defined words.
1.21      crook    3398: 
1.48      anton    3399: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3400: 
1.48      anton    3401: @example
                   3402: wordlist constant mywords
                   3403: @end example
1.21      crook    3404: 
1.48      anton    3405: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3406: defined words (the @emph{current} wordlist):
1.21      crook    3407: 
1.48      anton    3408: @example
                   3409: mywords set-current
                   3410: order
                   3411: @end example
1.26      crook    3412: 
1.48      anton    3413: Gforth does not display a name for the wordlist in @code{mywords}
                   3414: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3415: 
1.48      anton    3416: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3417: you want to put something into a specific wordlist without overall
                   3418: effect on the current wordlist, this typically looks like this:
1.21      crook    3419: 
1.48      anton    3420: @example
                   3421: get-current mywords set-current ( wid )
                   3422: create someword
                   3423: ( wid ) set-current
                   3424: @end example
1.21      crook    3425: 
1.48      anton    3426: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3427: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3428: searched wordlist is topmost.
1.21      crook    3429: 
1.48      anton    3430: @example
                   3431: get-order mywords swap 1+ set-order
                   3432: order
                   3433: @end example
1.21      crook    3434: 
1.48      anton    3435: Yes, the order of wordlists in the output of @code{order} is reversed
                   3436: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3437: 
1.141     anton    3438: @quotation Assignment
1.48      anton    3439: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3440: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3441: removes the first searched wordlist from the search order.  Experiment
                   3442: with boundary conditions (you will see some crashes or situations that
                   3443: are hard or impossible to leave).
1.141     anton    3444: @end quotation
1.21      crook    3445: 
1.48      anton    3446: The search order is a powerful foundation for providing features similar
                   3447: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3448: programs in this way has disadvantages for debugging and reuse/factoring
                   3449: that overcome the advantages in my experience (I don't do huge projects,
1.55      anton    3450: though).  These disadvantages are not so clear in other
1.82      anton    3451: languages/programming environments, because these languages are not so
1.48      anton    3452: strong in debugging and reuse.
1.21      crook    3453: 
1.66      anton    3454: @c !! example
                   3455: 
                   3456: Reference: @ref{Word Lists}.
1.21      crook    3457: 
1.29      crook    3458: @c ******************************************************************
1.48      anton    3459: @node Introduction, Words, Tutorial, Top
1.29      crook    3460: @comment node-name,     next,           previous, up
                   3461: @chapter An Introduction to ANS Forth
                   3462: @cindex Forth - an introduction
1.21      crook    3463: 
1.83      anton    3464: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
                   3465: that it is slower-paced in its examples, but uses them to dive deep into
                   3466: explaining Forth internals (not covered by the Tutorial).  Apart from
                   3467: that, this chapter covers far less material.  It is suitable for reading
                   3468: without using a computer.
                   3469: 
1.29      crook    3470: The primary purpose of this manual is to document Gforth. However, since
                   3471: Forth is not a widely-known language and there is a lack of up-to-date
                   3472: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3473: material.  For other sources of Forth-related
                   3474: information, see @ref{Forth-related information}.
1.21      crook    3475: 
1.29      crook    3476: The examples in this section should work on any ANS Forth; the
                   3477: output shown was produced using Gforth. Each example attempts to
                   3478: reproduce the exact output that Gforth produces. If you try out the
                   3479: examples (and you should), what you should type is shown @kbd{like this}
                   3480: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3481: that, where the example shows @key{RET} it means that you should
1.29      crook    3482: press the ``carriage return'' key. Unfortunately, some output formats for
                   3483: this manual cannot show the difference between @kbd{this} and
                   3484: @code{this} which will make trying out the examples harder (but not
                   3485: impossible).
1.21      crook    3486: 
1.29      crook    3487: Forth is an unusual language. It provides an interactive development
                   3488: environment which includes both an interpreter and compiler. Forth
                   3489: programming style encourages you to break a problem down into many
                   3490: @cindex factoring
                   3491: small fragments (@dfn{factoring}), and then to develop and test each
                   3492: fragment interactively. Forth advocates assert that breaking the
                   3493: edit-compile-test cycle used by conventional programming languages can
                   3494: lead to great productivity improvements.
1.21      crook    3495: 
1.29      crook    3496: @menu
1.67      anton    3497: * Introducing the Text Interpreter::  
                   3498: * Stacks and Postfix notation::  
                   3499: * Your first definition::       
                   3500: * How does that work?::         
                   3501: * Forth is written in Forth::   
                   3502: * Review - elements of a Forth system::  
                   3503: * Where to go next::            
                   3504: * Exercises::                   
1.29      crook    3505: @end menu
1.21      crook    3506: 
1.29      crook    3507: @comment ----------------------------------------------
                   3508: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3509: @section Introducing the Text Interpreter
                   3510: @cindex text interpreter
                   3511: @cindex outer interpreter
1.21      crook    3512: 
1.30      anton    3513: @c IMO this is too detailed and the pace is too slow for
                   3514: @c an introduction.  If you know German, take a look at
                   3515: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3516: @c to see how I do it - anton 
                   3517: 
1.44      crook    3518: @c nac-> Where I have accepted your comments 100% and modified the text
                   3519: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3520: @c response like this to attempt to rationalise what I have done. Of
                   3521: @c course, this is a very clumsy mechanism for something that would be
                   3522: @c done far more efficiently over a beer. Please delete any dialogue
                   3523: @c you consider closed.
                   3524: 
1.29      crook    3525: When you invoke the Forth image, you will see a startup banner printed
                   3526: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3527: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3528: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3529: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3530: about the text interpreter as you read through this chapter, for more
                   3531: detail @pxref{The Text Interpreter}).
1.21      crook    3532: 
1.29      crook    3533: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3534: input. Type a number and press the @key{RET} key:
1.21      crook    3535: 
1.26      crook    3536: @example
1.30      anton    3537: @kbd{45@key{RET}}  ok
1.26      crook    3538: @end example
1.21      crook    3539: 
1.29      crook    3540: Rather than give you a prompt to invite you to input something, the text
                   3541: interpreter prints a status message @i{after} it has processed a line
                   3542: of input. The status message in this case (``@code{ ok}'' followed by
                   3543: carriage-return) indicates that the text interpreter was able to process
                   3544: all of your input successfully. Now type something illegal:
                   3545: 
                   3546: @example
1.30      anton    3547: @kbd{qwer341@key{RET}}
1.134     anton    3548: *the terminal*:2: Undefined word
                   3549: >>>qwer341<<<
                   3550: Backtrace:
                   3551: $2A95B42A20 throw 
                   3552: $2A95B57FB8 no.extensions 
1.29      crook    3553: @end example
1.23      crook    3554: 
1.134     anton    3555: The exact text, other than the ``Undefined word'' may differ slightly
                   3556: on your system, but the effect is the same; when the text interpreter
1.29      crook    3557: detects an error, it discards any remaining text on a line, resets
1.134     anton    3558: certain internal state and prints an error message. For a detailed
                   3559: description of error messages see @ref{Error messages}.
1.23      crook    3560: 
1.29      crook    3561: The text interpreter waits for you to press carriage-return, and then
                   3562: processes your input line. Starting at the beginning of the line, it
                   3563: breaks the line into groups of characters separated by spaces. For each
                   3564: group of characters in turn, it makes two attempts to do something:
1.23      crook    3565: 
1.29      crook    3566: @itemize @bullet
                   3567: @item
1.44      crook    3568: @cindex name dictionary
1.29      crook    3569: It tries to treat it as a command. It does this by searching a @dfn{name
                   3570: dictionary}. If the group of characters matches an entry in the name
                   3571: dictionary, the name dictionary provides the text interpreter with
                   3572: information that allows the text interpreter perform some actions. In
                   3573: Forth jargon, we say that the group
                   3574: @cindex word
                   3575: @cindex definition
                   3576: @cindex execution token
                   3577: @cindex xt
                   3578: of characters names a @dfn{word}, that the dictionary search returns an
                   3579: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3580: word, and that the text interpreter executes the xt. Often, the terms
                   3581: @dfn{word} and @dfn{definition} are used interchangeably.
                   3582: @item
                   3583: If the text interpreter fails to find a match in the name dictionary, it
                   3584: tries to treat the group of characters as a number in the current number
                   3585: base (when you start up Forth, the current number base is base 10). If
                   3586: the group of characters legitimately represents a number, the text
                   3587: interpreter pushes the number onto a stack (we'll learn more about that
                   3588: in the next section).
                   3589: @end itemize
1.23      crook    3590: 
1.29      crook    3591: If the text interpreter is unable to do either of these things with any
                   3592: group of characters, it discards the group of characters and the rest of
                   3593: the line, then prints an error message. If the text interpreter reaches
                   3594: the end of the line without error, it prints the status message ``@code{ ok}''
                   3595: followed by carriage-return.
1.21      crook    3596: 
1.29      crook    3597: This is the simplest command we can give to the text interpreter:
1.23      crook    3598: 
                   3599: @example
1.30      anton    3600: @key{RET}  ok
1.23      crook    3601: @end example
1.21      crook    3602: 
1.29      crook    3603: The text interpreter did everything we asked it to do (nothing) without
                   3604: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3605: command:
1.21      crook    3606: 
1.23      crook    3607: @example
1.30      anton    3608: @kbd{12 dup fred dup@key{RET}}
1.134     anton    3609: *the terminal*:3: Undefined word
                   3610: 12 dup >>>fred<<< dup
                   3611: Backtrace:
                   3612: $2A95B42A20 throw 
                   3613: $2A95B57FB8 no.extensions 
1.23      crook    3614: @end example
1.21      crook    3615: 
1.29      crook    3616: When you press the carriage-return key, the text interpreter starts to
                   3617: work its way along the line:
1.21      crook    3618: 
1.29      crook    3619: @itemize @bullet
                   3620: @item
                   3621: When it gets to the space after the @code{2}, it takes the group of
                   3622: characters @code{12} and looks them up in the name
                   3623: dictionary@footnote{We can't tell if it found them or not, but assume
                   3624: for now that it did not}. There is no match for this group of characters
                   3625: in the name dictionary, so it tries to treat them as a number. It is
                   3626: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3627: (whatever that means).
                   3628: @item
                   3629: The text interpreter resumes scanning the line and gets the next group
                   3630: of characters, @code{dup}. It looks it up in the name dictionary and
                   3631: (you'll have to take my word for this) finds it, and executes the word
                   3632: @code{dup} (whatever that means).
                   3633: @item
                   3634: Once again, the text interpreter resumes scanning the line and gets the
                   3635: group of characters @code{fred}. It looks them up in the name
                   3636: dictionary, but can't find them. It tries to treat them as a number, but
                   3637: they don't represent any legal number.
                   3638: @end itemize
1.21      crook    3639: 
1.29      crook    3640: At this point, the text interpreter gives up and prints an error
                   3641: message. The error message shows exactly how far the text interpreter
                   3642: got in processing the line. In particular, it shows that the text
                   3643: interpreter made no attempt to do anything with the final character
                   3644: group, @code{dup}, even though we have good reason to believe that the
                   3645: text interpreter would have no problem looking that word up and
                   3646: executing it a second time.
1.21      crook    3647: 
                   3648: 
1.29      crook    3649: @comment ----------------------------------------------
                   3650: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3651: @section Stacks, postfix notation and parameter passing
                   3652: @cindex text interpreter
                   3653: @cindex outer interpreter
1.21      crook    3654: 
1.29      crook    3655: In procedural programming languages (like C and Pascal), the
                   3656: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3657: functions or procedures are called with @dfn{explicit parameters}. For
                   3658: example, in C we might write:
1.21      crook    3659: 
1.23      crook    3660: @example
1.29      crook    3661: total = total + new_volume(length,height,depth);
1.23      crook    3662: @end example
1.21      crook    3663: 
1.23      crook    3664: @noindent
1.29      crook    3665: where new_volume is a function-call to another piece of code, and total,
                   3666: length, height and depth are all variables. length, height and depth are
                   3667: parameters to the function-call.
1.21      crook    3668: 
1.29      crook    3669: In Forth, the equivalent of the function or procedure is the
                   3670: @dfn{definition} and parameters are implicitly passed between
                   3671: definitions using a shared stack that is visible to the
                   3672: programmer. Although Forth does support variables, the existence of the
                   3673: stack means that they are used far less often than in most other
                   3674: programming languages. When the text interpreter encounters a number, it
                   3675: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3676: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3677: used for any operation is implied unambiguously by the operation being
                   3678: performed. The stack used for all integer operations is called the @dfn{data
                   3679: stack} and, since this is the stack used most commonly, references to
                   3680: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3681: 
1.29      crook    3682: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3683: 
1.23      crook    3684: @example
1.30      anton    3685: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3686: @end example
1.21      crook    3687: 
1.29      crook    3688: Then this instructs the text interpreter to placed three numbers on the
                   3689: (data) stack. An analogy for the behaviour of the stack is to take a
                   3690: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3691: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3692: you take a card off the pile then, unless you're prepared to fiddle a
                   3693: bit, the card that you take off will be the 3 (``first-out''). The
                   3694: number that will be first-out of the stack is called the @dfn{top of
                   3695: stack}, which
                   3696: @cindex TOS definition
                   3697: is often abbreviated to @dfn{TOS}.
1.21      crook    3698: 
1.29      crook    3699: To understand how parameters are passed in Forth, consider the
                   3700: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3701: be surprised to learn that this definition performs addition. More
                   3702: precisely, it adds two number together and produces a result. Where does
                   3703: it get the two numbers from? It takes the top two numbers off the
                   3704: stack. Where does it place the result? On the stack. You can act-out the
                   3705: behaviour of @code{+} with your playing cards like this:
1.21      crook    3706: 
                   3707: @itemize @bullet
                   3708: @item
1.29      crook    3709: Pick up two cards from the stack on the table
1.21      crook    3710: @item
1.29      crook    3711: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3712: numbers''
1.21      crook    3713: @item
1.29      crook    3714: Decide that the answer is 5
1.21      crook    3715: @item
1.29      crook    3716: Shuffle the two cards back into the pack and find a 5
1.21      crook    3717: @item
1.29      crook    3718: Put a 5 on the remaining ace that's on the table.
1.21      crook    3719: @end itemize
                   3720: 
1.29      crook    3721: If you don't have a pack of cards handy but you do have Forth running,
                   3722: you can use the definition @code{.s} to show the current state of the stack,
                   3723: without affecting the stack. Type:
1.21      crook    3724: 
                   3725: @example
1.124     anton    3726: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30      anton    3727: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3728: @end example
                   3729: 
1.124     anton    3730: The text interpreter looks up the word @code{clearstacks} and executes
                   3731: it; it tidies up the stacks and removes any entries that may have been
1.29      crook    3732: left on it by earlier examples. The text interpreter pushes each of the
                   3733: three numbers in turn onto the stack. Finally, the text interpreter
                   3734: looks up the word @code{.s} and executes it. The effect of executing
                   3735: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3736: followed by a list of all the items on the stack; the item on the far
                   3737: right-hand side is the TOS.
1.21      crook    3738: 
1.29      crook    3739: You can now type:
1.21      crook    3740: 
1.29      crook    3741: @example
1.30      anton    3742: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3743: @end example
1.21      crook    3744: 
1.29      crook    3745: @noindent
                   3746: which is correct; there are now 2 items on the stack and the result of
                   3747: the addition is 5.
1.23      crook    3748: 
1.29      crook    3749: If you're playing with cards, try doing a second addition: pick up the
                   3750: two cards, work out that their sum is 6, shuffle them into the pack,
                   3751: look for a 6 and place that on the table. You now have just one item on
                   3752: the stack. What happens if you try to do a third addition? Pick up the
                   3753: first card, pick up the second card -- ah! There is no second card. This
                   3754: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95      anton    3755: do the same thing with Forth it often reports an error (probably a Stack
1.29      crook    3756: Underflow or an Invalid Memory Address error).
1.23      crook    3757: 
1.29      crook    3758: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3759: which simply accepts that there is a finite amount of storage space
                   3760: reserved for the stack. To stretch the playing card analogy, if you had
                   3761: enough packs of cards and you piled the cards up on the table, you would
                   3762: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3763: allows you to set the maximum size of the stacks. In general, the only
                   3764: time that you will get a stack overflow is because a definition has a
                   3765: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3766: 
1.29      crook    3767: There's one final use for the playing card analogy. If you model your
                   3768: stack using a pack of playing cards, the maximum number of items on
                   3769: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3770: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3771: possible numbers are positive integer numbers 1 through 13; you can't
                   3772: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3773: think about some of the cards, you can accommodate different
                   3774: numbers. For example, you could think of the Jack as representing 0,
                   3775: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3776: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3777: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3778: 
1.29      crook    3779: In that analogy, the limit was the amount of information that a single
                   3780: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3781: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3782: implementation dependent and affects the maximum value that a stack
                   3783: entry can hold. A Standard Forth provides a cell size of at least
                   3784: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3785: 
1.29      crook    3786: Forth does not do any type checking for you, so you are free to
                   3787: manipulate and combine stack items in any way you wish. A convenient way
                   3788: of treating stack items is as 2's complement signed integers, and that
                   3789: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3790: 
1.29      crook    3791: @example
1.30      anton    3792: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3793: @end example
1.21      crook    3794: 
1.29      crook    3795: If you use numbers and definitions like @code{+} in order to turn Forth
                   3796: into a great big pocket calculator, you will realise that it's rather
                   3797: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3798: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3799: result). The terminology used to describe this difference is to say that
                   3800: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3801: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3802: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3803: 
1.29      crook    3804: Whilst postfix notation might look confusing to begin with, it has
                   3805: several important advantages:
1.21      crook    3806: 
1.23      crook    3807: @itemize @bullet
                   3808: @item
1.29      crook    3809: it is unambiguous
1.23      crook    3810: @item
1.29      crook    3811: it is more concise
1.23      crook    3812: @item
1.29      crook    3813: it fits naturally with a stack-based system
1.23      crook    3814: @end itemize
1.21      crook    3815: 
1.29      crook    3816: To examine these claims in more detail, consider these sums:
1.21      crook    3817: 
1.29      crook    3818: @example
                   3819: 6 + 5 * 4 =
                   3820: 4 * 5 + 6 =
                   3821: @end example
1.21      crook    3822: 
1.29      crook    3823: If you're just learning maths or your maths is very rusty, you will
                   3824: probably come up with the answer 44 for the first and 26 for the
                   3825: second. If you are a bit of a whizz at maths you will remember the
                   3826: @i{convention} that multiplication takes precendence over addition, and
                   3827: you'd come up with the answer 26 both times. To explain the answer 26
                   3828: to someone who got the answer 44, you'd probably rewrite the first sum
                   3829: like this:
1.21      crook    3830: 
1.29      crook    3831: @example
                   3832: 6 + (5 * 4) =
                   3833: @end example
1.21      crook    3834: 
1.29      crook    3835: If what you really wanted was to perform the addition before the
                   3836: multiplication, you would have to use parentheses to force it.
1.21      crook    3837: 
1.29      crook    3838: If you did the first two sums on a pocket calculator you would probably
                   3839: get the right answers, unless you were very cautious and entered them using
                   3840: these keystroke sequences:
1.21      crook    3841: 
1.29      crook    3842: 6 + 5 = * 4 =
                   3843: 4 * 5 = + 6 =
1.21      crook    3844: 
1.29      crook    3845: Postfix notation is unambiguous because the order that the operators
                   3846: are applied is always explicit; that also means that parentheses are
                   3847: never required. The operators are @i{active} (the act of quoting the
                   3848: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3849: 
1.29      crook    3850: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3851: equivalent ways:
1.26      crook    3852: 
                   3853: @example
1.29      crook    3854: 6 5 4 * +      or:
                   3855: 5 4 * 6 +
1.26      crook    3856: @end example
1.23      crook    3857: 
1.29      crook    3858: An important thing that you should notice about this notation is that
                   3859: the @i{order} of the numbers does not change; if you want to subtract
                   3860: 2 from 10 you type @code{10 2 -}.
1.1       anton    3861: 
1.29      crook    3862: The reason that Forth uses postfix notation is very simple to explain: it
                   3863: makes the implementation extremely simple, and it follows naturally from
                   3864: using the stack as a mechanism for passing parameters. Another way of
                   3865: thinking about this is to realise that all Forth definitions are
                   3866: @i{active}; they execute as they are encountered by the text
                   3867: interpreter. The result of this is that the syntax of Forth is trivially
                   3868: simple.
1.1       anton    3869: 
                   3870: 
                   3871: 
1.29      crook    3872: @comment ----------------------------------------------
                   3873: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3874: @section Your first Forth definition
                   3875: @cindex first definition
1.1       anton    3876: 
1.29      crook    3877: Until now, the examples we've seen have been trivial; we've just been
                   3878: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3879: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3880: again@footnote{That's not quite true. If you press the up-arrow key on
                   3881: your keyboard you should be able to scroll back to any earlier command,
                   3882: edit it and re-enter it.} In this section we'll see how to add new
                   3883: words to Forth's vocabulary.
1.1       anton    3884: 
1.29      crook    3885: The easiest way to create a new word is to use a @dfn{colon
                   3886: definition}. We'll define a few and try them out before worrying too
                   3887: much about how they work. Try typing in these examples; be careful to
                   3888: copy the spaces accurately:
1.1       anton    3889: 
1.29      crook    3890: @example
                   3891: : add-two 2 + . ;
                   3892: : greet ." Hello and welcome" ;
                   3893: : demo 5 add-two ;
                   3894: @end example
1.1       anton    3895: 
1.29      crook    3896: @noindent
                   3897: Now try them out:
1.1       anton    3898: 
1.29      crook    3899: @example
1.30      anton    3900: @kbd{greet@key{RET}} Hello and welcome  ok
                   3901: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3902: @kbd{4 add-two@key{RET}} 6  ok
                   3903: @kbd{demo@key{RET}} 7  ok
                   3904: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3905: @end example
1.1       anton    3906: 
1.29      crook    3907: The first new thing that we've introduced here is the pair of words
                   3908: @code{:} and @code{;}. These are used to start and terminate a new
                   3909: definition, respectively. The first word after the @code{:} is the name
                   3910: for the new definition.
1.1       anton    3911: 
1.29      crook    3912: As you can see from the examples, a definition is built up of words that
                   3913: have already been defined; Forth makes no distinction between
                   3914: definitions that existed when you started the system up, and those that
                   3915: you define yourself.
1.1       anton    3916: 
1.29      crook    3917: The examples also introduce the words @code{.} (dot), @code{."}
                   3918: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3919: the stack and displays it. It's like @code{.s} except that it only
                   3920: displays the top item of the stack and it is destructive; after it has
                   3921: executed, the number is no longer on the stack. There is always one
                   3922: space printed after the number, and no spaces before it. Dot-quote
                   3923: defines a string (a sequence of characters) that will be printed when
                   3924: the word is executed. The string can contain any printable characters
                   3925: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3926: word but it acts as a delimiter (the way that delimiters work is
                   3927: described in the next section). Finally, @code{dup} duplicates the value
                   3928: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3929: 
1.29      crook    3930: We already know that the text interpreter searches through the
                   3931: dictionary to locate names. If you've followed the examples earlier, you
                   3932: will already have a definition called @code{add-two}. Lets try modifying
                   3933: it by typing in a new definition:
1.1       anton    3934: 
1.29      crook    3935: @example
1.30      anton    3936: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3937: @end example
1.5       anton    3938: 
1.29      crook    3939: Forth recognised that we were defining a word that already exists, and
                   3940: printed a message to warn us of that fact. Let's try out the new
                   3941: definition:
1.5       anton    3942: 
1.29      crook    3943: @example
1.30      anton    3944: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3945: @end example
1.1       anton    3946: 
1.29      crook    3947: @noindent
                   3948: All that we've actually done here, though, is to create a new
                   3949: definition, with a particular name. The fact that there was already a
                   3950: definition with the same name did not make any difference to the way
                   3951: that the new definition was created (except that Forth printed a warning
                   3952: message). The old definition of add-two still exists (try @code{demo}
                   3953: again to see that this is true). Any new definition will use the new
                   3954: definition of @code{add-two}, but old definitions continue to use the
                   3955: version that already existed at the time that they were @code{compiled}.
1.1       anton    3956: 
1.29      crook    3957: Before you go on to the next section, try defining and redefining some
                   3958: words of your own.
1.1       anton    3959: 
1.29      crook    3960: @comment ----------------------------------------------
                   3961: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3962: @section How does that work?
                   3963: @cindex parsing words
1.1       anton    3964: 
1.30      anton    3965: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3966: 
                   3967: @c Is it a good idea to talk about the interpretation semantics of a
                   3968: @c number? We don't have an xt to go along with it. - anton
                   3969: 
                   3970: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3971: @c be better to keep them (or add run-time semantics), to make it easier to
                   3972: @c explain what compilation semantics usually does. - anton
                   3973: 
1.44      crook    3974: @c nac-> I removed the term ``default compilation sematics'' from the
                   3975: @c introductory chapter. Removing ``execution semantics'' was making
                   3976: @c everything simpler to explain, then I think the use of this term made
                   3977: @c everything more complex again. I replaced it with ``default
                   3978: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3979: @c ``a definition that has neither the immediate nor the compile-only
1.83      anton    3980: @c flag set''.
                   3981: 
                   3982: @c anton: I have eliminated default semantics (except in one place where it
                   3983: @c means "default interpretation and compilation semantics"), because it
                   3984: @c makes no sense in the presence of combined words.  I reverted to
                   3985: @c "execution semantics" where necessary.
                   3986: 
                   3987: @c nac-> I reworded big chunks of the ``how does that work''
1.44      crook    3988: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3989: @c what you think -- I know I have not addressed your primary concern
                   3990: @c that it is too heavy-going for an introduction. From what I understood
                   3991: @c of your course notes it looks as though they might be a good framework. 
                   3992: @c Things that I've tried to capture here are some things that came as a
                   3993: @c great revelation here when I first understood them. Also, I like the
                   3994: @c fact that a very simple code example shows up almost all of the issues
                   3995: @c that you need to understand to see how Forth works. That's unique and
                   3996: @c worthwhile to emphasise.
                   3997: 
1.83      anton    3998: @c anton: I think it's a good idea to present the details, especially those
                   3999: @c that you found to be a revelation, and probably the tutorial tries to be
                   4000: @c too superficial and does not get some of the things across that make
                   4001: @c Forth special.  I do believe that most of the time these things should
                   4002: @c be discussed at the end of a section or in separate sections instead of
                   4003: @c in the middle of a section (e.g., the stuff you added in "User-defined
                   4004: @c defining words" leads in a completely different direction from the rest
                   4005: @c of the section).
                   4006: 
1.29      crook    4007: Now we're going to take another look at the definition of @code{add-two}
                   4008: from the previous section. From our knowledge of the way that the text
                   4009: interpreter works, we would have expected this result when we tried to
                   4010: define @code{add-two}:
1.21      crook    4011: 
1.29      crook    4012: @example
1.44      crook    4013: @kbd{: add-two 2 + . ;@key{RET}}
1.134     anton    4014: *the terminal*:4: Undefined word
                   4015: : >>>add-two<<< 2 + . ;
1.29      crook    4016: @end example
1.28      crook    4017: 
1.29      crook    4018: The reason that this didn't happen is bound up in the way that @code{:}
                   4019: works. The word @code{:} does two special things. The first special
                   4020: thing that it does prevents the text interpreter from ever seeing the
                   4021: characters @code{add-two}. The text interpreter uses a variable called
                   4022: @cindex modifying >IN
1.44      crook    4023: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    4024: input line. When it encounters the word @code{:} it behaves in exactly
                   4025: the same way as it does for any other word; it looks it up in the name
                   4026: dictionary, finds its xt and executes it. When @code{:} executes, it
                   4027: looks at the input buffer, finds the word @code{add-two} and advances the
                   4028: value of @code{>IN} to point past it. It then does some other stuff
                   4029: associated with creating the new definition (including creating an entry
                   4030: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   4031: completes, control returns to the text interpreter, which is oblivious
                   4032: to the fact that it has been tricked into ignoring part of the input
                   4033: line.
1.21      crook    4034: 
1.29      crook    4035: @cindex parsing words
                   4036: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   4037: prevent the text interpreter from acting on the whole of the input line
                   4038: -- are called @dfn{parsing words}.
1.21      crook    4039: 
1.29      crook    4040: @cindex @code{state} - effect on the text interpreter
                   4041: @cindex text interpreter - effect of state
                   4042: The second special thing that @code{:} does is change the value of a
                   4043: variable called @code{state}, which affects the way that the text
                   4044: interpreter behaves. When Gforth starts up, @code{state} has the value
                   4045: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   4046: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    4047: the text interpreter is said to be @dfn{compiling}.
                   4048: 
                   4049: In this example, the text interpreter is compiling when it processes the
                   4050: string ``@code{2 + . ;}''. It still breaks the string down into
                   4051: character sequences in the same way. However, instead of pushing the
                   4052: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   4053: into the definition of @code{add-two} that will make the number @code{2} get
                   4054: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   4055: the behaviours of @code{+} and @code{.} are also compiled into the
                   4056: definition.
                   4057: 
                   4058: One category of words don't get compiled. These so-called @dfn{immediate
                   4059: words} get executed (performed @i{now}) regardless of whether the text
                   4060: interpreter is interpreting or compiling. The word @code{;} is an
                   4061: immediate word. Rather than being compiled into the definition, it
                   4062: executes. Its effect is to terminate the current definition, which
                   4063: includes changing the value of @code{state} back to 0.
                   4064: 
                   4065: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   4066: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   4067: definition.
1.28      crook    4068: 
1.30      anton    4069: In Forth, every word or number can be described in terms of two
1.29      crook    4070: properties:
1.28      crook    4071: 
                   4072: @itemize @bullet
                   4073: @item
1.29      crook    4074: @cindex interpretation semantics
1.44      crook    4075: Its @dfn{interpretation semantics} describe how it will behave when the
                   4076: text interpreter encounters it in @dfn{interpret} state. The
                   4077: interpretation semantics of a word are represented by an @dfn{execution
                   4078: token}.
1.28      crook    4079: @item
1.29      crook    4080: @cindex compilation semantics
1.44      crook    4081: Its @dfn{compilation semantics} describe how it will behave when the
                   4082: text interpreter encounters it in @dfn{compile} state. The compilation
                   4083: semantics of a word are represented in an implementation-dependent way;
                   4084: Gforth uses a @dfn{compilation token}.
1.29      crook    4085: @end itemize
                   4086: 
                   4087: @noindent
                   4088: Numbers are always treated in a fixed way:
                   4089: 
                   4090: @itemize @bullet
1.28      crook    4091: @item
1.44      crook    4092: When the number is @dfn{interpreted}, its behaviour is to push the
                   4093: number onto the stack.
1.28      crook    4094: @item
1.30      anton    4095: When the number is @dfn{compiled}, a piece of code is appended to the
                   4096: current definition that pushes the number when it runs. (In other words,
                   4097: the compilation semantics of a number are to postpone its interpretation
                   4098: semantics until the run-time of the definition that it is being compiled
                   4099: into.)
1.29      crook    4100: @end itemize
                   4101: 
1.44      crook    4102: Words don't behave in such a regular way, but most have @i{default
                   4103: semantics} which means that they behave like this:
1.29      crook    4104: 
                   4105: @itemize @bullet
1.28      crook    4106: @item
1.30      anton    4107: The @dfn{interpretation semantics} of the word are to do something useful.
                   4108: @item
1.29      crook    4109: The @dfn{compilation semantics} of the word are to append its
1.30      anton    4110: @dfn{interpretation semantics} to the current definition (so that its
                   4111: run-time behaviour is to do something useful).
1.28      crook    4112: @end itemize
                   4113: 
1.30      anton    4114: @cindex immediate words
1.44      crook    4115: The actual behaviour of any particular word can be controlled by using
                   4116: the words @code{immediate} and @code{compile-only} when the word is
                   4117: defined. These words set flags in the name dictionary entry of the most
                   4118: recently defined word, and these flags are retrieved by the text
                   4119: interpreter when it finds the word in the name dictionary.
                   4120: 
                   4121: A word that is marked as @dfn{immediate} has compilation semantics that
                   4122: are identical to its interpretation semantics. In other words, it
                   4123: behaves like this:
1.29      crook    4124: 
                   4125: @itemize @bullet
                   4126: @item
1.30      anton    4127: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    4128: @item
1.30      anton    4129: The @dfn{compilation semantics} of the word are to do something useful
                   4130: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    4131: @end itemize
1.28      crook    4132: 
1.44      crook    4133: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   4134: performing the interpretation semantics of the word directly; an attempt
                   4135: to do so will generate an error. It is never necessary to use
                   4136: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   4137: provided by many implementations) but it is good etiquette to apply it
                   4138: to a word that will not behave correctly (and might have unexpected
                   4139: side-effects) in interpret state. For example, it is only legal to use
                   4140: the conditional word @code{IF} within a definition. If you forget this
                   4141: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   4142: @code{compile-only} allows the text interpreter to generate a helpful
                   4143: error message rather than subjecting you to the consequences of your
                   4144: folly.
                   4145: 
1.29      crook    4146: This example shows the difference between an immediate and a
                   4147: non-immediate word:
1.28      crook    4148: 
1.29      crook    4149: @example
                   4150: : show-state state @@ . ;
                   4151: : show-state-now show-state ; immediate
                   4152: : word1 show-state ;
                   4153: : word2 show-state-now ;
1.28      crook    4154: @end example
1.23      crook    4155: 
1.29      crook    4156: The word @code{immediate} after the definition of @code{show-state-now}
                   4157: makes that word an immediate word. These definitions introduce a new
                   4158: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   4159: variable, and leaves it on the stack. Therefore, the behaviour of
                   4160: @code{show-state} is to print a number that represents the current value
                   4161: of @code{state}.
1.28      crook    4162: 
1.29      crook    4163: When you execute @code{word1}, it prints the number 0, indicating that
                   4164: the system is interpreting. When the text interpreter compiled the
                   4165: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    4166: compilation semantics are to append its interpretation semantics to the
1.29      crook    4167: current definition. When you execute @code{word1}, it performs the
1.30      anton    4168: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    4169: (and therefore @code{show-state}) are executed, the system is
                   4170: interpreting.
1.28      crook    4171: 
1.30      anton    4172: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    4173: you should have seen the number -1 printed, followed by ``@code{
                   4174: ok}''. When the text interpreter compiled the definition of
                   4175: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    4176: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4177: semantics. It is executed straight away (even before the text
                   4178: interpreter has moved on to process another group of characters; the
                   4179: @code{;} in this example). The effect of executing it are to display the
                   4180: value of @code{state} @i{at the time that the definition of}
                   4181: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4182: system is compiling at this time. If you execute @code{word2} it does
                   4183: nothing at all.
1.28      crook    4184: 
1.29      crook    4185: @cindex @code{."}, how it works
                   4186: Before leaving the subject of immediate words, consider the behaviour of
                   4187: @code{."} in the definition of @code{greet}, in the previous
                   4188: section. This word is both a parsing word and an immediate word. Notice
                   4189: that there is a space between @code{."} and the start of the text
                   4190: @code{Hello and welcome}, but that there is no space between the last
                   4191: letter of @code{welcome} and the @code{"} character. The reason for this
                   4192: is that @code{."} is a Forth word; it must have a space after it so that
                   4193: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4194: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4195: is displayed, there is neither a space before the @code{H} nor after the
                   4196: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4197: that @code{greet} is defined. When it executes, its behaviour is to
                   4198: search forward in the input line looking for the delimiter. When it
                   4199: finds the delimiter, it updates @code{>IN} to point past the
                   4200: delimiter. It also compiles some magic code into the definition of
                   4201: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4202: compiles the string @code{Hello and welcome} into memory so that it is
                   4203: available to be printed later. When the text interpreter gains control,
                   4204: the next word it finds in the input stream is @code{;} and so it
                   4205: terminates the definition of @code{greet}.
1.28      crook    4206: 
                   4207: 
                   4208: @comment ----------------------------------------------
1.29      crook    4209: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4210: @section Forth is written in Forth
                   4211: @cindex structure of Forth programs
                   4212: 
                   4213: When you start up a Forth compiler, a large number of definitions
                   4214: already exist. In Forth, you develop a new application using bottom-up
                   4215: programming techniques to create new definitions that are defined in
                   4216: terms of existing definitions. As you create each definition you can
                   4217: test and debug it interactively.
                   4218: 
                   4219: If you have tried out the examples in this section, you will probably
                   4220: have typed them in by hand; when you leave Gforth, your definitions will
                   4221: be lost. You can avoid this by using a text editor to enter Forth source
                   4222: code into a file, and then loading code from the file using
1.49      anton    4223: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    4224: processed by the text interpreter, just as though you had typed it in by
                   4225: hand@footnote{Actually, there are some subtle differences -- see
                   4226: @ref{The Text Interpreter}.}.
                   4227: 
                   4228: Gforth also supports the traditional Forth alternative to using text
1.49      anton    4229: files for program entry (@pxref{Blocks}).
1.28      crook    4230: 
1.29      crook    4231: In common with many, if not most, Forth compilers, most of Gforth is
                   4232: actually written in Forth. All of the @file{.fs} files in the
                   4233: installation directory@footnote{For example,
1.30      anton    4234: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4235: study to see examples of Forth programming.
1.28      crook    4236: 
1.29      crook    4237: Gforth maintains a history file that records every line that you type to
                   4238: the text interpreter. This file is preserved between sessions, and is
                   4239: used to provide a command-line recall facility. If you enter long
                   4240: definitions by hand, you can use a text editor to paste them out of the
                   4241: history file into a Forth source file for reuse at a later time
1.49      anton    4242: (for more information @pxref{Command-line editing}).
1.28      crook    4243: 
                   4244: 
                   4245: @comment ----------------------------------------------
1.29      crook    4246: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4247: @section Review - elements of a Forth system
                   4248: @cindex elements of a Forth system
1.28      crook    4249: 
1.29      crook    4250: To summarise this chapter:
1.28      crook    4251: 
                   4252: @itemize @bullet
                   4253: @item
1.29      crook    4254: Forth programs use @dfn{factoring} to break a problem down into small
                   4255: fragments called @dfn{words} or @dfn{definitions}.
                   4256: @item
                   4257: Forth program development is an interactive process.
                   4258: @item
                   4259: The main command loop that accepts input, and controls both
                   4260: interpretation and compilation, is called the @dfn{text interpreter}
                   4261: (also known as the @dfn{outer interpreter}).
                   4262: @item
                   4263: Forth has a very simple syntax, consisting of words and numbers
                   4264: separated by spaces or carriage-return characters. Any additional syntax
                   4265: is imposed by @dfn{parsing words}.
                   4266: @item
                   4267: Forth uses a stack to pass parameters between words. As a result, it
                   4268: uses postfix notation.
                   4269: @item
                   4270: To use a word that has previously been defined, the text interpreter
                   4271: searches for the word in the @dfn{name dictionary}.
                   4272: @item
1.30      anton    4273: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4274: @item
1.29      crook    4275: The text interpreter uses the value of @code{state} to select between
                   4276: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4277: semantics} of a word that it encounters.
1.28      crook    4278: @item
1.30      anton    4279: The relationship between the @dfn{interpretation semantics} and
                   4280: @dfn{compilation semantics} for a word
1.29      crook    4281: depend upon the way in which the word was defined (for example, whether
                   4282: it is an @dfn{immediate} word).
1.28      crook    4283: @item
1.29      crook    4284: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4285: definitions}) or in some other way (usually a lower-level language and
                   4286: as a result often called @dfn{low-level definitions}, @dfn{code
                   4287: definitions} or @dfn{primitives}).
1.28      crook    4288: @item
1.29      crook    4289: Many Forth systems are implemented mainly in Forth.
1.28      crook    4290: @end itemize
                   4291: 
                   4292: 
1.29      crook    4293: @comment ----------------------------------------------
1.48      anton    4294: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4295: @section Where To Go Next
                   4296: @cindex where to go next
1.28      crook    4297: 
1.29      crook    4298: Amazing as it may seem, if you have read (and understood) this far, you
                   4299: know almost all the fundamentals about the inner workings of a Forth
                   4300: system. You certainly know enough to be able to read and understand the
                   4301: rest of this manual and the ANS Forth document, to learn more about the
                   4302: facilities that Forth in general and Gforth in particular provide. Even
                   4303: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4304: However, that's not a good idea just yet... better to try writing some
1.29      crook    4305: programs in Gforth.
1.28      crook    4306: 
1.29      crook    4307: Forth has such a rich vocabulary that it can be hard to know where to
                   4308: start in learning it. This section suggests a few sets of words that are
                   4309: enough to write small but useful programs. Use the word index in this
                   4310: document to learn more about each word, then try it out and try to write
                   4311: small definitions using it. Start by experimenting with these words:
1.28      crook    4312: 
                   4313: @itemize @bullet
                   4314: @item
1.29      crook    4315: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4316: @item
                   4317: Comparison: @code{MIN MAX =}
                   4318: @item
                   4319: Logic: @code{AND OR XOR NOT}
                   4320: @item
                   4321: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4322: @item
1.29      crook    4323: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4324: @item
1.29      crook    4325: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4326: @item
1.29      crook    4327: Defining words: @code{: ; CREATE}
1.28      crook    4328: @item
1.29      crook    4329: Memory allocation words: @code{ALLOT ,}
1.28      crook    4330: @item
1.29      crook    4331: Tools: @code{SEE WORDS .S MARKER}
                   4332: @end itemize
                   4333: 
                   4334: When you have mastered those, go on to:
                   4335: 
                   4336: @itemize @bullet
1.28      crook    4337: @item
1.29      crook    4338: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4339: @item
1.29      crook    4340: Memory access: @code{@@ !}
1.28      crook    4341: @end itemize
1.23      crook    4342: 
1.29      crook    4343: When you have mastered these, there's nothing for it but to read through
                   4344: the whole of this manual and find out what you've missed.
                   4345: 
                   4346: @comment ----------------------------------------------
1.48      anton    4347: @node Exercises,  , Where to go next, Introduction
1.29      crook    4348: @section Exercises
                   4349: @cindex exercises
                   4350: 
                   4351: TODO: provide a set of programming excercises linked into the stuff done
                   4352: already and into other sections of the manual. Provide solutions to all
                   4353: the exercises in a .fs file in the distribution.
                   4354: 
                   4355: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4356: 
                   4357: @c excercises:
                   4358: @c 1. take inches and convert to feet and inches.
                   4359: @c 2. take temperature and convert from fahrenheight to celcius;
                   4360: @c    may need to care about symmetric vs floored??
                   4361: @c 3. take input line and do character substitution
                   4362: @c    to encipher or decipher
                   4363: @c 4. as above but work on a file for in and out
                   4364: @c 5. take input line and convert to pig-latin 
                   4365: @c
                   4366: @c thing of sets of things to exercise then come up with
                   4367: @c problems that need those things.
                   4368: 
                   4369: 
1.26      crook    4370: @c ******************************************************************
1.29      crook    4371: @node Words, Error messages, Introduction, Top
1.1       anton    4372: @chapter Forth Words
1.26      crook    4373: @cindex words
1.1       anton    4374: 
                   4375: @menu
                   4376: * Notation::                    
1.65      anton    4377: * Case insensitivity::          
                   4378: * Comments::                    
                   4379: * Boolean Flags::               
1.1       anton    4380: * Arithmetic::                  
                   4381: * Stack Manipulation::          
1.5       anton    4382: * Memory::                      
1.1       anton    4383: * Control Structures::          
                   4384: * Defining Words::              
1.65      anton    4385: * Interpretation and Compilation Semantics::  
1.47      crook    4386: * Tokens for Words::            
1.81      anton    4387: * Compiling words::             
1.65      anton    4388: * The Text Interpreter::        
1.111     anton    4389: * The Input Stream::            
1.65      anton    4390: * Word Lists::                  
                   4391: * Environmental Queries::       
1.12      anton    4392: * Files::                       
                   4393: * Blocks::                      
                   4394: * Other I/O::                   
1.121     anton    4395: * OS command line arguments::   
1.78      anton    4396: * Locals::                      
                   4397: * Structures::                  
                   4398: * Object-oriented Forth::       
1.12      anton    4399: * Programming Tools::           
1.150     anton    4400: * C Interface::                 
1.12      anton    4401: * Assembler and Code Words::    
                   4402: * Threading Words::             
1.65      anton    4403: * Passing Commands to the OS::  
                   4404: * Keeping track of Time::       
                   4405: * Miscellaneous Words::         
1.1       anton    4406: @end menu
                   4407: 
1.65      anton    4408: @node Notation, Case insensitivity, Words, Words
1.1       anton    4409: @section Notation
                   4410: @cindex notation of glossary entries
                   4411: @cindex format of glossary entries
                   4412: @cindex glossary notation format
                   4413: @cindex word glossary entry format
                   4414: 
                   4415: The Forth words are described in this section in the glossary notation
1.67      anton    4416: that has become a de-facto standard for Forth texts:
1.1       anton    4417: 
                   4418: @format
1.29      crook    4419: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4420: @end format
1.29      crook    4421: @i{Description}
1.1       anton    4422: 
                   4423: @table @var
                   4424: @item word
1.28      crook    4425: The name of the word.
1.1       anton    4426: 
                   4427: @item Stack effect
                   4428: @cindex stack effect
1.29      crook    4429: The stack effect is written in the notation @code{@i{before} --
                   4430: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4431: stack entries before and after the execution of the word. The rest of
                   4432: the stack is not touched by the word. The top of stack is rightmost,
                   4433: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4434: uses a separate floating point stack, but a unified stack
1.29      crook    4435: notation. Also, return stack effects are not shown in @i{stack
                   4436: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4437: the type and/or the function of the item. See below for a discussion of
                   4438: the types.
                   4439: 
                   4440: All words have two stack effects: A compile-time stack effect and a
                   4441: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4442: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4443: this standard behaviour, or the word does other unusual things at
                   4444: compile time, both stack effects are shown; otherwise only the run-time
                   4445: stack effect is shown.
                   4446: 
1.211     anton    4447: Also note that in code templates or examples there can be comments in
                   4448: parentheses that display the stack picture at this point; there is no
                   4449: @code{--} in these places, because there is no before-after situation.
                   4450: 
1.1       anton    4451: @cindex pronounciation of words
                   4452: @item pronunciation
                   4453: How the word is pronounced.
                   4454: 
                   4455: @cindex wordset
1.67      anton    4456: @cindex environment wordset
1.1       anton    4457: @item wordset
1.21      crook    4458: The ANS Forth standard is divided into several word sets. A standard
                   4459: system need not support all of them. Therefore, in theory, the fewer
                   4460: word sets your program uses the more portable it will be. However, we
                   4461: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4462: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4463: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4464: describes words that will work in future releases of Gforth;
                   4465: @code{gforth-internal} words are more volatile. Environmental query
                   4466: strings are also displayed like words; you can recognize them by the
1.21      crook    4467: @code{environment} in the word set field.
1.1       anton    4468: 
                   4469: @item Description
                   4470: A description of the behaviour of the word.
                   4471: @end table
                   4472: 
                   4473: @cindex types of stack items
                   4474: @cindex stack item types
                   4475: The type of a stack item is specified by the character(s) the name
                   4476: starts with:
                   4477: 
                   4478: @table @code
                   4479: @item f
                   4480: @cindex @code{f}, stack item type
                   4481: Boolean flags, i.e. @code{false} or @code{true}.
                   4482: @item c
                   4483: @cindex @code{c}, stack item type
                   4484: Char
                   4485: @item w
                   4486: @cindex @code{w}, stack item type
                   4487: Cell, can contain an integer or an address
                   4488: @item n
                   4489: @cindex @code{n}, stack item type
                   4490: signed integer
                   4491: @item u
                   4492: @cindex @code{u}, stack item type
                   4493: unsigned integer
                   4494: @item d
                   4495: @cindex @code{d}, stack item type
                   4496: double sized signed integer
                   4497: @item ud
                   4498: @cindex @code{ud}, stack item type
                   4499: double sized unsigned integer
                   4500: @item r
                   4501: @cindex @code{r}, stack item type
                   4502: Float (on the FP stack)
1.21      crook    4503: @item a-
1.1       anton    4504: @cindex @code{a_}, stack item type
                   4505: Cell-aligned address
1.21      crook    4506: @item c-
1.1       anton    4507: @cindex @code{c_}, stack item type
                   4508: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4509: @item f-
1.1       anton    4510: @cindex @code{f_}, stack item type
                   4511: Float-aligned address
1.21      crook    4512: @item df-
1.1       anton    4513: @cindex @code{df_}, stack item type
                   4514: Address aligned for IEEE double precision float
1.21      crook    4515: @item sf-
1.1       anton    4516: @cindex @code{sf_}, stack item type
                   4517: Address aligned for IEEE single precision float
                   4518: @item xt
                   4519: @cindex @code{xt}, stack item type
                   4520: Execution token, same size as Cell
                   4521: @item wid
                   4522: @cindex @code{wid}, stack item type
1.21      crook    4523: Word list ID, same size as Cell
1.68      anton    4524: @item ior, wior
                   4525: @cindex ior type description
                   4526: @cindex wior type description
                   4527: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
1.1       anton    4528: @item f83name
                   4529: @cindex @code{f83name}, stack item type
                   4530: Pointer to a name structure
                   4531: @item "
                   4532: @cindex @code{"}, stack item type
1.12      anton    4533: string in the input stream (not on the stack). The terminating character
                   4534: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4535: quotes.
                   4536: @end table
                   4537: 
1.65      anton    4538: @comment ----------------------------------------------
                   4539: @node Case insensitivity, Comments, Notation, Words
                   4540: @section Case insensitivity
                   4541: @cindex case sensitivity
                   4542: @cindex upper and lower case
                   4543: 
                   4544: Gforth is case-insensitive; you can enter definitions and invoke
                   4545: Standard words using upper, lower or mixed case (however,
                   4546: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   4547: options}).
                   4548: 
                   4549: ANS Forth only @i{requires} implementations to recognise Standard words
                   4550: when they are typed entirely in upper case. Therefore, a Standard
                   4551: program must use upper case for all Standard words. You can use whatever
                   4552: case you like for words that you define, but in a Standard program you
                   4553: have to use the words in the same case that you defined them.
                   4554: 
                   4555: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   4556: wordlists, @pxref{Word Lists}).
                   4557: 
                   4558: Two people have asked how to convert Gforth to be case-sensitive; while
                   4559: we think this is a bad idea, you can change all wordlists into tables
                   4560: like this:
                   4561: 
                   4562: @example
                   4563: ' table-find forth-wordlist wordlist-map @ !
                   4564: @end example
                   4565: 
                   4566: Note that you now have to type the predefined words in the same case
                   4567: that we defined them, which are varying.  You may want to convert them
                   4568: to your favourite case before doing this operation (I won't explain how,
                   4569: because if you are even contemplating doing this, you'd better have
                   4570: enough knowledge of Forth systems to know this already).
                   4571: 
                   4572: @node Comments, Boolean Flags, Case insensitivity, Words
1.21      crook    4573: @section Comments
1.26      crook    4574: @cindex comments
1.21      crook    4575: 
1.29      crook    4576: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4577: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4578: 
1.44      crook    4579: 
1.23      crook    4580: doc-(
1.21      crook    4581: doc-\
1.23      crook    4582: doc-\G
1.21      crook    4583: 
1.44      crook    4584: 
1.21      crook    4585: @node Boolean Flags, Arithmetic, Comments, Words
                   4586: @section Boolean Flags
1.26      crook    4587: @cindex Boolean flags
1.21      crook    4588: 
                   4589: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4590: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4591: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4592: a cell that has @i{any} bit set as @code{true}.
1.67      anton    4593: @c on and off to Memory? 
                   4594: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44      crook    4595: 
1.21      crook    4596: doc-true
                   4597: doc-false
1.29      crook    4598: doc-on
                   4599: doc-off
1.21      crook    4600: 
1.44      crook    4601: 
1.21      crook    4602: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4603: @section Arithmetic
                   4604: @cindex arithmetic words
                   4605: 
                   4606: @cindex division with potentially negative operands
                   4607: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4608: overflow on addition or multiplication, you may hear about division by
                   4609: zero if you are lucky. The operator is written after the operands, but
                   4610: the operands are still in the original order. I.e., the infix @code{2-1}
                   4611: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4612: operators. If you perform division with potentially negative operands,
                   4613: you do not want to use @code{/} or @code{/mod} with its undefined
                   4614: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4615: former, @pxref{Mixed precision}).
1.26      crook    4616: @comment TODO discuss the different division forms and the std approach
1.1       anton    4617: 
                   4618: @menu
                   4619: * Single precision::            
1.67      anton    4620: * Double precision::            Double-cell integer arithmetic
1.1       anton    4621: * Bitwise operations::          
1.67      anton    4622: * Numeric comparison::          
1.29      crook    4623: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4624: * Floating Point::              
                   4625: @end menu
                   4626: 
1.67      anton    4627: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1       anton    4628: @subsection Single precision
                   4629: @cindex single precision arithmetic words
                   4630: 
1.67      anton    4631: @c !! cell undefined
                   4632: 
                   4633: By default, numbers in Forth are single-precision integers that are one
1.26      crook    4634: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4635: treat them. For the rules used by the text interpreter for recognising
                   4636: single-precision integers see @ref{Number Conversion}.
1.21      crook    4637: 
1.67      anton    4638: These words are all defined for signed operands, but some of them also
                   4639: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
                   4640: @code{*}.
1.44      crook    4641: 
1.1       anton    4642: doc-+
1.21      crook    4643: doc-1+
1.128     anton    4644: doc-under+
1.1       anton    4645: doc--
1.21      crook    4646: doc-1-
1.1       anton    4647: doc-*
                   4648: doc-/
                   4649: doc-mod
                   4650: doc-/mod
                   4651: doc-negate
                   4652: doc-abs
                   4653: doc-min
                   4654: doc-max
1.27      crook    4655: doc-floored
1.1       anton    4656: 
1.44      crook    4657: 
1.67      anton    4658: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21      crook    4659: @subsection Double precision
                   4660: @cindex double precision arithmetic words
                   4661: 
1.49      anton    4662: For the rules used by the text interpreter for
                   4663: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4664: 
                   4665: A double precision number is represented by a cell pair, with the most
1.67      anton    4666: significant cell at the TOS. It is trivial to convert an unsigned single
                   4667: to a double: simply push a @code{0} onto the TOS. Since numbers are
                   4668: represented by Gforth using 2's complement arithmetic, converting a
                   4669: signed single to a (signed) double requires sign-extension across the
                   4670: most significant cell. This can be achieved using @code{s>d}. The moral
                   4671: of the story is that you cannot convert a number without knowing whether
                   4672: it represents an unsigned or a signed number.
1.21      crook    4673: 
1.67      anton    4674: These words are all defined for signed operands, but some of them also
                   4675: work for unsigned numbers: @code{d+}, @code{d-}.
1.44      crook    4676: 
1.21      crook    4677: doc-s>d
1.67      anton    4678: doc-d>s
1.21      crook    4679: doc-d+
                   4680: doc-d-
                   4681: doc-dnegate
                   4682: doc-dabs
                   4683: doc-dmin
                   4684: doc-dmax
                   4685: 
1.44      crook    4686: 
1.67      anton    4687: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
                   4688: @subsection Bitwise operations
                   4689: @cindex bitwise operation words
                   4690: 
                   4691: 
                   4692: doc-and
                   4693: doc-or
                   4694: doc-xor
                   4695: doc-invert
                   4696: doc-lshift
                   4697: doc-rshift
                   4698: doc-2*
                   4699: doc-d2*
                   4700: doc-2/
                   4701: doc-d2/
                   4702: 
                   4703: 
                   4704: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21      crook    4705: @subsection Numeric comparison
                   4706: @cindex numeric comparison words
                   4707: 
1.67      anton    4708: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
                   4709: d0= d0<>}) work for for both signed and unsigned numbers.
1.44      crook    4710: 
1.28      crook    4711: doc-<
                   4712: doc-<=
                   4713: doc-<>
                   4714: doc-=
                   4715: doc->
                   4716: doc->=
                   4717: 
1.21      crook    4718: doc-0<
1.23      crook    4719: doc-0<=
1.21      crook    4720: doc-0<>
                   4721: doc-0=
1.23      crook    4722: doc-0>
                   4723: doc-0>=
1.28      crook    4724: 
                   4725: doc-u<
                   4726: doc-u<=
1.44      crook    4727: @c u<> and u= exist but are the same as <> and =
1.31      anton    4728: @c doc-u<>
                   4729: @c doc-u=
1.28      crook    4730: doc-u>
                   4731: doc-u>=
                   4732: 
                   4733: doc-within
                   4734: 
                   4735: doc-d<
                   4736: doc-d<=
                   4737: doc-d<>
                   4738: doc-d=
                   4739: doc-d>
                   4740: doc-d>=
1.23      crook    4741: 
1.21      crook    4742: doc-d0<
1.23      crook    4743: doc-d0<=
                   4744: doc-d0<>
1.21      crook    4745: doc-d0=
1.23      crook    4746: doc-d0>
                   4747: doc-d0>=
                   4748: 
1.21      crook    4749: doc-du<
1.28      crook    4750: doc-du<=
1.44      crook    4751: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4752: @c doc-du<>
                   4753: @c doc-du=
1.28      crook    4754: doc-du>
                   4755: doc-du>=
1.1       anton    4756: 
1.44      crook    4757: 
1.21      crook    4758: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4759: @subsection Mixed precision
                   4760: @cindex mixed precision arithmetic words
                   4761: 
1.44      crook    4762: 
1.1       anton    4763: doc-m+
                   4764: doc-*/
                   4765: doc-*/mod
                   4766: doc-m*
                   4767: doc-um*
                   4768: doc-m*/
                   4769: doc-um/mod
                   4770: doc-fm/mod
                   4771: doc-sm/rem
                   4772: 
1.44      crook    4773: 
1.21      crook    4774: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4775: @subsection Floating Point
                   4776: @cindex floating point arithmetic words
                   4777: 
1.49      anton    4778: For the rules used by the text interpreter for
                   4779: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4780: 
1.67      anton    4781: Gforth has a separate floating point stack, but the documentation uses
                   4782: the unified notation.@footnote{It's easy to generate the separate
                   4783: notation from that by just separating the floating-point numbers out:
                   4784: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
                   4785: r3 )}.}
1.1       anton    4786: 
                   4787: @cindex floating-point arithmetic, pitfalls
                   4788: Floating point numbers have a number of unpleasant surprises for the
1.190     anton    4789: unwary (e.g., floating point addition is not associative) and even a
                   4790: few for the wary. You should not use them unless you know what you are
                   4791: doing or you don't care that the results you get are totally bogus. If
                   4792: you want to learn about the problems of floating point numbers (and
                   4793: how to avoid them), you might start with @cite{David Goldberg,
                   4794: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
                   4795: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
                   4796: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1       anton    4797: 
1.44      crook    4798: 
1.21      crook    4799: doc-d>f
                   4800: doc-f>d
1.1       anton    4801: doc-f+
                   4802: doc-f-
                   4803: doc-f*
                   4804: doc-f/
                   4805: doc-fnegate
                   4806: doc-fabs
                   4807: doc-fmax
                   4808: doc-fmin
                   4809: doc-floor
                   4810: doc-fround
                   4811: doc-f**
                   4812: doc-fsqrt
                   4813: doc-fexp
                   4814: doc-fexpm1
                   4815: doc-fln
                   4816: doc-flnp1
                   4817: doc-flog
                   4818: doc-falog
1.32      anton    4819: doc-f2*
                   4820: doc-f2/
                   4821: doc-1/f
                   4822: doc-precision
                   4823: doc-set-precision
                   4824: 
                   4825: @cindex angles in trigonometric operations
                   4826: @cindex trigonometric operations
                   4827: Angles in floating point operations are given in radians (a full circle
                   4828: has 2 pi radians).
                   4829: 
1.1       anton    4830: doc-fsin
                   4831: doc-fcos
                   4832: doc-fsincos
                   4833: doc-ftan
                   4834: doc-fasin
                   4835: doc-facos
                   4836: doc-fatan
                   4837: doc-fatan2
                   4838: doc-fsinh
                   4839: doc-fcosh
                   4840: doc-ftanh
                   4841: doc-fasinh
                   4842: doc-facosh
                   4843: doc-fatanh
1.21      crook    4844: doc-pi
1.28      crook    4845: 
1.32      anton    4846: @cindex equality of floats
                   4847: @cindex floating-point comparisons
1.31      anton    4848: One particular problem with floating-point arithmetic is that comparison
                   4849: for equality often fails when you would expect it to succeed.  For this
                   4850: reason approximate equality is often preferred (but you still have to
1.67      anton    4851: know what you are doing).  Also note that IEEE NaNs may compare
1.68      anton    4852: differently from what you might expect.  The comparison words are:
1.31      anton    4853: 
                   4854: doc-f~rel
                   4855: doc-f~abs
1.68      anton    4856: doc-f~
1.31      anton    4857: doc-f=
                   4858: doc-f<>
                   4859: 
                   4860: doc-f<
                   4861: doc-f<=
                   4862: doc-f>
                   4863: doc-f>=
                   4864: 
1.21      crook    4865: doc-f0<
1.28      crook    4866: doc-f0<=
                   4867: doc-f0<>
1.21      crook    4868: doc-f0=
1.28      crook    4869: doc-f0>
                   4870: doc-f0>=
                   4871: 
1.1       anton    4872: 
                   4873: @node Stack Manipulation, Memory, Arithmetic, Words
                   4874: @section Stack Manipulation
                   4875: @cindex stack manipulation words
                   4876: 
                   4877: @cindex floating-point stack in the standard
1.21      crook    4878: Gforth maintains a number of separate stacks:
                   4879: 
1.29      crook    4880: @cindex data stack
                   4881: @cindex parameter stack
1.21      crook    4882: @itemize @bullet
                   4883: @item
1.29      crook    4884: A data stack (also known as the @dfn{parameter stack}) -- for
                   4885: characters, cells, addresses, and double cells.
1.21      crook    4886: 
1.29      crook    4887: @cindex floating-point stack
1.21      crook    4888: @item
1.44      crook    4889: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4890: 
1.29      crook    4891: @cindex return stack
1.21      crook    4892: @item
1.44      crook    4893: A return stack -- for holding the return addresses of colon
1.32      anton    4894: definitions and other (non-FP) data.
1.21      crook    4895: 
1.29      crook    4896: @cindex locals stack
1.21      crook    4897: @item
1.44      crook    4898: A locals stack -- for holding local variables.
1.21      crook    4899: @end itemize
                   4900: 
1.1       anton    4901: @menu
                   4902: * Data stack::                  
                   4903: * Floating point stack::        
                   4904: * Return stack::                
                   4905: * Locals stack::                
                   4906: * Stack pointer manipulation::  
                   4907: @end menu
                   4908: 
                   4909: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4910: @subsection Data stack
                   4911: @cindex data stack manipulation words
                   4912: @cindex stack manipulations words, data stack
                   4913: 
1.44      crook    4914: 
1.1       anton    4915: doc-drop
                   4916: doc-nip
                   4917: doc-dup
                   4918: doc-over
                   4919: doc-tuck
                   4920: doc-swap
1.21      crook    4921: doc-pick
1.1       anton    4922: doc-rot
                   4923: doc--rot
                   4924: doc-?dup
                   4925: doc-roll
                   4926: doc-2drop
                   4927: doc-2nip
                   4928: doc-2dup
                   4929: doc-2over
                   4930: doc-2tuck
                   4931: doc-2swap
                   4932: doc-2rot
                   4933: 
1.44      crook    4934: 
1.1       anton    4935: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4936: @subsection Floating point stack
                   4937: @cindex floating-point stack manipulation words
                   4938: @cindex stack manipulation words, floating-point stack
                   4939: 
1.32      anton    4940: Whilst every sane Forth has a separate floating-point stack, it is not
                   4941: strictly required; an ANS Forth system could theoretically keep
                   4942: floating-point numbers on the data stack. As an additional difficulty,
                   4943: you don't know how many cells a floating-point number takes. It is
                   4944: reportedly possible to write words in a way that they work also for a
                   4945: unified stack model, but we do not recommend trying it. Instead, just
                   4946: say that your program has an environmental dependency on a separate
                   4947: floating-point stack.
                   4948: 
                   4949: doc-floating-stack
                   4950: 
1.1       anton    4951: doc-fdrop
                   4952: doc-fnip
                   4953: doc-fdup
                   4954: doc-fover
                   4955: doc-ftuck
                   4956: doc-fswap
1.21      crook    4957: doc-fpick
1.1       anton    4958: doc-frot
                   4959: 
1.44      crook    4960: 
1.1       anton    4961: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4962: @subsection Return stack
                   4963: @cindex return stack manipulation words
                   4964: @cindex stack manipulation words, return stack
                   4965: 
1.32      anton    4966: @cindex return stack and locals
                   4967: @cindex locals and return stack
                   4968: A Forth system is allowed to keep local variables on the
                   4969: return stack. This is reasonable, as local variables usually eliminate
                   4970: the need to use the return stack explicitly. So, if you want to produce
                   4971: a standard compliant program and you are using local variables in a
                   4972: word, forget about return stack manipulations in that word (refer to the
                   4973: standard document for the exact rules).
                   4974: 
1.1       anton    4975: doc->r
                   4976: doc-r>
                   4977: doc-r@
                   4978: doc-rdrop
                   4979: doc-2>r
                   4980: doc-2r>
                   4981: doc-2r@
                   4982: doc-2rdrop
                   4983: 
1.44      crook    4984: 
1.1       anton    4985: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4986: @subsection Locals stack
                   4987: 
1.78      anton    4988: Gforth uses an extra locals stack.  It is described, along with the
                   4989: reasons for its existence, in @ref{Locals implementation}.
1.21      crook    4990: 
1.1       anton    4991: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4992: @subsection Stack pointer manipulation
                   4993: @cindex stack pointer manipulation words
                   4994: 
1.44      crook    4995: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    4996: doc-sp0
1.1       anton    4997: doc-sp@
                   4998: doc-sp!
1.21      crook    4999: doc-fp0
1.1       anton    5000: doc-fp@
                   5001: doc-fp!
1.21      crook    5002: doc-rp0
1.1       anton    5003: doc-rp@
                   5004: doc-rp!
1.21      crook    5005: doc-lp0
1.1       anton    5006: doc-lp@
                   5007: doc-lp!
                   5008: 
1.44      crook    5009: 
1.1       anton    5010: @node Memory, Control Structures, Stack Manipulation, Words
                   5011: @section Memory
1.26      crook    5012: @cindex memory words
1.1       anton    5013: 
1.32      anton    5014: @menu
                   5015: * Memory model::                
                   5016: * Dictionary allocation::       
                   5017: * Heap Allocation::             
                   5018: * Memory Access::               
                   5019: * Address arithmetic::          
                   5020: * Memory Blocks::               
                   5021: @end menu
                   5022: 
1.67      anton    5023: In addition to the standard Forth memory allocation words, there is also
                   5024: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   5025: garbage collector}.
                   5026: 
1.32      anton    5027: @node Memory model, Dictionary allocation, Memory, Memory
                   5028: @subsection ANS Forth and Gforth memory models
                   5029: 
                   5030: @c The ANS Forth description is a mess (e.g., is the heap part of
                   5031: @c the dictionary?), so let's not stick to closely with it.
                   5032: 
1.67      anton    5033: ANS Forth considers a Forth system as consisting of several address
                   5034: spaces, of which only @dfn{data space} is managed and accessible with
                   5035: the memory words.  Memory not necessarily in data space includes the
                   5036: stacks, the code (called code space) and the headers (called name
                   5037: space). In Gforth everything is in data space, but the code for the
                   5038: primitives is usually read-only.
1.32      anton    5039: 
                   5040: Data space is divided into a number of areas: The (data space portion of
                   5041: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   5042: refer to the search data structure embodied in word lists and headers,
                   5043: because it is used for looking up names, just as you would in a
                   5044: conventional dictionary.}, the heap, and a number of system-allocated
                   5045: buffers.
                   5046: 
1.68      anton    5047: @cindex address arithmetic restrictions, ANS vs. Gforth
                   5048: @cindex contiguous regions, ANS vs. Gforth
1.32      anton    5049: In ANS Forth data space is also divided into contiguous regions.  You
                   5050: can only use address arithmetic within a contiguous region, not between
                   5051: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    5052: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    5053: allocation}).
                   5054: 
                   5055: Gforth provides one big address space, and address arithmetic can be
                   5056: performed between any addresses. However, in the dictionary headers or
                   5057: code are interleaved with data, so almost the only contiguous data space
                   5058: regions there are those described by ANS Forth as contiguous; but you
                   5059: can be sure that the dictionary is allocated towards increasing
                   5060: addresses even between contiguous regions.  The memory order of
                   5061: allocations in the heap is platform-dependent (and possibly different
                   5062: from one run to the next).
                   5063: 
1.27      crook    5064: 
1.32      anton    5065: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   5066: @subsection Dictionary allocation
1.27      crook    5067: @cindex reserving data space
                   5068: @cindex data space - reserving some
                   5069: 
1.32      anton    5070: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   5071: you want to deallocate X, you also deallocate everything
                   5072: allocated after X.
                   5073: 
1.68      anton    5074: @cindex contiguous regions in dictionary allocation
1.32      anton    5075: The allocations using the words below are contiguous and grow the region
                   5076: towards increasing addresses.  Other words that allocate dictionary
                   5077: memory of any kind (i.e., defining words including @code{:noname}) end
                   5078: the contiguous region and start a new one.
                   5079: 
                   5080: In ANS Forth only @code{create}d words are guaranteed to produce an
                   5081: address that is the start of the following contiguous region.  In
                   5082: particular, the cell allocated by @code{variable} is not guaranteed to
                   5083: be contiguous with following @code{allot}ed memory.
                   5084: 
                   5085: You can deallocate memory by using @code{allot} with a negative argument
                   5086: (with some restrictions, see @code{allot}). For larger deallocations use
                   5087: @code{marker}.
1.27      crook    5088: 
1.29      crook    5089: 
1.27      crook    5090: doc-here
                   5091: doc-unused
                   5092: doc-allot
                   5093: doc-c,
1.29      crook    5094: doc-f,
1.27      crook    5095: doc-,
                   5096: doc-2,
                   5097: 
1.32      anton    5098: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   5099: course you should allocate memory in an aligned way, too. I.e., before
                   5100: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   5101: The words below align @code{here} if it is not already.  Basically it is
                   5102: only already aligned for a type, if the last allocation was a multiple
                   5103: of the size of this type and if @code{here} was aligned for this type
                   5104: before.
                   5105: 
                   5106: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   5107: ANS Forth (@code{maxalign}ed in Gforth).
                   5108: 
                   5109: doc-align
                   5110: doc-falign
                   5111: doc-sfalign
                   5112: doc-dfalign
                   5113: doc-maxalign
                   5114: doc-cfalign
                   5115: 
                   5116: 
                   5117: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   5118: @subsection Heap allocation
                   5119: @cindex heap allocation
                   5120: @cindex dynamic allocation of memory
                   5121: @cindex memory-allocation word set
                   5122: 
1.68      anton    5123: @cindex contiguous regions and heap allocation
1.32      anton    5124: Heap allocation supports deallocation of allocated memory in any
                   5125: order. Dictionary allocation is not affected by it (i.e., it does not
                   5126: end a contiguous region). In Gforth, these words are implemented using
                   5127: the standard C library calls malloc(), free() and resize().
                   5128: 
1.68      anton    5129: The memory region produced by one invocation of @code{allocate} or
                   5130: @code{resize} is internally contiguous.  There is no contiguity between
                   5131: such a region and any other region (including others allocated from the
                   5132: heap).
                   5133: 
1.32      anton    5134: doc-allocate
                   5135: doc-free
                   5136: doc-resize
                   5137: 
1.27      crook    5138: 
1.32      anton    5139: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    5140: @subsection Memory Access
                   5141: @cindex memory access words
                   5142: 
                   5143: doc-@
                   5144: doc-!
                   5145: doc-+!
                   5146: doc-c@
                   5147: doc-c!
                   5148: doc-2@
                   5149: doc-2!
                   5150: doc-f@
                   5151: doc-f!
                   5152: doc-sf@
                   5153: doc-sf!
                   5154: doc-df@
                   5155: doc-df!
1.144     anton    5156: doc-sw@
                   5157: doc-uw@
                   5158: doc-w!
                   5159: doc-sl@
                   5160: doc-ul@
                   5161: doc-l!
1.68      anton    5162: 
1.32      anton    5163: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   5164: @subsection Address arithmetic
1.1       anton    5165: @cindex address arithmetic words
                   5166: 
1.67      anton    5167: Address arithmetic is the foundation on which you can build data
                   5168: structures like arrays, records (@pxref{Structures}) and objects
                   5169: (@pxref{Object-oriented Forth}).
1.32      anton    5170: 
1.68      anton    5171: @cindex address unit
                   5172: @cindex au (address unit)
1.1       anton    5173: ANS Forth does not specify the sizes of the data types. Instead, it
                   5174: offers a number of words for computing sizes and doing address
1.29      crook    5175: arithmetic. Address arithmetic is performed in terms of address units
                   5176: (aus); on most systems the address unit is one byte. Note that a
                   5177: character may have more than one au, so @code{chars} is no noop (on
1.68      anton    5178: platforms where it is a noop, it compiles to nothing).
1.1       anton    5179: 
1.67      anton    5180: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
                   5181: you have the address of a cell, perform @code{1 cells +}, and you will
                   5182: have the address of the next cell.
                   5183: 
1.68      anton    5184: @cindex contiguous regions and address arithmetic
1.67      anton    5185: In ANS Forth you can perform address arithmetic only within a contiguous
                   5186: region, i.e., if you have an address into one region, you can only add
                   5187: and subtract such that the result is still within the region; you can
                   5188: only subtract or compare addresses from within the same contiguous
                   5189: region.  Reasons: several contiguous regions can be arranged in memory
                   5190: in any way; on segmented systems addresses may have unusual
                   5191: representations, such that address arithmetic only works within a
                   5192: region.  Gforth provides a few more guarantees (linear address space,
                   5193: dictionary grows upwards), but in general I have found it easy to stay
                   5194: within contiguous regions (exception: computing and comparing to the
                   5195: address just beyond the end of an array).
                   5196: 
1.1       anton    5197: @cindex alignment of addresses for types
                   5198: ANS Forth also defines words for aligning addresses for specific
                   5199: types. Many computers require that accesses to specific data types
                   5200: must only occur at specific addresses; e.g., that cells may only be
                   5201: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5202: accesses, it can usually perform aligned accesses faster. 
                   5203: 
                   5204: For the performance-conscious: alignment operations are usually only
                   5205: necessary during the definition of a data structure, not during the
                   5206: (more frequent) accesses to it.
                   5207: 
                   5208: ANS Forth defines no words for character-aligning addresses. This is not
                   5209: an oversight, but reflects the fact that addresses that are not
                   5210: char-aligned have no use in the standard and therefore will not be
                   5211: created.
                   5212: 
                   5213: @cindex @code{CREATE} and alignment
1.29      crook    5214: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5215: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5216: are aligned for all purposes.
                   5217: 
1.26      crook    5218: Note that the ANS Forth word @code{char} has nothing to do with address
                   5219: arithmetic.
1.1       anton    5220: 
1.44      crook    5221: 
1.1       anton    5222: doc-chars
                   5223: doc-char+
                   5224: doc-cells
                   5225: doc-cell+
                   5226: doc-cell
                   5227: doc-aligned
                   5228: doc-floats
                   5229: doc-float+
                   5230: doc-float
                   5231: doc-faligned
                   5232: doc-sfloats
                   5233: doc-sfloat+
                   5234: doc-sfaligned
                   5235: doc-dfloats
                   5236: doc-dfloat+
                   5237: doc-dfaligned
                   5238: doc-maxaligned
                   5239: doc-cfaligned
                   5240: doc-address-unit-bits
1.145     anton    5241: doc-/w
                   5242: doc-/l
1.44      crook    5243: 
1.32      anton    5244: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5245: @subsection Memory Blocks
                   5246: @cindex memory block words
1.27      crook    5247: @cindex character strings - moving and copying
                   5248: 
1.49      anton    5249: Memory blocks often represent character strings; For ways of storing
                   5250: character strings in memory see @ref{String Formats}.  For other
                   5251: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5252: 
1.67      anton    5253: A few of these words work on address unit blocks.  In that case, you
                   5254: usually have to insert @code{CHARS} before the word when working on
                   5255: character strings.  Most words work on character blocks, and expect a
                   5256: char-aligned address.
                   5257: 
                   5258: When copying characters between overlapping memory regions, use
                   5259: @code{chars move} or choose carefully between @code{cmove} and
                   5260: @code{cmove>}.
1.44      crook    5261: 
1.1       anton    5262: doc-move
                   5263: doc-erase
                   5264: doc-cmove
                   5265: doc-cmove>
                   5266: doc-fill
                   5267: doc-blank
1.21      crook    5268: doc-compare
1.111     anton    5269: doc-str=
                   5270: doc-str<
                   5271: doc-string-prefix?
1.21      crook    5272: doc-search
1.27      crook    5273: doc--trailing
                   5274: doc-/string
1.82      anton    5275: doc-bounds
1.141     anton    5276: doc-pad
1.111     anton    5277: 
1.27      crook    5278: @comment TODO examples
                   5279: 
1.1       anton    5280: 
1.26      crook    5281: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5282: @section Control Structures
                   5283: @cindex control structures
                   5284: 
1.33      anton    5285: Control structures in Forth cannot be used interpretively, only in a
                   5286: colon definition@footnote{To be precise, they have no interpretation
                   5287: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5288: not like this limitation, but have not seen a satisfying way around it
                   5289: yet, although many schemes have been proposed.
1.1       anton    5290: 
                   5291: @menu
1.33      anton    5292: * Selection::                   IF ... ELSE ... ENDIF
                   5293: * Simple Loops::                BEGIN ...
1.29      crook    5294: * Counted Loops::               DO
1.67      anton    5295: * Arbitrary control structures::  
                   5296: * Calls and returns::           
1.1       anton    5297: * Exception Handling::          
                   5298: @end menu
                   5299: 
                   5300: @node Selection, Simple Loops, Control Structures, Control Structures
                   5301: @subsection Selection
                   5302: @cindex selection control structures
                   5303: @cindex control structures for selection
                   5304: 
                   5305: @cindex @code{IF} control structure
                   5306: @example
1.29      crook    5307: @i{flag}
1.1       anton    5308: IF
1.29      crook    5309:   @i{code}
1.1       anton    5310: ENDIF
                   5311: @end example
1.21      crook    5312: @noindent
1.33      anton    5313: 
1.44      crook    5314: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5315: with any bit set represents truth) @i{code} is executed.
1.33      anton    5316: 
1.1       anton    5317: @example
1.29      crook    5318: @i{flag}
1.1       anton    5319: IF
1.29      crook    5320:   @i{code1}
1.1       anton    5321: ELSE
1.29      crook    5322:   @i{code2}
1.1       anton    5323: ENDIF
                   5324: @end example
                   5325: 
1.44      crook    5326: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5327: executed.
1.33      anton    5328: 
1.1       anton    5329: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5330: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5331: recommend using @code{ENDIF}, because it is less confusing for people
                   5332: who also know other languages (and is not prone to reinforcing negative
                   5333: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5334: system that only supplies @code{THEN} is simple:
                   5335: @example
1.82      anton    5336: : ENDIF   POSTPONE then ; immediate
1.1       anton    5337: @end example
                   5338: 
                   5339: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5340: (adv.)}  has the following meanings:
                   5341: @quotation
                   5342: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5343: (if you were there, then you saw them).
                   5344: @end quotation
                   5345: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5346: and many other programming languages has the meaning 3d.]
                   5347: 
1.21      crook    5348: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5349: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5350: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5351: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5352: @file{compat/control.fs}.
                   5353: 
                   5354: @cindex @code{CASE} control structure
                   5355: @example
1.213     anton    5356: @i{x}
1.1       anton    5357: CASE
1.213     anton    5358:   @i{x1} OF @i{code1} ENDOF
                   5359:   @i{x2} OF @i{code2} ENDOF
1.1       anton    5360:   @dots{}
1.213     anton    5361:   ( x ) @i{default-code} ( x )
1.131     anton    5362: ENDCASE ( )
1.1       anton    5363: @end example
                   5364: 
1.213     anton    5365: Executes the first @i{codei}, where the @i{xi} is equal to @i{x}.  If no
                   5366: @i{xi} matches, the optional @i{default-code} is executed. The optional
1.211     anton    5367: default case can be added by simply writing the code after the last
1.213     anton    5368: @code{ENDOF}. It may use @i{x}, which is on top of the stack, but must
                   5369: not consume it.  The value @i{x} is consumed by this construction
1.211     anton    5370: (either by an @code{OF} that matches, or by the @code{ENDCASE}, if no OF
                   5371: matches).  Example:
                   5372: 
                   5373: @example
1.213     anton    5374: : num-name ( n -- c-addr u )
1.211     anton    5375:  case
1.213     anton    5376:    0 of s" zero " endof
                   5377:    1 of s" one "  endof
                   5378:    2 of s" two "  endof
                   5379:    \ default case:
                   5380:    s" other number" 
                   5381:    rot \ get n on top so ENDCASE can drop it
1.211     anton    5382:  endcase ;
                   5383: @end example
1.1       anton    5384: 
1.69      anton    5385: @progstyle
1.131     anton    5386: To keep the code understandable, you should ensure that you change the
                   5387: stack in the same way (wrt. number and types of stack items consumed
                   5388: and pushed) on all paths through a selection construct.
1.69      anton    5389: 
1.1       anton    5390: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5391: @subsection Simple Loops
                   5392: @cindex simple loops
                   5393: @cindex loops without count 
                   5394: 
                   5395: @cindex @code{WHILE} loop
                   5396: @example
                   5397: BEGIN
1.29      crook    5398:   @i{code1}
                   5399:   @i{flag}
1.1       anton    5400: WHILE
1.29      crook    5401:   @i{code2}
1.1       anton    5402: REPEAT
                   5403: @end example
                   5404: 
1.29      crook    5405: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5406: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5407: false, execution continues after the @code{REPEAT}.
                   5408: 
                   5409: @cindex @code{UNTIL} loop
                   5410: @example
                   5411: BEGIN
1.29      crook    5412:   @i{code}
                   5413:   @i{flag}
1.1       anton    5414: UNTIL
                   5415: @end example
                   5416: 
1.29      crook    5417: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5418: 
1.69      anton    5419: @progstyle
                   5420: To keep the code understandable, a complete iteration of the loop should
                   5421: not change the number and types of the items on the stacks.
                   5422: 
1.1       anton    5423: @cindex endless loop
                   5424: @cindex loops, endless
                   5425: @example
                   5426: BEGIN
1.29      crook    5427:   @i{code}
1.1       anton    5428: AGAIN
                   5429: @end example
                   5430: 
                   5431: This is an endless loop.
                   5432: 
                   5433: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5434: @subsection Counted Loops
                   5435: @cindex counted loops
                   5436: @cindex loops, counted
                   5437: @cindex @code{DO} loops
                   5438: 
                   5439: The basic counted loop is:
                   5440: @example
1.29      crook    5441: @i{limit} @i{start}
1.1       anton    5442: ?DO
1.29      crook    5443:   @i{body}
1.1       anton    5444: LOOP
                   5445: @end example
                   5446: 
1.29      crook    5447: This performs one iteration for every integer, starting from @i{start}
                   5448: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5449: accessed with @code{i}. For example, the loop:
1.1       anton    5450: @example
                   5451: 10 0 ?DO
                   5452:   i .
                   5453: LOOP
                   5454: @end example
1.21      crook    5455: @noindent
                   5456: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5457: 
1.1       anton    5458: The index of the innermost loop can be accessed with @code{i}, the index
                   5459: of the next loop with @code{j}, and the index of the third loop with
                   5460: @code{k}.
                   5461: 
1.44      crook    5462: 
1.1       anton    5463: doc-i
                   5464: doc-j
                   5465: doc-k
                   5466: 
1.44      crook    5467: 
1.1       anton    5468: The loop control data are kept on the return stack, so there are some
1.21      crook    5469: restrictions on mixing return stack accesses and counted loop words. In
                   5470: particuler, if you put values on the return stack outside the loop, you
                   5471: cannot read them inside the loop@footnote{well, not in a way that is
                   5472: portable.}. If you put values on the return stack within a loop, you
                   5473: have to remove them before the end of the loop and before accessing the
                   5474: index of the loop.
1.1       anton    5475: 
                   5476: There are several variations on the counted loop:
                   5477: 
1.21      crook    5478: @itemize @bullet
                   5479: @item
                   5480: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5481: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5482: 
                   5483: @example
                   5484: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5485: @end example
                   5486: prints @code{0 1 2 3}
                   5487: 
1.1       anton    5488: 
1.21      crook    5489: @item
                   5490: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5491: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5492: return stack so @code{EXIT} can get to its return address. For example:
                   5493: 
                   5494: @example
                   5495: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5496: @end example
                   5497: prints @code{0 1 2 3}
                   5498: 
                   5499: 
                   5500: @item
1.29      crook    5501: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5502: (and @code{LOOP} iterates until they become equal by wrap-around
                   5503: arithmetic). This behaviour is usually not what you want. Therefore,
                   5504: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5505: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5506: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5507: unsigned loop parameters.
                   5508: 
1.21      crook    5509: @item
                   5510: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5511: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5512: if you know that the loop is entered in any case. Such knowledge tends
                   5513: to become invalid during maintenance of a program, and then the
                   5514: @code{DO} will make trouble.
                   5515: 
                   5516: @item
1.29      crook    5517: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5518: index by @i{n} instead of by 1. The loop is terminated when the border
                   5519: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5520: 
1.21      crook    5521: @example
                   5522: 4 0 +DO  i .  2 +LOOP
                   5523: @end example
                   5524: @noindent
                   5525: prints @code{0 2}
                   5526: 
                   5527: @example
                   5528: 4 1 +DO  i .  2 +LOOP
                   5529: @end example
                   5530: @noindent
                   5531: prints @code{1 3}
1.1       anton    5532: 
1.68      anton    5533: @item
1.1       anton    5534: @cindex negative increment for counted loops
                   5535: @cindex counted loops with negative increment
1.29      crook    5536: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5537: 
1.21      crook    5538: @example
                   5539: -1 0 ?DO  i .  -1 +LOOP
                   5540: @end example
                   5541: @noindent
                   5542: prints @code{0 -1}
1.1       anton    5543: 
1.21      crook    5544: @example
                   5545: 0 0 ?DO  i .  -1 +LOOP
                   5546: @end example
                   5547: prints nothing.
1.1       anton    5548: 
1.29      crook    5549: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5550: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5551: index by @i{u} each iteration. The loop is terminated when the border
                   5552: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5553: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5554: 
1.21      crook    5555: @example
                   5556: -2 0 -DO  i .  1 -LOOP
                   5557: @end example
                   5558: @noindent
                   5559: prints @code{0 -1}
1.1       anton    5560: 
1.21      crook    5561: @example
                   5562: -1 0 -DO  i .  1 -LOOP
                   5563: @end example
                   5564: @noindent
                   5565: prints @code{0}
                   5566: 
                   5567: @example
                   5568: 0 0 -DO  i .  1 -LOOP
                   5569: @end example
                   5570: @noindent
                   5571: prints nothing.
1.1       anton    5572: 
1.21      crook    5573: @end itemize
1.1       anton    5574: 
                   5575: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5576: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5577: for these words that uses only standard words is provided in
                   5578: @file{compat/loops.fs}.
1.1       anton    5579: 
                   5580: 
                   5581: @cindex @code{FOR} loops
1.26      crook    5582: Another counted loop is:
1.1       anton    5583: @example
1.29      crook    5584: @i{n}
1.1       anton    5585: FOR
1.29      crook    5586:   @i{body}
1.1       anton    5587: NEXT
                   5588: @end example
                   5589: This is the preferred loop of native code compiler writers who are too
1.26      crook    5590: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5591: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5592: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5593: Forth systems may behave differently, even if they support @code{FOR}
                   5594: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5595: 
                   5596: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5597: @subsection Arbitrary control structures
                   5598: @cindex control structures, user-defined
                   5599: 
                   5600: @cindex control-flow stack
                   5601: ANS Forth permits and supports using control structures in a non-nested
                   5602: way. Information about incomplete control structures is stored on the
                   5603: control-flow stack. This stack may be implemented on the Forth data
                   5604: stack, and this is what we have done in Gforth.
                   5605: 
                   5606: @cindex @code{orig}, control-flow stack item
                   5607: @cindex @code{dest}, control-flow stack item
                   5608: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5609: entry represents a backward branch target. A few words are the basis for
                   5610: building any control structure possible (except control structures that
                   5611: need storage, like calls, coroutines, and backtracking).
                   5612: 
1.44      crook    5613: 
1.1       anton    5614: doc-if
                   5615: doc-ahead
                   5616: doc-then
                   5617: doc-begin
                   5618: doc-until
                   5619: doc-again
                   5620: doc-cs-pick
                   5621: doc-cs-roll
                   5622: 
1.44      crook    5623: 
1.21      crook    5624: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5625: manipulate the control-flow stack in a portable way. Without them, you
                   5626: would need to know how many stack items are occupied by a control-flow
                   5627: entry (many systems use one cell. In Gforth they currently take three,
                   5628: but this may change in the future).
                   5629: 
1.1       anton    5630: Some standard control structure words are built from these words:
                   5631: 
1.44      crook    5632: 
1.1       anton    5633: doc-else
                   5634: doc-while
                   5635: doc-repeat
                   5636: 
1.44      crook    5637: 
                   5638: @noindent
1.1       anton    5639: Gforth adds some more control-structure words:
                   5640: 
1.44      crook    5641: 
1.1       anton    5642: doc-endif
                   5643: doc-?dup-if
                   5644: doc-?dup-0=-if
                   5645: 
1.44      crook    5646: 
                   5647: @noindent
1.1       anton    5648: Counted loop words constitute a separate group of words:
                   5649: 
1.44      crook    5650: 
1.1       anton    5651: doc-?do
                   5652: doc-+do
                   5653: doc-u+do
                   5654: doc--do
                   5655: doc-u-do
                   5656: doc-do
                   5657: doc-for
                   5658: doc-loop
                   5659: doc-+loop
                   5660: doc--loop
                   5661: doc-next
                   5662: doc-leave
                   5663: doc-?leave
                   5664: doc-unloop
                   5665: doc-done
                   5666: 
1.44      crook    5667: 
1.21      crook    5668: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5669: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5670: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5671: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5672: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5673: resolved (by using one of the loop-ending words or @code{DONE}).
                   5674: 
1.44      crook    5675: @noindent
1.26      crook    5676: Another group of control structure words are:
1.1       anton    5677: 
1.44      crook    5678: 
1.1       anton    5679: doc-case
                   5680: doc-endcase
                   5681: doc-of
                   5682: doc-endof
                   5683: 
1.44      crook    5684: 
1.21      crook    5685: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5686: @code{CS-ROLL}.
1.1       anton    5687: 
                   5688: @subsubsection Programming Style
1.47      crook    5689: @cindex control structures programming style
                   5690: @cindex programming style, arbitrary control structures
1.1       anton    5691: 
                   5692: In order to ensure readability we recommend that you do not create
                   5693: arbitrary control structures directly, but define new control structure
                   5694: words for the control structure you want and use these words in your
1.26      crook    5695: program. For example, instead of writing:
1.1       anton    5696: 
                   5697: @example
1.26      crook    5698: BEGIN
1.1       anton    5699:   ...
1.26      crook    5700: IF [ 1 CS-ROLL ]
1.1       anton    5701:   ...
1.26      crook    5702: AGAIN THEN
1.1       anton    5703: @end example
                   5704: 
1.21      crook    5705: @noindent
1.1       anton    5706: we recommend defining control structure words, e.g.,
                   5707: 
                   5708: @example
1.26      crook    5709: : WHILE ( DEST -- ORIG DEST )
                   5710:  POSTPONE IF
                   5711:  1 CS-ROLL ; immediate
                   5712: 
                   5713: : REPEAT ( orig dest -- )
                   5714:  POSTPONE AGAIN
                   5715:  POSTPONE THEN ; immediate
1.1       anton    5716: @end example
                   5717: 
1.21      crook    5718: @noindent
1.1       anton    5719: and then using these to create the control structure:
                   5720: 
                   5721: @example
1.26      crook    5722: BEGIN
1.1       anton    5723:   ...
1.26      crook    5724: WHILE
1.1       anton    5725:   ...
1.26      crook    5726: REPEAT
1.1       anton    5727: @end example
                   5728: 
                   5729: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5730: @code{WHILE} are predefined, so in this example it would not be
                   5731: necessary to define them.
                   5732: 
                   5733: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5734: @subsection Calls and returns
                   5735: @cindex calling a definition
                   5736: @cindex returning from a definition
                   5737: 
1.3       anton    5738: @cindex recursive definitions
                   5739: A definition can be called simply be writing the name of the definition
1.26      crook    5740: to be called. Normally a definition is invisible during its own
1.3       anton    5741: definition. If you want to write a directly recursive definition, you
1.26      crook    5742: can use @code{recursive} to make the current definition visible, or
                   5743: @code{recurse} to call the current definition directly.
1.3       anton    5744: 
1.44      crook    5745: 
1.3       anton    5746: doc-recursive
                   5747: doc-recurse
                   5748: 
1.44      crook    5749: 
1.21      crook    5750: @comment TODO add example of the two recursion methods
1.12      anton    5751: @quotation
                   5752: @progstyle
                   5753: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5754: definition by name is more descriptive (if the name is well-chosen) than
                   5755: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5756: implementation, it is much better to read (and think) ``now sort the
                   5757: partitions'' than to read ``now do a recursive call''.
                   5758: @end quotation
1.3       anton    5759: 
1.29      crook    5760: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5761: 
                   5762: @example
1.28      crook    5763: Defer foo
1.3       anton    5764: 
                   5765: : bar ( ... -- ... )
                   5766:  ... foo ... ;
                   5767: 
                   5768: :noname ( ... -- ... )
                   5769:  ... bar ... ;
                   5770: IS foo
                   5771: @end example
                   5772: 
1.170     pazsan   5773: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33      anton    5774: 
1.26      crook    5775: The current definition returns control to the calling definition when
1.33      anton    5776: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5777: 
                   5778: doc-exit
                   5779: doc-;s
                   5780: 
1.44      crook    5781: 
1.1       anton    5782: @node Exception Handling,  , Calls and returns, Control Structures
                   5783: @subsection Exception Handling
1.26      crook    5784: @cindex exceptions
1.1       anton    5785: 
1.68      anton    5786: @c quit is a very bad idea for error handling, 
                   5787: @c because it does not translate into a THROW
                   5788: @c it also does not belong into this chapter
                   5789: 
                   5790: If a word detects an error condition that it cannot handle, it can
                   5791: @code{throw} an exception.  In the simplest case, this will terminate
                   5792: your program, and report an appropriate error.
1.21      crook    5793: 
1.68      anton    5794: doc-throw
1.1       anton    5795: 
1.69      anton    5796: @code{Throw} consumes a cell-sized error number on the stack. There are
                   5797: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
                   5798: Gforth (and most other systems) you can use the iors produced by various
                   5799: words as error numbers (e.g., a typical use of @code{allocate} is
                   5800: @code{allocate throw}).  Gforth also provides the word @code{exception}
                   5801: to define your own error numbers (with decent error reporting); an ANS
                   5802: Forth version of this word (but without the error messages) is available
                   5803: in @code{compat/except.fs}.  And finally, you can use your own error
1.68      anton    5804: numbers (anything outside the range -4095..0), but won't get nice error
                   5805: messages, only numbers.  For example, try:
                   5806: 
                   5807: @example
1.69      anton    5808: -10 throw                    \ ANS defined
                   5809: -267 throw                   \ system defined
                   5810: s" my error" exception throw \ user defined
                   5811: 7 throw                      \ arbitrary number
1.68      anton    5812: @end example
                   5813: 
                   5814: doc---exception-exception
1.1       anton    5815: 
1.69      anton    5816: A common idiom to @code{THROW} a specific error if a flag is true is
                   5817: this:
                   5818: 
                   5819: @example
                   5820: @code{( flag ) 0<> @i{errno} and throw}
                   5821: @end example
                   5822: 
                   5823: Your program can provide exception handlers to catch exceptions.  An
                   5824: exception handler can be used to correct the problem, or to clean up
                   5825: some data structures and just throw the exception to the next exception
                   5826: handler.  Note that @code{throw} jumps to the dynamically innermost
                   5827: exception handler.  The system's exception handler is outermost, and just
                   5828: prints an error and restarts command-line interpretation (or, in batch
                   5829: mode (i.e., while processing the shell command line), leaves Gforth).
1.1       anton    5830: 
1.68      anton    5831: The ANS Forth way to catch exceptions is @code{catch}:
1.1       anton    5832: 
1.68      anton    5833: doc-catch
1.160     anton    5834: doc-nothrow
1.68      anton    5835: 
                   5836: The most common use of exception handlers is to clean up the state when
                   5837: an error happens.  E.g.,
1.1       anton    5838: 
1.26      crook    5839: @example
1.68      anton    5840: base @ >r hex \ actually the hex should be inside foo, or we h
                   5841: ['] foo catch ( nerror|0 )
                   5842: r> base !
1.69      anton    5843: ( nerror|0 ) throw \ pass it on
1.26      crook    5844: @end example
1.1       anton    5845: 
1.69      anton    5846: A use of @code{catch} for handling the error @code{myerror} might look
                   5847: like this:
1.44      crook    5848: 
1.68      anton    5849: @example
1.69      anton    5850: ['] foo catch
                   5851: CASE
1.160     anton    5852:   myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5853:   dup throw \ default: pass other errors on, do nothing on non-errors
                   5854: ENDCASE
1.68      anton    5855: @end example
1.44      crook    5856: 
1.68      anton    5857: Having to wrap the code into a separate word is often cumbersome,
                   5858: therefore Gforth provides an alternative syntax:
1.1       anton    5859: 
                   5860: @example
1.69      anton    5861: TRY
1.68      anton    5862:   @i{code1}
1.172     anton    5863:   IFERROR
                   5864:     @i{code2}
                   5865:   THEN
                   5866:   @i{code3}
1.69      anton    5867: ENDTRY
1.1       anton    5868: @end example
                   5869: 
1.172     anton    5870: This performs @i{code1}.  If @i{code1} completes normally, execution
1.201     anton    5871: continues with @i{code3}.  If there is an exception in @i{code1} or
                   5872: before @code{endtry}, the stacks are reset to the depth during
1.172     anton    5873: @code{try}, the throw value is pushed on the data stack, and execution
1.201     anton    5874: constinues at @i{code2}, and finally falls through to @i{code3}.
1.26      crook    5875: 
1.68      anton    5876: doc-try
                   5877: doc-endtry
1.172     anton    5878: doc-iferror
                   5879: 
                   5880: If you don't need @i{code2}, you can write @code{restore} instead of
                   5881: @code{iferror then}:
                   5882: 
                   5883: @example
                   5884: TRY
                   5885:   @i{code1}
                   5886: RESTORE
                   5887:   @i{code3}
                   5888: ENDTRY
                   5889: @end example
1.26      crook    5890: 
1.172     anton    5891: @cindex unwind-protect
1.69      anton    5892: The cleanup example from above in this syntax:
1.26      crook    5893: 
1.68      anton    5894: @example
1.174     anton    5895: base @@ @{ oldbase @}
1.172     anton    5896: TRY
1.68      anton    5897:   hex foo \ now the hex is placed correctly
1.69      anton    5898:   0       \ value for throw
1.172     anton    5899: RESTORE
                   5900:   oldbase base !
                   5901: ENDTRY
                   5902: throw
1.1       anton    5903: @end example
                   5904: 
1.172     anton    5905: An additional advantage of this variant is that an exception between
                   5906: @code{restore} and @code{endtry} (e.g., from the user pressing
                   5907: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
                   5908: so the base will be restored under all circumstances.
                   5909: 
                   5910: However, you have to ensure that this code does not cause an exception
                   5911: itself, otherwise the @code{iferror}/@code{restore} code will loop.
                   5912: Moreover, you should also make sure that the stack contents needed by
                   5913: the @code{iferror}/@code{restore} code exist everywhere between
                   5914: @code{try} and @code{endtry}; in our example this is achived by
                   5915: putting the data in a local before the @code{try} (you cannot use the
                   5916: return stack because the exception frame (@i{sys1}) is in the way
                   5917: there).
                   5918: 
                   5919: This kind of usage corresponds to Lisp's @code{unwind-protect}.
                   5920: 
                   5921: @cindex @code{recover} (old Gforth versions)
                   5922: If you do not want this exception-restarting behaviour, you achieve
                   5923: this as follows:
                   5924: 
                   5925: @example
                   5926: TRY
                   5927:   @i{code1}
                   5928: ENDTRY-IFERROR
                   5929:   @i{code2}
                   5930: THEN
                   5931: @end example
                   5932: 
                   5933: If there is an exception in @i{code1}, then @i{code2} is executed,
                   5934: otherwise execution continues behind the @code{then} (or in a possible
                   5935: @code{else} branch).  This corresponds to the construct
                   5936: 
                   5937: @example
                   5938: TRY
                   5939:   @i{code1}
                   5940: RECOVER
                   5941:   @i{code2}
                   5942: ENDTRY
                   5943: @end example
                   5944: 
                   5945: in Gforth before version 0.7.  So you can directly replace
                   5946: @code{recover}-using code; however, we recommend that you check if it
                   5947: would not be better to use one of the other @code{try} variants while
                   5948: you are at it.
                   5949: 
1.173     anton    5950: To ease the transition, Gforth provides two compatibility files:
                   5951: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
                   5952: ... then} syntax (but not @code{iferror} or @code{restore}) for old
                   5953: systems; @file{recover-endtry.fs} provides the @code{try ... recover
                   5954: ... endtry} syntax on new systems, so you can use that file as a
                   5955: stopgap to run old programs.  Both files work on any system (they just
                   5956: do nothing if the system already has the syntax it implements), so you
                   5957: can unconditionally @code{require} one of these files, even if you use
                   5958: a mix old and new systems.
                   5959: 
1.172     anton    5960: doc-restore
                   5961: doc-endtry-iferror
                   5962: 
                   5963: Here's the error handling example:
1.1       anton    5964: 
1.68      anton    5965: @example
1.69      anton    5966: TRY
1.68      anton    5967:   foo
1.172     anton    5968: ENDTRY-IFERROR
1.69      anton    5969:   CASE
1.160     anton    5970:     myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5971:     throw \ pass other errors on
                   5972:   ENDCASE
1.172     anton    5973: THEN
1.68      anton    5974: @end example
1.1       anton    5975: 
1.69      anton    5976: @progstyle
                   5977: As usual, you should ensure that the stack depth is statically known at
                   5978: the end: either after the @code{throw} for passing on errors, or after
                   5979: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
                   5980: selection construct for handling the error).
                   5981: 
1.68      anton    5982: There are two alternatives to @code{throw}: @code{Abort"} is conditional
                   5983: and you can provide an error message.  @code{Abort} just produces an
                   5984: ``Aborted'' error.
1.1       anton    5985: 
1.68      anton    5986: The problem with these words is that exception handlers cannot
                   5987: differentiate between different @code{abort"}s; they just look like
                   5988: @code{-2 throw} to them (the error message cannot be accessed by
                   5989: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
                   5990: exception handlers.
1.44      crook    5991: 
1.68      anton    5992: doc-abort"
1.26      crook    5993: doc-abort
1.29      crook    5994: 
                   5995: 
1.44      crook    5996: 
1.29      crook    5997: @c -------------------------------------------------------------
1.47      crook    5998: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    5999: @section Defining Words
                   6000: @cindex defining words
                   6001: 
1.47      crook    6002: Defining words are used to extend Forth by creating new entries in the dictionary.
                   6003: 
1.29      crook    6004: @menu
1.67      anton    6005: * CREATE::                      
1.44      crook    6006: * Variables::                   Variables and user variables
1.67      anton    6007: * Constants::                   
1.44      crook    6008: * Values::                      Initialised variables
1.67      anton    6009: * Colon Definitions::           
1.44      crook    6010: * Anonymous Definitions::       Definitions without names
1.69      anton    6011: * Supplying names::             Passing definition names as strings
1.67      anton    6012: * User-defined Defining Words::  
1.170     pazsan   6013: * Deferred Words::              Allow forward references
1.67      anton    6014: * Aliases::                     
1.29      crook    6015: @end menu
                   6016: 
1.44      crook    6017: @node CREATE, Variables, Defining Words, Defining Words
                   6018: @subsection @code{CREATE}
1.29      crook    6019: @cindex simple defining words
                   6020: @cindex defining words, simple
                   6021: 
                   6022: Defining words are used to create new entries in the dictionary. The
                   6023: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   6024: this:
                   6025: 
                   6026: @example
                   6027: CREATE new-word1
                   6028: @end example
                   6029: 
1.69      anton    6030: @code{CREATE} is a parsing word, i.e., it takes an argument from the
                   6031: input stream (@code{new-word1} in our example).  It generates a
                   6032: dictionary entry for @code{new-word1}. When @code{new-word1} is
                   6033: executed, all that it does is leave an address on the stack. The address
                   6034: represents the value of the data space pointer (@code{HERE}) at the time
                   6035: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
                   6036: associating a name with the address of a region of memory.
1.29      crook    6037: 
1.34      anton    6038: doc-create
                   6039: 
1.69      anton    6040: Note that in ANS Forth guarantees only for @code{create} that its body
                   6041: is in dictionary data space (i.e., where @code{here}, @code{allot}
                   6042: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
                   6043: @code{create}d words can be modified with @code{does>}
                   6044: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
                   6045: can only be applied to @code{create}d words.
                   6046: 
1.29      crook    6047: By extending this example to reserve some memory in data space, we end
1.69      anton    6048: up with something like a @i{variable}. Here are two different ways to do
                   6049: it:
1.29      crook    6050: 
                   6051: @example
                   6052: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   6053: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   6054: @end example
                   6055: 
                   6056: The variable can be examined and modified using @code{@@} (``fetch'') and
                   6057: @code{!} (``store'') like this:
                   6058: 
                   6059: @example
                   6060: new-word2 @@ .      \ get address, fetch from it and display
                   6061: 1234 new-word2 !   \ new value, get address, store to it
                   6062: @end example
                   6063: 
1.44      crook    6064: @cindex arrays
                   6065: A similar mechanism can be used to create arrays. For example, an
                   6066: 80-character text input buffer:
1.29      crook    6067: 
                   6068: @example
1.44      crook    6069: CREATE text-buf 80 chars allot
                   6070: 
1.168     anton    6071: text-buf 0 chars + c@@ \ the 1st character (offset 0)
                   6072: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44      crook    6073: @end example
1.29      crook    6074: 
1.44      crook    6075: You can build arbitrarily complex data structures by allocating
1.49      anton    6076: appropriate areas of memory. For further discussions of this, and to
1.66      anton    6077: learn about some Gforth tools that make it easier,
1.49      anton    6078: @xref{Structures}.
1.44      crook    6079: 
                   6080: 
                   6081: @node Variables, Constants, CREATE, Defining Words
                   6082: @subsection Variables
                   6083: @cindex variables
                   6084: 
                   6085: The previous section showed how a sequence of commands could be used to
                   6086: generate a variable.  As a final refinement, the whole code sequence can
                   6087: be wrapped up in a defining word (pre-empting the subject of the next
                   6088: section), making it easier to create new variables:
                   6089: 
                   6090: @example
                   6091: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   6092: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   6093: 
                   6094: myvariableX foo \ variable foo starts off with an unknown value
                   6095: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    6096: 
                   6097: 45 3 * foo !   \ set foo to 135
                   6098: 1234 joe !     \ set joe to 1234
                   6099: 3 joe +!       \ increment joe by 3.. to 1237
                   6100: @end example
                   6101: 
                   6102: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    6103: Forth already has a definition @code{Variable}. ANS Forth does not
1.69      anton    6104: guarantee that a @code{Variable} is initialised when it is created
                   6105: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
                   6106: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
                   6107: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    6108: @code{fvariable} for double and floating-point variables, respectively
1.69      anton    6109: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47      crook    6110: store a boolean, you can use @code{on} and @code{off} to toggle its
                   6111: state.
1.29      crook    6112: 
1.34      anton    6113: doc-variable
                   6114: doc-2variable
                   6115: doc-fvariable
                   6116: 
1.29      crook    6117: @cindex user variables
                   6118: @cindex user space
                   6119: The defining word @code{User} behaves in the same way as @code{Variable}.
                   6120: The difference is that it reserves space in @i{user (data) space} rather
                   6121: than normal data space. In a Forth system that has a multi-tasker, each
                   6122: task has its own set of user variables.
                   6123: 
1.34      anton    6124: doc-user
1.67      anton    6125: @c doc-udp
                   6126: @c doc-uallot
1.34      anton    6127: 
1.29      crook    6128: @comment TODO is that stuff about user variables strictly correct? Is it
                   6129: @comment just terminal tasks that have user variables?
                   6130: @comment should document tasker.fs (with some examples) elsewhere
                   6131: @comment in this manual, then expand on user space and user variables.
                   6132: 
1.44      crook    6133: @node Constants, Values, Variables, Defining Words
                   6134: @subsection Constants
                   6135: @cindex constants
                   6136: 
                   6137: @code{Constant} allows you to declare a fixed value and refer to it by
                   6138: name. For example:
1.29      crook    6139: 
                   6140: @example
                   6141: 12 Constant INCHES-PER-FOOT
                   6142: 3E+08 fconstant SPEED-O-LIGHT
                   6143: @end example
                   6144: 
                   6145: A @code{Variable} can be both read and written, so its run-time
                   6146: behaviour is to supply an address through which its current value can be
                   6147: manipulated. In contrast, the value of a @code{Constant} cannot be
                   6148: changed once it has been declared@footnote{Well, often it can be -- but
                   6149: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   6150: on).} so it's not necessary to supply the address -- it is more
                   6151: efficient to return the value of the constant directly. That's exactly
                   6152: what happens; the run-time effect of a constant is to put its value on
1.49      anton    6153: the top of the stack (You can find one
                   6154: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    6155: 
1.69      anton    6156: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29      crook    6157: double and floating-point constants, respectively.
                   6158: 
1.34      anton    6159: doc-constant
                   6160: doc-2constant
                   6161: doc-fconstant
                   6162: 
                   6163: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    6164: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   6165: @c constant, use it and then delete the definition of the constant..
1.69      anton    6166: 
                   6167: @c anton->An ANS Forth system can compile a constant to a literal; On
                   6168: @c decompilation you would see only the number, just as if it had been used
                   6169: @c in the first place.  The word will stay, of course, but it will only be
                   6170: @c used by the text interpreter (no run-time duties, except when it is 
                   6171: @c POSTPONEd or somesuch).
                   6172: 
                   6173: @c nac:
1.44      crook    6174: @c I agree that it's rather deep, but IMO it is an important difference
                   6175: @c relative to other programming languages.. often it's annoying: it
                   6176: @c certainly changes my programming style relative to C.
                   6177: 
1.69      anton    6178: @c anton: In what way?
                   6179: 
1.29      crook    6180: Constants in Forth behave differently from their equivalents in other
                   6181: programming languages. In other languages, a constant (such as an EQU in
                   6182: assembler or a #define in C) only exists at compile-time; in the
                   6183: executable program the constant has been translated into an absolute
                   6184: number and, unless you are using a symbolic debugger, it's impossible to
                   6185: know what abstract thing that number represents. In Forth a constant has
1.44      crook    6186: an entry in the header space and remains there after the code that uses
                   6187: it has been defined. In fact, it must remain in the dictionary since it
                   6188: has run-time duties to perform. For example:
1.29      crook    6189: 
                   6190: @example
                   6191: 12 Constant INCHES-PER-FOOT
                   6192: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   6193: @end example
                   6194: 
                   6195: @cindex in-lining of constants
                   6196: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   6197: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   6198: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   6199: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   6200: attempt to optimise constants by in-lining them where they are used. You
                   6201: can force Gforth to in-line a constant like this:
                   6202: 
                   6203: @example
                   6204: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   6205: @end example
                   6206: 
                   6207: If you use @code{see} to decompile @i{this} version of
                   6208: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    6209: longer present. To understand how this works, read
                   6210: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    6211: 
                   6212: In-lining constants in this way might improve execution time
                   6213: fractionally, and can ensure that a constant is now only referenced at
                   6214: compile-time. However, the definition of the constant still remains in
                   6215: the dictionary. Some Forth compilers provide a mechanism for controlling
                   6216: a second dictionary for holding transient words such that this second
                   6217: dictionary can be deleted later in order to recover memory
                   6218: space. However, there is no standard way of doing this.
                   6219: 
                   6220: 
1.44      crook    6221: @node Values, Colon Definitions, Constants, Defining Words
                   6222: @subsection Values
                   6223: @cindex values
1.34      anton    6224: 
1.69      anton    6225: A @code{Value} behaves like a @code{Constant}, but it can be changed.
                   6226: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
                   6227: (not in ANS Forth) you can access (and change) a @code{value} also with
                   6228: @code{>body}.
                   6229: 
                   6230: Here are some
                   6231: examples:
1.29      crook    6232: 
                   6233: @example
1.69      anton    6234: 12 Value APPLES     \ Define APPLES with an initial value of 12
                   6235: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
                   6236: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
                   6237: APPLES              \ puts 35 on the top of the stack.
1.29      crook    6238: @end example
                   6239: 
1.44      crook    6240: doc-value
                   6241: doc-to
1.29      crook    6242: 
1.35      anton    6243: 
1.69      anton    6244: 
1.44      crook    6245: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   6246: @subsection Colon Definitions
                   6247: @cindex colon definitions
1.35      anton    6248: 
                   6249: @example
1.44      crook    6250: : name ( ... -- ... )
                   6251:     word1 word2 word3 ;
1.29      crook    6252: @end example
                   6253: 
1.44      crook    6254: @noindent
                   6255: Creates a word called @code{name} that, upon execution, executes
                   6256: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    6257: 
1.49      anton    6258: The explanation above is somewhat superficial. For simple examples of
                   6259: colon definitions see @ref{Your first definition}.  For an in-depth
1.66      anton    6260: discussion of some of the issues involved, @xref{Interpretation and
1.49      anton    6261: Compilation Semantics}.
1.29      crook    6262: 
1.44      crook    6263: doc-:
                   6264: doc-;
1.1       anton    6265: 
1.34      anton    6266: 
1.69      anton    6267: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44      crook    6268: @subsection Anonymous Definitions
                   6269: @cindex colon definitions
                   6270: @cindex defining words without name
1.34      anton    6271: 
1.44      crook    6272: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   6273: name. You can do this with:
1.1       anton    6274: 
1.44      crook    6275: doc-:noname
1.1       anton    6276: 
1.44      crook    6277: This leaves the execution token for the word on the stack after the
                   6278: closing @code{;}. Here's an example in which a deferred word is
                   6279: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6280: 
1.29      crook    6281: @example
1.44      crook    6282: Defer deferred
                   6283: :noname ( ... -- ... )
                   6284:   ... ;
                   6285: IS deferred
1.29      crook    6286: @end example
1.26      crook    6287: 
1.44      crook    6288: @noindent
                   6289: Gforth provides an alternative way of doing this, using two separate
                   6290: words:
1.27      crook    6291: 
1.44      crook    6292: doc-noname
                   6293: @cindex execution token of last defined word
1.116     anton    6294: doc-latestxt
1.1       anton    6295: 
1.44      crook    6296: @noindent
                   6297: The previous example can be rewritten using @code{noname} and
1.116     anton    6298: @code{latestxt}:
1.1       anton    6299: 
1.26      crook    6300: @example
1.44      crook    6301: Defer deferred
                   6302: noname : ( ... -- ... )
                   6303:   ... ;
1.116     anton    6304: latestxt IS deferred
1.26      crook    6305: @end example
1.1       anton    6306: 
1.29      crook    6307: @noindent
1.44      crook    6308: @code{noname} works with any defining word, not just @code{:}.
                   6309: 
1.116     anton    6310: @code{latestxt} also works when the last word was not defined as
1.71      anton    6311: @code{noname}.  It does not work for combined words, though.  It also has
                   6312: the useful property that is is valid as soon as the header for a
                   6313: definition has been built. Thus:
1.44      crook    6314: 
                   6315: @example
1.116     anton    6316: latestxt . : foo [ latestxt . ] ; ' foo .
1.44      crook    6317: @end example
1.1       anton    6318: 
1.44      crook    6319: @noindent
                   6320: prints 3 numbers; the last two are the same.
1.26      crook    6321: 
1.69      anton    6322: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
                   6323: @subsection Supplying the name of a defined word
                   6324: @cindex names for defined words
                   6325: @cindex defining words, name given in a string
                   6326: 
                   6327: By default, a defining word takes the name for the defined word from the
                   6328: input stream. Sometimes you want to supply the name from a string. You
                   6329: can do this with:
                   6330: 
                   6331: doc-nextname
                   6332: 
                   6333: For example:
                   6334: 
                   6335: @example
                   6336: s" foo" nextname create
                   6337: @end example
                   6338: 
                   6339: @noindent
                   6340: is equivalent to:
                   6341: 
                   6342: @example
                   6343: create foo
                   6344: @end example
                   6345: 
                   6346: @noindent
                   6347: @code{nextname} works with any defining word.
                   6348: 
1.1       anton    6349: 
1.170     pazsan   6350: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26      crook    6351: @subsection User-defined Defining Words
                   6352: @cindex user-defined defining words
                   6353: @cindex defining words, user-defined
1.1       anton    6354: 
1.29      crook    6355: You can create a new defining word by wrapping defining-time code around
                   6356: an existing defining word and putting the sequence in a colon
1.69      anton    6357: definition. 
                   6358: 
                   6359: @c anton: This example is very complex and leads in a quite different
                   6360: @c direction from the CREATE-DOES> stuff that follows.  It should probably
                   6361: @c be done elsewhere, or as a subsubsection of this subsection (or as a
                   6362: @c subsection of Defining Words)
                   6363: 
                   6364: For example, suppose that you have a word @code{stats} that
1.29      crook    6365: gathers statistics about colon definitions given the @i{xt} of the
                   6366: definition, and you want every colon definition in your application to
                   6367: make a call to @code{stats}. You can define and use a new version of
                   6368: @code{:} like this:
                   6369: 
                   6370: @example
                   6371: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6372:   ... ;  \ other code
                   6373: 
1.116     anton    6374: : my: : latestxt postpone literal ['] stats compile, ;
1.29      crook    6375: 
                   6376: my: foo + - ;
                   6377: @end example
                   6378: 
                   6379: When @code{foo} is defined using @code{my:} these steps occur:
                   6380: 
                   6381: @itemize @bullet
                   6382: @item
                   6383: @code{my:} is executed.
                   6384: @item
                   6385: The @code{:} within the definition (the one between @code{my:} and
1.116     anton    6386: @code{latestxt}) is executed, and does just what it always does; it parses
1.29      crook    6387: the input stream for a name, builds a dictionary header for the name
                   6388: @code{foo} and switches @code{state} from interpret to compile.
                   6389: @item
1.116     anton    6390: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29      crook    6391: being defined -- @code{foo} -- onto the stack.
                   6392: @item
                   6393: The code that was produced by @code{postpone literal} is executed; this
                   6394: causes the value on the stack to be compiled as a literal in the code
                   6395: area of @code{foo}.
                   6396: @item
                   6397: The code @code{['] stats} compiles a literal into the definition of
                   6398: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6399: execution token for @code{stats} -- is layed down in the code area of
                   6400: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6401: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6402: in the code area is implementation-dependent. A threaded implementation
                   6403: might spit out the execution token directly whilst another
                   6404: implementation might spit out a native code sequence.}.
                   6405: @item
                   6406: At this point, the execution of @code{my:} is complete, and control
                   6407: returns to the text interpreter. The text interpreter is in compile
                   6408: state, so subsequent text @code{+ -} is compiled into the definition of
                   6409: @code{foo} and the @code{;} terminates the definition as always.
                   6410: @end itemize
                   6411: 
                   6412: You can use @code{see} to decompile a word that was defined using
                   6413: @code{my:} and see how it is different from a normal @code{:}
                   6414: definition. For example:
                   6415: 
                   6416: @example
                   6417: : bar + - ;  \ like foo but using : rather than my:
                   6418: see bar
                   6419: : bar
                   6420:   + - ;
                   6421: see foo
                   6422: : foo
                   6423:   107645672 stats + - ;
                   6424: 
1.140     anton    6425: \ use ' foo . to show that 107645672 is the xt for foo
1.29      crook    6426: @end example
                   6427: 
                   6428: You can use techniques like this to make new defining words in terms of
                   6429: @i{any} existing defining word.
1.1       anton    6430: 
                   6431: 
1.29      crook    6432: @cindex defining defining words
1.26      crook    6433: @cindex @code{CREATE} ... @code{DOES>}
                   6434: If you want the words defined with your defining words to behave
                   6435: differently from words defined with standard defining words, you can
                   6436: write your defining word like this:
1.1       anton    6437: 
                   6438: @example
1.26      crook    6439: : def-word ( "name" -- )
1.29      crook    6440:     CREATE @i{code1}
1.26      crook    6441: DOES> ( ... -- ... )
1.29      crook    6442:     @i{code2} ;
1.26      crook    6443: 
                   6444: def-word name
1.1       anton    6445: @end example
                   6446: 
1.29      crook    6447: @cindex child words
                   6448: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6449: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6450: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6451: is not executed at this time. The word @code{name} is sometimes called a
                   6452: @dfn{child} of @code{def-word}.
                   6453: 
                   6454: When you execute @code{name}, the address of the body of @code{name} is
                   6455: put on the data stack and @i{code2} is executed (the address of the body
                   6456: of @code{name} is the address @code{HERE} returns immediately after the
1.69      anton    6457: @code{CREATE}, i.e., the address a @code{create}d word returns by
                   6458: default).
                   6459: 
                   6460: @c anton:
                   6461: @c www.dictionary.com says:
                   6462: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
                   6463: @c several generations of absence, usually caused by the chance
                   6464: @c recombination of genes.  2.An individual or a part that exhibits
                   6465: @c atavism. Also called throwback.  3.The return of a trait or recurrence
                   6466: @c of previous behavior after a period of absence.
                   6467: @c
                   6468: @c Doesn't seem to fit.
1.29      crook    6469: 
1.69      anton    6470: @c @cindex atavism in child words
1.33      anton    6471: You can use @code{def-word} to define a set of child words that behave
1.69      anton    6472: similarly; they all have a common run-time behaviour determined by
                   6473: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
                   6474: body of the child word. The structure of the data is common to all
                   6475: children of @code{def-word}, but the data values are specific -- and
                   6476: private -- to each child word. When a child word is executed, the
                   6477: address of its private data area is passed as a parameter on TOS to be
                   6478: used and manipulated@footnote{It is legitimate both to read and write to
                   6479: this data area.} by @i{code2}.
1.29      crook    6480: 
                   6481: The two fragments of code that make up the defining words act (are
                   6482: executed) at two completely separate times:
1.1       anton    6483: 
1.29      crook    6484: @itemize @bullet
                   6485: @item
                   6486: At @i{define time}, the defining word executes @i{code1} to generate a
                   6487: child word
                   6488: @item
                   6489: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6490: is executed, using parameters (data) that are private and specific to
                   6491: the child word.
                   6492: @end itemize
                   6493: 
1.44      crook    6494: Another way of understanding the behaviour of @code{def-word} and
                   6495: @code{name} is to say that, if you make the following definitions:
1.33      anton    6496: @example
                   6497: : def-word1 ( "name" -- )
                   6498:     CREATE @i{code1} ;
                   6499: 
                   6500: : action1 ( ... -- ... )
                   6501:     @i{code2} ;
                   6502: 
                   6503: def-word1 name1
                   6504: @end example
                   6505: 
1.44      crook    6506: @noindent
                   6507: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6508: 
1.29      crook    6509: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6510: 
1.1       anton    6511: @example
1.29      crook    6512: : CONSTANT ( w "name" -- )
                   6513:     CREATE ,
1.26      crook    6514: DOES> ( -- w )
                   6515:     @@ ;
1.1       anton    6516: @end example
                   6517: 
1.29      crook    6518: @comment There is a beautiful description of how this works and what
                   6519: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6520: @comment commentary on the Counting Fruits problem.
                   6521: 
                   6522: When you create a constant with @code{5 CONSTANT five}, a set of
                   6523: define-time actions take place; first a new word @code{five} is created,
                   6524: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6525: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6526: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6527: no code of its own; it simply contains a data field and a pointer to the
                   6528: code that follows @code{DOES>} in its defining word. That makes words
                   6529: created in this way very compact.
                   6530: 
                   6531: The final example in this section is intended to remind you that space
                   6532: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6533: both read and written by a Standard program@footnote{Exercise: use this
                   6534: example as a starting point for your own implementation of @code{Value}
                   6535: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6536: @code{[']}.}:
                   6537: 
                   6538: @example
                   6539: : foo ( "name" -- )
                   6540:     CREATE -1 ,
                   6541: DOES> ( -- )
1.33      anton    6542:     @@ . ;
1.29      crook    6543: 
                   6544: foo first-word
                   6545: foo second-word
                   6546: 
                   6547: 123 ' first-word >BODY !
                   6548: @end example
                   6549: 
                   6550: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6551: have executed it to get the address of its data field. However, since it
                   6552: was defined to have @code{DOES>} actions, its execution semantics are to
                   6553: perform those @code{DOES>} actions. To get the address of its data field
                   6554: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6555: translate the xt into the address of the data field.  When you execute
                   6556: @code{first-word}, it will display @code{123}. When you execute
                   6557: @code{second-word} it will display @code{-1}.
1.26      crook    6558: 
                   6559: @cindex stack effect of @code{DOES>}-parts
                   6560: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6561: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6562: the stack effect of the defined words, not the stack effect of the
                   6563: following code (the following code expects the address of the body on
                   6564: the top of stack, which is not reflected in the stack comment). This is
                   6565: the convention that I use and recommend (it clashes a bit with using
                   6566: locals declarations for stack effect specification, though).
1.1       anton    6567: 
1.53      anton    6568: @menu
                   6569: * CREATE..DOES> applications::  
                   6570: * CREATE..DOES> details::       
1.63      anton    6571: * Advanced does> usage example::  
1.155     anton    6572: * Const-does>::                 
1.53      anton    6573: @end menu
                   6574: 
                   6575: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26      crook    6576: @subsubsection Applications of @code{CREATE..DOES>}
                   6577: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6578: 
1.26      crook    6579: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6580: 
1.26      crook    6581: @cindex factoring similar colon definitions
                   6582: When you see a sequence of code occurring several times, and you can
                   6583: identify a meaning, you will factor it out as a colon definition. When
                   6584: you see similar colon definitions, you can factor them using
                   6585: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6586: that look very similar:
1.1       anton    6587: @example
1.26      crook    6588: : ori, ( reg-target reg-source n -- )
                   6589:     0 asm-reg-reg-imm ;
                   6590: : andi, ( reg-target reg-source n -- )
                   6591:     1 asm-reg-reg-imm ;
1.1       anton    6592: @end example
                   6593: 
1.26      crook    6594: @noindent
                   6595: This could be factored with:
                   6596: @example
                   6597: : reg-reg-imm ( op-code -- )
                   6598:     CREATE ,
                   6599: DOES> ( reg-target reg-source n -- )
                   6600:     @@ asm-reg-reg-imm ;
                   6601: 
                   6602: 0 reg-reg-imm ori,
                   6603: 1 reg-reg-imm andi,
                   6604: @end example
1.1       anton    6605: 
1.26      crook    6606: @cindex currying
                   6607: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6608: supply a part of the parameters for a word (known as @dfn{currying} in
                   6609: the functional language community). E.g., @code{+} needs two
                   6610: parameters. Creating versions of @code{+} with one parameter fixed can
                   6611: be done like this:
1.82      anton    6612: 
1.1       anton    6613: @example
1.82      anton    6614: : curry+ ( n1 "name" -- )
1.26      crook    6615:     CREATE ,
                   6616: DOES> ( n2 -- n1+n2 )
                   6617:     @@ + ;
                   6618: 
                   6619:  3 curry+ 3+
                   6620: -2 curry+ 2-
1.1       anton    6621: @end example
                   6622: 
1.91      anton    6623: 
1.63      anton    6624: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6625: @subsubsection The gory details of @code{CREATE..DOES>}
                   6626: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6627: 
1.26      crook    6628: doc-does>
1.1       anton    6629: 
1.26      crook    6630: @cindex @code{DOES>} in a separate definition
                   6631: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6632: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6633: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6634: @example
                   6635: : does1 
                   6636: DOES> ( ... -- ... )
1.44      crook    6637:     ... ;
                   6638: 
                   6639: : does2
                   6640: DOES> ( ... -- ... )
                   6641:     ... ;
                   6642: 
                   6643: : def-word ( ... -- ... )
                   6644:     create ...
                   6645:     IF
                   6646:        does1
                   6647:     ELSE
                   6648:        does2
                   6649:     ENDIF ;
                   6650: @end example
                   6651: 
                   6652: In this example, the selection of whether to use @code{does1} or
1.69      anton    6653: @code{does2} is made at definition-time; at the time that the child word is
1.44      crook    6654: @code{CREATE}d.
                   6655: 
                   6656: @cindex @code{DOES>} in interpretation state
                   6657: In a standard program you can apply a @code{DOES>}-part only if the last
                   6658: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6659: will override the behaviour of the last word defined in any case. In a
                   6660: standard program, you can use @code{DOES>} only in a colon
                   6661: definition. In Gforth, you can also use it in interpretation state, in a
                   6662: kind of one-shot mode; for example:
                   6663: @example
                   6664: CREATE name ( ... -- ... )
                   6665:   @i{initialization}
                   6666: DOES>
                   6667:   @i{code} ;
                   6668: @end example
                   6669: 
                   6670: @noindent
                   6671: is equivalent to the standard:
                   6672: @example
                   6673: :noname
                   6674: DOES>
                   6675:     @i{code} ;
                   6676: CREATE name EXECUTE ( ... -- ... )
                   6677:     @i{initialization}
                   6678: @end example
                   6679: 
1.53      anton    6680: doc->body
                   6681: 
1.152     pazsan   6682: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63      anton    6683: @subsubsection Advanced does> usage example
                   6684: 
                   6685: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
                   6686: for disassembling instructions, that follow a very repetetive scheme:
                   6687: 
                   6688: @example
                   6689: :noname @var{disasm-operands} s" @var{inst-name}" type ;
                   6690: @var{entry-num} cells @var{table} + !
                   6691: @end example
                   6692: 
                   6693: Of course, this inspires the idea to factor out the commonalities to
                   6694: allow a definition like
                   6695: 
                   6696: @example
                   6697: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
                   6698: @end example
                   6699: 
                   6700: The parameters @var{disasm-operands} and @var{table} are usually
1.69      anton    6701: correlated.  Moreover, before I wrote the disassembler, there already
                   6702: existed code that defines instructions like this:
1.63      anton    6703: 
                   6704: @example
                   6705: @var{entry-num} @var{inst-format} @var{inst-name}
                   6706: @end example
                   6707: 
                   6708: This code comes from the assembler and resides in
                   6709: @file{arch/mips/insts.fs}.
                   6710: 
                   6711: So I had to define the @var{inst-format} words that performed the scheme
                   6712: above when executed.  At first I chose to use run-time code-generation:
                   6713: 
                   6714: @example
                   6715: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
                   6716:   :noname Postpone @var{disasm-operands}
                   6717:   name Postpone sliteral Postpone type Postpone ;
                   6718:   swap cells @var{table} + ! ;
                   6719: @end example
                   6720: 
                   6721: Note that this supplies the other two parameters of the scheme above.
1.44      crook    6722: 
1.63      anton    6723: An alternative would have been to write this using
                   6724: @code{create}/@code{does>}:
                   6725: 
                   6726: @example
                   6727: : @var{inst-format} ( entry-num "name" -- )
                   6728:   here name string, ( entry-num c-addr ) \ parse and save "name"
                   6729:   noname create , ( entry-num )
1.116     anton    6730:   latestxt swap cells @var{table} + !
1.63      anton    6731: does> ( addr w -- )
                   6732:   \ disassemble instruction w at addr
                   6733:   @@ >r 
                   6734:   @var{disasm-operands}
                   6735:   r> count type ;
                   6736: @end example
                   6737: 
                   6738: Somehow the first solution is simpler, mainly because it's simpler to
                   6739: shift a string from definition-time to use-time with @code{sliteral}
                   6740: than with @code{string,} and friends.
                   6741: 
                   6742: I wrote a lot of words following this scheme and soon thought about
                   6743: factoring out the commonalities among them.  Note that this uses a
                   6744: two-level defining word, i.e., a word that defines ordinary defining
                   6745: words.
                   6746: 
                   6747: This time a solution involving @code{postpone} and friends seemed more
                   6748: difficult (try it as an exercise), so I decided to use a
                   6749: @code{create}/@code{does>} word; since I was already at it, I also used
                   6750: @code{create}/@code{does>} for the lower level (try using
                   6751: @code{postpone} etc. as an exercise), resulting in the following
                   6752: definition:
                   6753: 
                   6754: @example
                   6755: : define-format ( disasm-xt table-xt -- )
                   6756:     \ define an instruction format that uses disasm-xt for
                   6757:     \ disassembling and enters the defined instructions into table
                   6758:     \ table-xt
                   6759:     create 2,
                   6760: does> ( u "inst" -- )
                   6761:     \ defines an anonymous word for disassembling instruction inst,
                   6762:     \ and enters it as u-th entry into table-xt
                   6763:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
                   6764:     noname create 2,      \ define anonymous word
1.116     anton    6765:     execute latestxt swap ! \ enter xt of defined word into table-xt
1.63      anton    6766: does> ( addr w -- )
                   6767:     \ disassemble instruction w at addr
                   6768:     2@@ >r ( addr w disasm-xt R: c-addr )
                   6769:     execute ( R: c-addr ) \ disassemble operands
                   6770:     r> count type ; \ print name 
                   6771: @end example
                   6772: 
                   6773: Note that the tables here (in contrast to above) do the @code{cells +}
                   6774: by themselves (that's why you have to pass an xt).  This word is used in
                   6775: the following way:
                   6776: 
                   6777: @example
                   6778: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
                   6779: @end example
                   6780: 
1.71      anton    6781: As shown above, the defined instruction format is then used like this:
                   6782: 
                   6783: @example
                   6784: @var{entry-num} @var{inst-format} @var{inst-name}
                   6785: @end example
                   6786: 
1.63      anton    6787: In terms of currying, this kind of two-level defining word provides the
                   6788: parameters in three stages: first @var{disasm-operands} and @var{table},
                   6789: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
                   6790: the instruction to be disassembled.  
                   6791: 
                   6792: Of course this did not quite fit all the instruction format names used
                   6793: in @file{insts.fs}, so I had to define a few wrappers that conditioned
                   6794: the parameters into the right form.
                   6795: 
                   6796: If you have trouble following this section, don't worry.  First, this is
                   6797: involved and takes time (and probably some playing around) to
                   6798: understand; second, this is the first two-level
                   6799: @code{create}/@code{does>} word I have written in seventeen years of
                   6800: Forth; and if I did not have @file{insts.fs} to start with, I may well
                   6801: have elected to use just a one-level defining word (with some repeating
                   6802: of parameters when using the defining word). So it is not necessary to
                   6803: understand this, but it may improve your understanding of Forth.
1.44      crook    6804: 
                   6805: 
1.152     pazsan   6806: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
1.91      anton    6807: @subsubsection @code{Const-does>}
                   6808: 
                   6809: A frequent use of @code{create}...@code{does>} is for transferring some
                   6810: values from definition-time to run-time.  Gforth supports this use with
                   6811: 
                   6812: doc-const-does>
                   6813: 
                   6814: A typical use of this word is:
                   6815: 
                   6816: @example
                   6817: : curry+ ( n1 "name" -- )
                   6818: 1 0 CONST-DOES> ( n2 -- n1+n2 )
                   6819:     + ;
                   6820: 
                   6821: 3 curry+ 3+
                   6822: @end example
                   6823: 
                   6824: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
                   6825: definition to run-time.
                   6826: 
                   6827: The advantages of using @code{const-does>} are:
                   6828: 
                   6829: @itemize
                   6830: 
                   6831: @item
                   6832: You don't have to deal with storing and retrieving the values, i.e.,
                   6833: your program becomes more writable and readable.
                   6834: 
                   6835: @item
                   6836: When using @code{does>}, you have to introduce a @code{@@} that cannot
                   6837: be optimized away (because you could change the data using
                   6838: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
                   6839: 
                   6840: @end itemize
                   6841: 
                   6842: An ANS Forth implementation of @code{const-does>} is available in
                   6843: @file{compat/const-does.fs}.
                   6844: 
                   6845: 
1.170     pazsan   6846: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
                   6847: @subsection Deferred Words
1.44      crook    6848: @cindex deferred words
                   6849: 
                   6850: The defining word @code{Defer} allows you to define a word by name
                   6851: without defining its behaviour; the definition of its behaviour is
                   6852: deferred. Here are two situation where this can be useful:
                   6853: 
                   6854: @itemize @bullet
                   6855: @item
                   6856: Where you want to allow the behaviour of a word to be altered later, and
                   6857: for all precompiled references to the word to change when its behaviour
                   6858: is changed.
                   6859: @item
                   6860: For mutual recursion; @xref{Calls and returns}.
                   6861: @end itemize
                   6862: 
                   6863: In the following example, @code{foo} always invokes the version of
                   6864: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6865: always invokes the version that prints ``@code{Hello}''. There is no way
                   6866: of getting @code{foo} to use the later version without re-ordering the
                   6867: source code and recompiling it.
                   6868: 
                   6869: @example
                   6870: : greet ." Good morning" ;
                   6871: : foo ... greet ... ;
                   6872: : greet ." Hello" ;
                   6873: : bar ... greet ... ;
                   6874: @end example
                   6875: 
                   6876: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6877: word. The behaviour of a @code{Defer}red word can be defined and
                   6878: redefined at any time by using @code{IS} to associate the xt of a
                   6879: previously-defined word with it. The previous example becomes:
                   6880: 
                   6881: @example
1.69      anton    6882: Defer greet ( -- )
1.44      crook    6883: : foo ... greet ... ;
                   6884: : bar ... greet ... ;
1.69      anton    6885: : greet1 ( -- ) ." Good morning" ;
                   6886: : greet2 ( -- ) ." Hello" ;
1.132     anton    6887: ' greet2 IS greet  \ make greet behave like greet2
1.44      crook    6888: @end example
                   6889: 
1.69      anton    6890: @progstyle
                   6891: You should write a stack comment for every deferred word, and put only
                   6892: XTs into deferred words that conform to this stack effect.  Otherwise
                   6893: it's too difficult to use the deferred word.
                   6894: 
1.44      crook    6895: A deferred word can be used to improve the statistics-gathering example
                   6896: from @ref{User-defined Defining Words}; rather than edit the
                   6897: application's source code to change every @code{:} to a @code{my:}, do
                   6898: this:
                   6899: 
                   6900: @example
                   6901: : real: : ;     \ retain access to the original
                   6902: defer :         \ redefine as a deferred word
1.132     anton    6903: ' my: IS :      \ use special version of :
1.44      crook    6904: \
                   6905: \ load application here
                   6906: \
1.132     anton    6907: ' real: IS :    \ go back to the original
1.44      crook    6908: @end example
                   6909: 
                   6910: 
1.132     anton    6911: One thing to note is that @code{IS} has special compilation semantics,
                   6912: such that it parses the name at compile time (like @code{TO}):
1.44      crook    6913: 
                   6914: @example
                   6915: : set-greet ( xt -- )
1.132     anton    6916:   IS greet ;
1.44      crook    6917: 
                   6918: ' greet1 set-greet
                   6919: @end example
                   6920: 
1.132     anton    6921: In situations where @code{IS} does not fit, use @code{defer!} instead.
                   6922: 
1.69      anton    6923: A deferred word can only inherit execution semantics from the xt
                   6924: (because that is all that an xt can represent -- for more discussion of
                   6925: this @pxref{Tokens for Words}); by default it will have default
                   6926: interpretation and compilation semantics deriving from this execution
                   6927: semantics.  However, you can change the interpretation and compilation
                   6928: semantics of the deferred word in the usual ways:
1.44      crook    6929: 
                   6930: @example
1.132     anton    6931: : bar .... ; immediate
1.44      crook    6932: Defer fred immediate
                   6933: Defer jim
                   6934: 
1.132     anton    6935: ' bar IS jim  \ jim has default semantics
                   6936: ' bar IS fred \ fred is immediate
1.44      crook    6937: @end example
                   6938: 
                   6939: doc-defer
1.132     anton    6940: doc-defer!
1.44      crook    6941: doc-is
1.132     anton    6942: doc-defer@
                   6943: doc-action-of
1.44      crook    6944: @comment TODO document these: what's defers [is]
                   6945: doc-defers
                   6946: 
                   6947: @c Use @code{words-deferred} to see a list of deferred words.
                   6948: 
1.132     anton    6949: Definitions of these words (except @code{defers}) in ANS Forth are
                   6950: provided in @file{compat/defer.fs}.
1.44      crook    6951: 
                   6952: 
1.170     pazsan   6953: @node Aliases,  , Deferred Words, Defining Words
1.44      crook    6954: @subsection Aliases
                   6955: @cindex aliases
1.1       anton    6956: 
1.44      crook    6957: The defining word @code{Alias} allows you to define a word by name that
                   6958: has the same behaviour as some other word. Here are two situation where
                   6959: this can be useful:
1.1       anton    6960: 
1.44      crook    6961: @itemize @bullet
                   6962: @item
                   6963: When you want access to a word's definition from a different word list
                   6964: (for an example of this, see the definition of the @code{Root} word list
                   6965: in the Gforth source).
                   6966: @item
                   6967: When you want to create a synonym; a definition that can be known by
                   6968: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   6969: aliases).
                   6970: @end itemize
1.1       anton    6971: 
1.69      anton    6972: Like deferred words, an alias has default compilation and interpretation
                   6973: semantics at the beginning (not the modifications of the other word),
                   6974: but you can change them in the usual ways (@code{immediate},
                   6975: @code{compile-only}). For example:
1.1       anton    6976: 
                   6977: @example
1.44      crook    6978: : foo ... ; immediate
                   6979: 
                   6980: ' foo Alias bar \ bar is not an immediate word
                   6981: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    6982: @end example
                   6983: 
1.44      crook    6984: Words that are aliases have the same xt, different headers in the
                   6985: dictionary, and consequently different name tokens (@pxref{Tokens for
                   6986: Words}) and possibly different immediate flags.  An alias can only have
                   6987: default or immediate compilation semantics; you can define aliases for
                   6988: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    6989: 
1.44      crook    6990: doc-alias
1.1       anton    6991: 
                   6992: 
1.47      crook    6993: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   6994: @section Interpretation and Compilation Semantics
1.26      crook    6995: @cindex semantics, interpretation and compilation
1.1       anton    6996: 
1.71      anton    6997: @c !! state and ' are used without explanation
                   6998: @c example for immediate/compile-only? or is the tutorial enough
                   6999: 
1.26      crook    7000: @cindex interpretation semantics
1.71      anton    7001: The @dfn{interpretation semantics} of a (named) word are what the text
1.26      crook    7002: interpreter does when it encounters the word in interpret state. It also
                   7003: appears in some other contexts, e.g., the execution token returned by
1.71      anton    7004: @code{' @i{word}} identifies the interpretation semantics of @i{word}
                   7005: (in other words, @code{' @i{word} execute} is equivalent to
1.29      crook    7006: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    7007: 
1.26      crook    7008: @cindex compilation semantics
1.71      anton    7009: The @dfn{compilation semantics} of a (named) word are what the text
                   7010: interpreter does when it encounters the word in compile state. It also
                   7011: appears in other contexts, e.g, @code{POSTPONE @i{word}}
                   7012: compiles@footnote{In standard terminology, ``appends to the current
                   7013: definition''.} the compilation semantics of @i{word}.
1.1       anton    7014: 
1.26      crook    7015: @cindex execution semantics
                   7016: The standard also talks about @dfn{execution semantics}. They are used
                   7017: only for defining the interpretation and compilation semantics of many
                   7018: words. By default, the interpretation semantics of a word are to
                   7019: @code{execute} its execution semantics, and the compilation semantics of
                   7020: a word are to @code{compile,} its execution semantics.@footnote{In
                   7021: standard terminology: The default interpretation semantics are its
                   7022: execution semantics; the default compilation semantics are to append its
                   7023: execution semantics to the execution semantics of the current
                   7024: definition.}
                   7025: 
1.71      anton    7026: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
                   7027: the text interpreter, ticked, or @code{postpone}d, so they have no
                   7028: interpretation or compilation semantics.  Their behaviour is represented
                   7029: by their XT (@pxref{Tokens for Words}), and we call it execution
                   7030: semantics, too.
                   7031: 
1.26      crook    7032: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   7033: 
                   7034: @cindex immediate words
                   7035: @cindex compile-only words
                   7036: You can change the semantics of the most-recently defined word:
                   7037: 
1.44      crook    7038: 
1.26      crook    7039: doc-immediate
                   7040: doc-compile-only
                   7041: doc-restrict
                   7042: 
1.82      anton    7043: By convention, words with non-default compilation semantics (e.g.,
                   7044: immediate words) often have names surrounded with brackets (e.g.,
                   7045: @code{[']}, @pxref{Execution token}).
1.44      crook    7046: 
1.26      crook    7047: Note that ticking (@code{'}) a compile-only word gives an error
                   7048: (``Interpreting a compile-only word'').
1.1       anton    7049: 
1.47      crook    7050: @menu
1.67      anton    7051: * Combined words::              
1.47      crook    7052: @end menu
1.44      crook    7053: 
1.71      anton    7054: 
1.48      anton    7055: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    7056: @subsection Combined Words
                   7057: @cindex combined words
                   7058: 
                   7059: Gforth allows you to define @dfn{combined words} -- words that have an
                   7060: arbitrary combination of interpretation and compilation semantics.
                   7061: 
1.26      crook    7062: doc-interpret/compile:
1.1       anton    7063: 
1.26      crook    7064: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   7065: recommend that you do not define such words, as cute as they may be:
                   7066: they make it hard to get at both parts of the word in some contexts.
                   7067: E.g., assume you want to get an execution token for the compilation
                   7068: part. Instead, define two words, one that embodies the interpretation
                   7069: part, and one that embodies the compilation part.  Once you have done
                   7070: that, you can define a combined word with @code{interpret/compile:} for
                   7071: the convenience of your users.
1.1       anton    7072: 
1.26      crook    7073: You might try to use this feature to provide an optimizing
                   7074: implementation of the default compilation semantics of a word. For
                   7075: example, by defining:
1.1       anton    7076: @example
1.26      crook    7077: :noname
                   7078:    foo bar ;
                   7079: :noname
                   7080:    POSTPONE foo POSTPONE bar ;
1.29      crook    7081: interpret/compile: opti-foobar
1.1       anton    7082: @end example
1.26      crook    7083: 
1.23      crook    7084: @noindent
1.26      crook    7085: as an optimizing version of:
                   7086: 
1.1       anton    7087: @example
1.26      crook    7088: : foobar
                   7089:     foo bar ;
1.1       anton    7090: @end example
                   7091: 
1.26      crook    7092: Unfortunately, this does not work correctly with @code{[compile]},
                   7093: because @code{[compile]} assumes that the compilation semantics of all
                   7094: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    7095: opti-foobar} would compile compilation semantics, whereas
                   7096: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    7097: 
1.26      crook    7098: @cindex state-smart words (are a bad idea)
1.82      anton    7099: @anchor{state-smartness}
1.29      crook    7100: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    7101: by @code{interpret/compile:} (words are state-smart if they check
                   7102: @code{STATE} during execution). E.g., they would try to code
                   7103: @code{foobar} like this:
1.1       anton    7104: 
1.26      crook    7105: @example
                   7106: : foobar
                   7107:   STATE @@
                   7108:   IF ( compilation state )
                   7109:     POSTPONE foo POSTPONE bar
                   7110:   ELSE
                   7111:     foo bar
                   7112:   ENDIF ; immediate
                   7113: @end example
1.1       anton    7114: 
1.26      crook    7115: Although this works if @code{foobar} is only processed by the text
                   7116: interpreter, it does not work in other contexts (like @code{'} or
                   7117: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   7118: for a state-smart word, not for the interpretation semantics of the
                   7119: original @code{foobar}; when you execute this execution token (directly
                   7120: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   7121: state, the result will not be what you expected (i.e., it will not
                   7122: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   7123: write them@footnote{For a more detailed discussion of this topic, see
1.66      anton    7124: M. Anton Ertl,
                   7125: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
                   7126: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1       anton    7127: 
1.26      crook    7128: @cindex defining words with arbitrary semantics combinations
                   7129: It is also possible to write defining words that define words with
                   7130: arbitrary combinations of interpretation and compilation semantics. In
                   7131: general, they look like this:
1.1       anton    7132: 
1.26      crook    7133: @example
                   7134: : def-word
                   7135:     create-interpret/compile
1.29      crook    7136:     @i{code1}
1.26      crook    7137: interpretation>
1.29      crook    7138:     @i{code2}
1.26      crook    7139: <interpretation
                   7140: compilation>
1.29      crook    7141:     @i{code3}
1.26      crook    7142: <compilation ;
                   7143: @end example
1.1       anton    7144: 
1.29      crook    7145: For a @i{word} defined with @code{def-word}, the interpretation
                   7146: semantics are to push the address of the body of @i{word} and perform
                   7147: @i{code2}, and the compilation semantics are to push the address of
                   7148: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    7149: can also be defined like this (except that the defined constants don't
                   7150: behave correctly when @code{[compile]}d):
1.1       anton    7151: 
1.26      crook    7152: @example
                   7153: : constant ( n "name" -- )
                   7154:     create-interpret/compile
                   7155:     ,
                   7156: interpretation> ( -- n )
                   7157:     @@
                   7158: <interpretation
                   7159: compilation> ( compilation. -- ; run-time. -- n )
                   7160:     @@ postpone literal
                   7161: <compilation ;
                   7162: @end example
1.1       anton    7163: 
1.44      crook    7164: 
1.26      crook    7165: doc-create-interpret/compile
                   7166: doc-interpretation>
                   7167: doc-<interpretation
                   7168: doc-compilation>
                   7169: doc-<compilation
1.1       anton    7170: 
1.44      crook    7171: 
1.29      crook    7172: Words defined with @code{interpret/compile:} and
1.26      crook    7173: @code{create-interpret/compile} have an extended header structure that
                   7174: differs from other words; however, unless you try to access them with
                   7175: plain address arithmetic, you should not notice this. Words for
                   7176: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    7177: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   7178: with @code{create-interpret/compile}.
1.1       anton    7179: 
1.44      crook    7180: 
1.47      crook    7181: @c -------------------------------------------------------------
1.81      anton    7182: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47      crook    7183: @section Tokens for Words
                   7184: @cindex tokens for words
                   7185: 
                   7186: This section describes the creation and use of tokens that represent
                   7187: words.
                   7188: 
1.71      anton    7189: @menu
                   7190: * Execution token::             represents execution/interpretation semantics
                   7191: * Compilation token::           represents compilation semantics
                   7192: * Name token::                  represents named words
                   7193: @end menu
1.47      crook    7194: 
1.71      anton    7195: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
                   7196: @subsection Execution token
1.47      crook    7197: 
                   7198: @cindex xt
                   7199: @cindex execution token
1.71      anton    7200: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
                   7201: You can use @code{execute} to invoke this behaviour.
1.47      crook    7202: 
1.71      anton    7203: @cindex tick (')
                   7204: You can use @code{'} to get an execution token that represents the
                   7205: interpretation semantics of a named word:
1.47      crook    7206: 
                   7207: @example
1.97      anton    7208: 5 ' .   ( n xt ) 
                   7209: execute ( )      \ execute the xt (i.e., ".")
1.71      anton    7210: @end example
1.47      crook    7211: 
1.71      anton    7212: doc-'
                   7213: 
                   7214: @code{'} parses at run-time; there is also a word @code{[']} that parses
                   7215: when it is compiled, and compiles the resulting XT:
                   7216: 
                   7217: @example
                   7218: : foo ['] . execute ;
                   7219: 5 foo
                   7220: : bar ' execute ; \ by contrast,
                   7221: 5 bar .           \ ' parses "." when bar executes
                   7222: @end example
                   7223: 
                   7224: doc-[']
                   7225: 
                   7226: If you want the execution token of @i{word}, write @code{['] @i{word}}
                   7227: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
                   7228: @code{'} and @code{[']} behave somewhat unusually by complaining about
                   7229: compile-only words (because these words have no interpretation
                   7230: semantics).  You might get what you want by using @code{COMP' @i{word}
                   7231: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
                   7232: token}).
                   7233: 
1.116     anton    7234: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71      anton    7235: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
                   7236: for the only behaviour the word has (the execution semantics).  For
1.116     anton    7237: named words, @code{latestxt} produces an XT for the same behaviour it
1.71      anton    7238: would produce if the word was defined anonymously.
                   7239: 
                   7240: @example
                   7241: :noname ." hello" ;
                   7242: execute
1.47      crook    7243: @end example
                   7244: 
1.71      anton    7245: An XT occupies one cell and can be manipulated like any other cell.
                   7246: 
1.47      crook    7247: @cindex code field address
                   7248: @cindex CFA
1.71      anton    7249: In ANS Forth the XT is just an abstract data type (i.e., defined by the
                   7250: operations that produce or consume it).  For old hands: In Gforth, the
                   7251: XT is implemented as a code field address (CFA).
                   7252: 
                   7253: doc-execute
                   7254: doc-perform
                   7255: 
                   7256: @node Compilation token, Name token, Execution token, Tokens for Words
                   7257: @subsection Compilation token
1.47      crook    7258: 
                   7259: @cindex compilation token
1.71      anton    7260: @cindex CT (compilation token)
                   7261: Gforth represents the compilation semantics of a named word by a
1.47      crook    7262: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   7263: @i{xt} is an execution token. The compilation semantics represented by
                   7264: the compilation token can be performed with @code{execute}, which
                   7265: consumes the whole compilation token, with an additional stack effect
                   7266: determined by the represented compilation semantics.
                   7267: 
                   7268: At present, the @i{w} part of a compilation token is an execution token,
                   7269: and the @i{xt} part represents either @code{execute} or
                   7270: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   7271: word. If the word has default compilation semantics, the @i{xt} will
                   7272: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   7273: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   7274: knowledge, unless necessary; future versions of Gforth may introduce
                   7275: unusual compilation tokens (e.g., a compilation token that represents
                   7276: the compilation semantics of a literal).
                   7277: 
1.71      anton    7278: You can perform the compilation semantics represented by the compilation
                   7279: token with @code{execute}.  You can compile the compilation semantics
                   7280: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
                   7281: equivalent to @code{postpone @i{word}}.
                   7282: 
                   7283: doc-[comp']
                   7284: doc-comp'
                   7285: doc-postpone,
                   7286: 
                   7287: @node Name token,  , Compilation token, Tokens for Words
                   7288: @subsection Name token
1.47      crook    7289: 
                   7290: @cindex name token
1.116     anton    7291: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
                   7292: token is an abstract data type that occurs as argument or result of the
                   7293: words below.
                   7294: 
                   7295: @c !! put this elswhere?
1.47      crook    7296: @cindex name field address
                   7297: @cindex NFA
1.116     anton    7298: The closest thing to the nt in older Forth systems is the name field
                   7299: address (NFA), but there are significant differences: in older Forth
                   7300: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
                   7301: LFA, NFA, CFA, PFA) and there were words for getting from one to the
                   7302: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
                   7303: is a link field in the structure identified by the name token, but
                   7304: searching usually uses a hash table external to these structures; the
                   7305: name in Gforth has a cell-wide count-and-flags field, and the nt is not
                   7306: implemented as the address of that count field.
1.47      crook    7307: 
                   7308: doc-find-name
1.116     anton    7309: doc-latest
                   7310: doc->name
1.47      crook    7311: doc-name>int
                   7312: doc-name?int
                   7313: doc-name>comp
                   7314: doc-name>string
1.109     anton    7315: doc-id.
                   7316: doc-.name
                   7317: doc-.id
1.47      crook    7318: 
1.81      anton    7319: @c ----------------------------------------------------------
                   7320: @node Compiling words, The Text Interpreter, Tokens for Words, Words
                   7321: @section Compiling words
                   7322: @cindex compiling words
                   7323: @cindex macros
                   7324: 
                   7325: In contrast to most other languages, Forth has no strict boundary
1.82      anton    7326: between compilation and run-time.  E.g., you can run arbitrary code
                   7327: between defining words (or for computing data used by defining words
                   7328: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
                   7329: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
                   7330: running arbitrary code while compiling a colon definition (exception:
                   7331: you must not allot dictionary space).
                   7332: 
                   7333: @menu
                   7334: * Literals::                    Compiling data values
                   7335: * Macros::                      Compiling words
                   7336: @end menu
                   7337: 
                   7338: @node Literals, Macros, Compiling words, Compiling words
                   7339: @subsection Literals
                   7340: @cindex Literals
                   7341: 
                   7342: The simplest and most frequent example is to compute a literal during
                   7343: compilation.  E.g., the following definition prints an array of strings,
                   7344: one string per line:
                   7345: 
                   7346: @example
                   7347: : .strings ( addr u -- ) \ gforth
                   7348:     2* cells bounds U+DO
                   7349:        cr i 2@@ type
                   7350:     2 cells +LOOP ;  
                   7351: @end example
1.81      anton    7352: 
1.82      anton    7353: With a simple-minded compiler like Gforth's, this computes @code{2
                   7354: cells} on every loop iteration.  You can compute this value once and for
                   7355: all at compile time and compile it into the definition like this:
                   7356: 
                   7357: @example
                   7358: : .strings ( addr u -- ) \ gforth
                   7359:     2* cells bounds U+DO
                   7360:        cr i 2@@ type
                   7361:     [ 2 cells ] literal +LOOP ;  
                   7362: @end example
                   7363: 
                   7364: @code{[} switches the text interpreter to interpret state (you will get
                   7365: an @code{ok} prompt if you type this example interactively and insert a
                   7366: newline between @code{[} and @code{]}), so it performs the
                   7367: interpretation semantics of @code{2 cells}; this computes a number.
                   7368: @code{]} switches the text interpreter back into compile state.  It then
                   7369: performs @code{Literal}'s compilation semantics, which are to compile
                   7370: this number into the current word.  You can decompile the word with
                   7371: @code{see .strings} to see the effect on the compiled code.
1.81      anton    7372: 
1.82      anton    7373: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
                   7374: *} in this way.
1.81      anton    7375: 
1.82      anton    7376: doc-[
                   7377: doc-]
1.81      anton    7378: doc-literal
                   7379: doc-]L
1.82      anton    7380: 
                   7381: There are also words for compiling other data types than single cells as
                   7382: literals:
                   7383: 
1.81      anton    7384: doc-2literal
                   7385: doc-fliteral
1.82      anton    7386: doc-sliteral
                   7387: 
                   7388: @cindex colon-sys, passing data across @code{:}
                   7389: @cindex @code{:}, passing data across
                   7390: You might be tempted to pass data from outside a colon definition to the
                   7391: inside on the data stack.  This does not work, because @code{:} puhes a
                   7392: colon-sys, making stuff below unaccessible.  E.g., this does not work:
                   7393: 
                   7394: @example
                   7395: 5 : foo literal ; \ error: "unstructured"
                   7396: @end example
                   7397: 
                   7398: Instead, you have to pass the value in some other way, e.g., through a
                   7399: variable:
                   7400: 
                   7401: @example
                   7402: variable temp
                   7403: 5 temp !
                   7404: : foo [ temp @@ ] literal ;
                   7405: @end example
                   7406: 
                   7407: 
                   7408: @node Macros,  , Literals, Compiling words
                   7409: @subsection Macros
                   7410: @cindex Macros
                   7411: @cindex compiling compilation semantics
                   7412: 
                   7413: @code{Literal} and friends compile data values into the current
                   7414: definition.  You can also write words that compile other words into the
                   7415: current definition.  E.g.,
                   7416: 
                   7417: @example
                   7418: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
                   7419:   POSTPONE + ;
                   7420: 
                   7421: : foo ( n1 n2 -- n )
                   7422:   [ compile-+ ] ;
                   7423: 1 2 foo .
                   7424: @end example
                   7425: 
                   7426: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
                   7427: What happens in this example?  @code{Postpone} compiles the compilation
                   7428: semantics of @code{+} into @code{compile-+}; later the text interpreter
                   7429: executes @code{compile-+} and thus the compilation semantics of +, which
                   7430: compile (the execution semantics of) @code{+} into
                   7431: @code{foo}.@footnote{A recent RFI answer requires that compiling words
                   7432: should only be executed in compile state, so this example is not
                   7433: guaranteed to work on all standard systems, but on any decent system it
                   7434: will work.}
                   7435: 
                   7436: doc-postpone
                   7437: 
                   7438: Compiling words like @code{compile-+} are usually immediate (or similar)
                   7439: so you do not have to switch to interpret state to execute them;
1.206     anton    7440: modifying the last example accordingly produces:
1.82      anton    7441: 
                   7442: @example
                   7443: : [compile-+] ( compilation: --; interpretation: -- )
                   7444:   \ compiled code: ( n1 n2 -- n )
                   7445:   POSTPONE + ; immediate
                   7446: 
                   7447: : foo ( n1 n2 -- n )
                   7448:   [compile-+] ;
                   7449: 1 2 foo .
                   7450: @end example
                   7451: 
1.206     anton    7452: You will occassionally find the need to POSTPONE several words;
                   7453: putting POSTPONE before each such word is cumbersome, so Gforth
                   7454: provides a more convenient syntax: @code{]] ... [[}.  This
                   7455: allows us to write @code{[compile-+]} as:
                   7456: 
                   7457: @example
                   7458: : [compile-+] ( compilation: --; interpretation: -- )
                   7459:   ]] + [[ ; immediate
                   7460: @end example
                   7461: 
                   7462: doc-]]
                   7463: doc-[[
                   7464: 
                   7465: The unusual direction of the brackets indicates their function:
                   7466: @code{]]} switches from compilation to postponing (i.e., compilation
                   7467: of compilation), just like @code{]} switches from immediate execution
                   7468: (interpretation) to compilation.  Conversely, @code{[[} switches from
                   7469: postponing to compilation, ananlogous to @code{[} which switches from
                   7470: compilation to immediate execution.
                   7471: 
                   7472: The real advantage of @code{]] }...@code{ [[} becomes apparent when
                   7473: there are many words to POSTPONE.  E.g., the word
                   7474: @code{compile-map-array} (@pxref{Advanced macros Tutorial}) can be
                   7475: written much shorter as follows:
                   7476: 
                   7477: @example
                   7478: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   7479: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   7480: \ array beginning at addr and containing u elements
                   7481:   @{ xt @}
                   7482:   ]] cells over + swap ?do
                   7483:     i @@ [[ xt compile, 
                   7484:   1 cells ]]L +loop [[ ;
                   7485: @end example
                   7486: 
                   7487: This example also uses @code{]]L} as a shortcut for @code{]] literal}.
                   7488: There are also other shortcuts
                   7489: 
                   7490: doc-]]L
                   7491: doc-]]2L
                   7492: doc-]]FL
                   7493: doc-]]SL
                   7494: 
                   7495: Note that parsing words don't parse at postpone time; if you want to
                   7496: provide the parsed string right away, you have to switch back to
                   7497: compilation:
                   7498: 
                   7499: @example
                   7500: ]] ... [[ s" some string" ]]2L ... [[
                   7501: ]] ... [[ ['] + ]]L ... [[
                   7502: @end example
                   7503: 
                   7504: Definitions of @code{]]} and friends in ANS Forth are provided in
                   7505: @file{compat/macros.fs}.
                   7506: 
1.82      anton    7507: Immediate compiling words are similar to macros in other languages (in
                   7508: particular, Lisp).  The important differences to macros in, e.g., C are:
                   7509: 
                   7510: @itemize @bullet
                   7511: 
                   7512: @item
                   7513: You use the same language for defining and processing macros, not a
                   7514: separate preprocessing language and processor.
                   7515: 
                   7516: @item
                   7517: Consequently, the full power of Forth is available in macro definitions.
                   7518: E.g., you can perform arbitrarily complex computations, or generate
                   7519: different code conditionally or in a loop (e.g., @pxref{Advanced macros
                   7520: Tutorial}).  This power is very useful when writing a parser generators
                   7521: or other code-generating software.
                   7522: 
                   7523: @item
                   7524: Macros defined using @code{postpone} etc. deal with the language at a
                   7525: higher level than strings; name binding happens at macro definition
                   7526: time, so you can avoid the pitfalls of name collisions that can happen
                   7527: in C macros.  Of course, Forth is a liberal language and also allows to
                   7528: shoot yourself in the foot with text-interpreted macros like
                   7529: 
                   7530: @example
                   7531: : [compile-+] s" +" evaluate ; immediate
                   7532: @end example
                   7533: 
                   7534: Apart from binding the name at macro use time, using @code{evaluate}
                   7535: also makes your definition @code{state}-smart (@pxref{state-smartness}).
                   7536: @end itemize
                   7537: 
                   7538: You may want the macro to compile a number into a word.  The word to do
                   7539: it is @code{literal}, but you have to @code{postpone} it, so its
                   7540: compilation semantics take effect when the macro is executed, not when
                   7541: it is compiled:
                   7542: 
                   7543: @example
                   7544: : [compile-5] ( -- ) \ compiled code: ( -- n )
                   7545:   5 POSTPONE literal ; immediate
                   7546: 
                   7547: : foo [compile-5] ;
                   7548: foo .
                   7549: @end example
                   7550: 
                   7551: You may want to pass parameters to a macro, that the macro should
                   7552: compile into the current definition.  If the parameter is a number, then
                   7553: you can use @code{postpone literal} (similar for other values).
                   7554: 
                   7555: If you want to pass a word that is to be compiled, the usual way is to
                   7556: pass an execution token and @code{compile,} it:
                   7557: 
                   7558: @example
                   7559: : twice1 ( xt -- ) \ compiled code: ... -- ...
                   7560:   dup compile, compile, ;
                   7561: 
                   7562: : 2+ ( n1 -- n2 )
                   7563:   [ ' 1+ twice1 ] ;
                   7564: @end example
                   7565: 
                   7566: doc-compile,
                   7567: 
                   7568: An alternative available in Gforth, that allows you to pass compile-only
                   7569: words as parameters is to use the compilation token (@pxref{Compilation
                   7570: token}).  The same example in this technique:
                   7571: 
                   7572: @example
                   7573: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
                   7574:   2dup 2>r execute 2r> execute ;
                   7575: 
                   7576: : 2+ ( n1 -- n2 )
                   7577:   [ comp' 1+ twice ] ;
                   7578: @end example
                   7579: 
                   7580: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
                   7581: works even if the executed compilation semantics has an effect on the
                   7582: data stack.
                   7583: 
                   7584: You can also define complete definitions with these words; this provides
                   7585: an alternative to using @code{does>} (@pxref{User-defined Defining
                   7586: Words}).  E.g., instead of
                   7587: 
                   7588: @example
                   7589: : curry+ ( n1 "name" -- )
                   7590:     CREATE ,
                   7591: DOES> ( n2 -- n1+n2 )
                   7592:     @@ + ;
                   7593: @end example
                   7594: 
                   7595: you could define
                   7596: 
                   7597: @example
                   7598: : curry+ ( n1 "name" -- )
                   7599:   \ name execution: ( n2 -- n1+n2 )
                   7600:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81      anton    7601: 
1.82      anton    7602: -3 curry+ 3-
                   7603: see 3-
                   7604: @end example
1.81      anton    7605: 
1.82      anton    7606: The sequence @code{>r : r>} is necessary, because @code{:} puts a
                   7607: colon-sys on the data stack that makes everything below it unaccessible.
1.81      anton    7608: 
1.82      anton    7609: This way of writing defining words is sometimes more, sometimes less
                   7610: convenient than using @code{does>} (@pxref{Advanced does> usage
                   7611: example}).  One advantage of this method is that it can be optimized
                   7612: better, because the compiler knows that the value compiled with
                   7613: @code{literal} is fixed, whereas the data associated with a
                   7614: @code{create}d word can be changed.
1.47      crook    7615: 
1.206     anton    7616: @c doc-[compile] !! not properly documented
                   7617: 
1.26      crook    7618: @c ----------------------------------------------------------
1.111     anton    7619: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26      crook    7620: @section  The Text Interpreter
                   7621: @cindex interpreter - outer
                   7622: @cindex text interpreter
                   7623: @cindex outer interpreter
1.1       anton    7624: 
1.34      anton    7625: @c Should we really describe all these ugly details?  IMO the text
                   7626: @c interpreter should be much cleaner, but that may not be possible within
                   7627: @c ANS Forth. - anton
1.44      crook    7628: @c nac-> I wanted to explain how it works to show how you can exploit
                   7629: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   7630: @c some of these gory details was very helpful to me. None of the textbooks
                   7631: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   7632: @c seems to positively avoid going into too much detail for some of
                   7633: @c the internals.
1.34      anton    7634: 
1.71      anton    7635: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
                   7636: @c it is; for the ugly details, I would prefer another place.  I wonder
                   7637: @c whether we should have a chapter before "Words" that describes some
                   7638: @c basic concepts referred to in words, and a chapter after "Words" that
                   7639: @c describes implementation details.
                   7640: 
1.29      crook    7641: The text interpreter@footnote{This is an expanded version of the
                   7642: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    7643: that processes input from the current input device. It is also called
                   7644: the outer interpreter, in contrast to the inner interpreter
                   7645: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   7646: implementations.
1.27      crook    7647: 
1.29      crook    7648: @cindex interpret state
                   7649: @cindex compile state
                   7650: The text interpreter operates in one of two states: @dfn{interpret
                   7651: state} and @dfn{compile state}. The current state is defined by the
1.71      anton    7652: aptly-named variable @code{state}.
1.29      crook    7653: 
                   7654: This section starts by describing how the text interpreter behaves when
                   7655: it is in interpret state, processing input from the user input device --
                   7656: the keyboard. This is the mode that a Forth system is in after it starts
                   7657: up.
                   7658: 
                   7659: @cindex input buffer
                   7660: @cindex terminal input buffer
                   7661: The text interpreter works from an area of memory called the @dfn{input
                   7662: buffer}@footnote{When the text interpreter is processing input from the
                   7663: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   7664: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   7665: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    7666: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    7667: leading spaces (called @dfn{delimiters}) then parses a string (a
                   7668: sequence of non-space characters) until it reaches either a space
                   7669: character or the end of the buffer. Having parsed a string, it makes two
                   7670: attempts to process it:
1.27      crook    7671: 
1.29      crook    7672: @cindex dictionary
1.27      crook    7673: @itemize @bullet
                   7674: @item
1.29      crook    7675: It looks for the string in a @dfn{dictionary} of definitions. If the
                   7676: string is found, the string names a @dfn{definition} (also known as a
                   7677: @dfn{word}) and the dictionary search returns information that allows
                   7678: the text interpreter to perform the word's @dfn{interpretation
                   7679: semantics}. In most cases, this simply means that the word will be
                   7680: executed.
1.27      crook    7681: @item
                   7682: If the string is not found in the dictionary, the text interpreter
1.29      crook    7683: attempts to treat it as a number, using the rules described in
                   7684: @ref{Number Conversion}. If the string represents a legal number in the
                   7685: current radix, the number is pushed onto a parameter stack (the data
                   7686: stack for integers, the floating-point stack for floating-point
                   7687: numbers).
                   7688: @end itemize
                   7689: 
                   7690: If both attempts fail, or if the word is found in the dictionary but has
                   7691: no interpretation semantics@footnote{This happens if the word was
                   7692: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   7693: remainder of the input buffer, issues an error message and waits for
                   7694: more input. If one of the attempts succeeds, the text interpreter
                   7695: repeats the parsing process until the whole of the input buffer has been
                   7696: processed, at which point it prints the status message ``@code{ ok}''
                   7697: and waits for more input.
                   7698: 
1.71      anton    7699: @c anton: this should be in the input stream subsection (or below it)
                   7700: 
1.29      crook    7701: @cindex parse area
                   7702: The text interpreter keeps track of its position in the input buffer by
                   7703: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   7704: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   7705: of the input buffer. The region from offset @code{>IN @@} to the end of
                   7706: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   7707: the text interpreter processes the contents of the input buffer by
                   7708: parsing strings from the parse area until the parse area is empty.}.
                   7709: This example shows how @code{>IN} changes as the text interpreter parses
                   7710: the input buffer:
                   7711: 
                   7712: @example
                   7713: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   7714:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   7715: 
                   7716: 1 2 3 remaining + remaining . 
                   7717: 
                   7718: : foo 1 2 3 remaining SWAP remaining ;
                   7719: @end example
                   7720: 
                   7721: @noindent
                   7722: The result is:
                   7723: 
                   7724: @example
                   7725: ->+ remaining .<-
                   7726: ->.<-5  ok
                   7727: 
                   7728: ->SWAP remaining ;-<
                   7729: ->;<-  ok
                   7730: @end example
                   7731: 
                   7732: @cindex parsing words
                   7733: The value of @code{>IN} can also be modified by a word in the input
                   7734: buffer that is executed by the text interpreter.  This means that a word
                   7735: can ``trick'' the text interpreter into either skipping a section of the
                   7736: input buffer@footnote{This is how parsing words work.} or into parsing a
                   7737: section twice. For example:
1.27      crook    7738: 
1.29      crook    7739: @example
1.71      anton    7740: : lat ." <<foo>>" ;
                   7741: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29      crook    7742: @end example
                   7743: 
                   7744: @noindent
                   7745: When @code{flat} is executed, this output is produced@footnote{Exercise
                   7746: for the reader: what would happen if the @code{3} were replaced with
                   7747: @code{4}?}:
                   7748: 
                   7749: @example
1.71      anton    7750: <<bar>><<foo>>
1.29      crook    7751: @end example
                   7752: 
1.71      anton    7753: This technique can be used to work around some of the interoperability
                   7754: problems of parsing words.  Of course, it's better to avoid parsing
                   7755: words where possible.
                   7756: 
1.29      crook    7757: @noindent
                   7758: Two important notes about the behaviour of the text interpreter:
1.27      crook    7759: 
                   7760: @itemize @bullet
                   7761: @item
                   7762: It processes each input string to completion before parsing additional
1.29      crook    7763: characters from the input buffer.
                   7764: @item
                   7765: It treats the input buffer as a read-only region (and so must your code).
                   7766: @end itemize
                   7767: 
                   7768: @noindent
                   7769: When the text interpreter is in compile state, its behaviour changes in
                   7770: these ways:
                   7771: 
                   7772: @itemize @bullet
                   7773: @item
                   7774: If a parsed string is found in the dictionary, the text interpreter will
                   7775: perform the word's @dfn{compilation semantics}. In most cases, this
                   7776: simply means that the execution semantics of the word will be appended
                   7777: to the current definition.
1.27      crook    7778: @item
1.29      crook    7779: When a number is encountered, it is compiled into the current definition
                   7780: (as a literal) rather than being pushed onto a parameter stack.
                   7781: @item
                   7782: If an error occurs, @code{state} is modified to put the text interpreter
                   7783: back into interpret state.
                   7784: @item
                   7785: Each time a line is entered from the keyboard, Gforth prints
                   7786: ``@code{ compiled}'' rather than `` @code{ok}''.
                   7787: @end itemize
                   7788: 
                   7789: @cindex text interpreter - input sources
                   7790: When the text interpreter is using an input device other than the
                   7791: keyboard, its behaviour changes in these ways:
                   7792: 
                   7793: @itemize @bullet
                   7794: @item
                   7795: When the parse area is empty, the text interpreter attempts to refill
                   7796: the input buffer from the input source. When the input source is
1.71      anton    7797: exhausted, the input source is set back to the previous input source.
1.29      crook    7798: @item
                   7799: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7800: time the parse area is emptied.
                   7801: @item
                   7802: If an error occurs, the input source is set back to the user input
                   7803: device.
1.27      crook    7804: @end itemize
1.21      crook    7805: 
1.49      anton    7806: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7807: 
1.26      crook    7808: doc->in
1.27      crook    7809: doc-source
                   7810: 
1.26      crook    7811: doc-tib
                   7812: doc-#tib
1.1       anton    7813: 
1.44      crook    7814: 
1.26      crook    7815: @menu
1.67      anton    7816: * Input Sources::               
                   7817: * Number Conversion::           
                   7818: * Interpret/Compile states::    
                   7819: * Interpreter Directives::      
1.26      crook    7820: @end menu
1.1       anton    7821: 
1.29      crook    7822: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7823: @subsection Input Sources
                   7824: @cindex input sources
                   7825: @cindex text interpreter - input sources
                   7826: 
1.44      crook    7827: By default, the text interpreter processes input from the user input
1.29      crook    7828: device (the keyboard) when Forth starts up. The text interpreter can
                   7829: process input from any of these sources:
                   7830: 
                   7831: @itemize @bullet
                   7832: @item
                   7833: The user input device -- the keyboard.
                   7834: @item
                   7835: A file, using the words described in @ref{Forth source files}.
                   7836: @item
                   7837: A block, using the words described in @ref{Blocks}.
                   7838: @item
                   7839: A text string, using @code{evaluate}.
                   7840: @end itemize
                   7841: 
                   7842: A program can identify the current input device from the values of
                   7843: @code{source-id} and @code{blk}.
                   7844: 
1.44      crook    7845: 
1.29      crook    7846: doc-source-id
                   7847: doc-blk
                   7848: 
                   7849: doc-save-input
                   7850: doc-restore-input
                   7851: 
                   7852: doc-evaluate
1.111     anton    7853: doc-query
1.1       anton    7854: 
1.29      crook    7855: 
1.44      crook    7856: 
1.29      crook    7857: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7858: @subsection Number Conversion
                   7859: @cindex number conversion
                   7860: @cindex double-cell numbers, input format
                   7861: @cindex input format for double-cell numbers
                   7862: @cindex single-cell numbers, input format
                   7863: @cindex input format for single-cell numbers
                   7864: @cindex floating-point numbers, input format
                   7865: @cindex input format for floating-point numbers
1.1       anton    7866: 
1.29      crook    7867: This section describes the rules that the text interpreter uses when it
                   7868: tries to convert a string into a number.
1.1       anton    7869: 
1.26      crook    7870: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7871: number base@footnote{For example, 0-9 when the number base is decimal or
                   7872: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7873: 
1.26      crook    7874: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7875: 
1.29      crook    7876: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7877: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7878: 
1.26      crook    7879: Let * represent any number of instances of the previous character
                   7880: (including none).
1.1       anton    7881: 
1.26      crook    7882: Let any other character represent itself.
1.1       anton    7883: 
1.29      crook    7884: @noindent
1.26      crook    7885: Now, the conversion rules are:
1.21      crook    7886: 
1.26      crook    7887: @itemize @bullet
                   7888: @item
                   7889: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7890: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7891: @item
                   7892: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7893: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7894: arithmetic. Examples are -45 -5681 -0
                   7895: @item
                   7896: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7897: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7898: (all three of these represent the same number).
1.26      crook    7899: @item
                   7900: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7901: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7902: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7903: -34.65 (all three of these represent the same number).
1.26      crook    7904: @item
1.29      crook    7905: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7906: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7907: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7908: number) +12.E-4
1.26      crook    7909: @end itemize
1.1       anton    7910: 
1.174     anton    7911: By default, the number base used for integer number conversion is
                   7912: given by the contents of the variable @code{base}.  Note that a lot of
1.35      anton    7913: confusion can result from unexpected values of @code{base}.  If you
1.174     anton    7914: change @code{base} anywhere, make sure to save the old value and
                   7915: restore it afterwards; better yet, use @code{base-execute}, which does
                   7916: this for you.  In general I recommend keeping @code{base} decimal, and
1.35      anton    7917: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7918: 
1.29      crook    7919: doc-dpl
1.174     anton    7920: doc-base-execute
1.26      crook    7921: doc-base
                   7922: doc-hex
                   7923: doc-decimal
1.1       anton    7924: 
1.26      crook    7925: @cindex '-prefix for character strings
                   7926: @cindex &-prefix for decimal numbers
1.133     anton    7927: @cindex #-prefix for decimal numbers
1.26      crook    7928: @cindex %-prefix for binary numbers
                   7929: @cindex $-prefix for hexadecimal numbers
1.133     anton    7930: @cindex 0x-prefix for hexadecimal numbers
1.35      anton    7931: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7932: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7933: implementing @code{$} etc. as parsing words that process the subsequent
                   7934: number in the input stream and push it onto the stack. For example, see
                   7935: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7936: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7937: is required between the prefix and the number.} before the first digit
1.133     anton    7938: of an (integer) number. The following prefixes are supported:
1.1       anton    7939: 
1.26      crook    7940: @itemize @bullet
                   7941: @item
1.35      anton    7942: @code{&} -- decimal
1.26      crook    7943: @item
1.133     anton    7944: @code{#} -- decimal
                   7945: @item
1.35      anton    7946: @code{%} -- binary
1.26      crook    7947: @item
1.35      anton    7948: @code{$} -- hexadecimal
1.26      crook    7949: @item
1.133     anton    7950: @code{0x} -- hexadecimal, if base<33.
                   7951: @item
                   7952: @code{'} -- numeric value (e.g., ASCII code) of next character; an
                   7953: optional @code{'} may be present after the character.
1.26      crook    7954: @end itemize
1.1       anton    7955: 
1.26      crook    7956: Here are some examples, with the equivalent decimal number shown after
                   7957: in braces:
1.1       anton    7958: 
1.26      crook    7959: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133     anton    7960: 'A (65),
                   7961: -'a' (-97),
1.26      crook    7962: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    7963: 
1.26      crook    7964: @cindex number conversion - traps for the unwary
1.29      crook    7965: @noindent
1.26      crook    7966: Number conversion has a number of traps for the unwary:
1.1       anton    7967: 
1.26      crook    7968: @itemize @bullet
                   7969: @item
                   7970: You cannot determine the current number base using the code sequence
1.35      anton    7971: @code{base @@ .} -- the number base is always 10 in the current number
                   7972: base. Instead, use something like @code{base @@ dec.}
1.26      crook    7973: @item
                   7974: If the number base is set to a value greater than 14 (for example,
                   7975: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   7976: it to be intepreted as either a single-precision integer or a
                   7977: floating-point number (Gforth treats it as an integer). The ambiguity
                   7978: can be resolved by explicitly stating the sign of the mantissa and/or
                   7979: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   7980: ambiguity arises; either representation will be treated as a
                   7981: floating-point number.
                   7982: @item
1.29      crook    7983: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    7984: It is used to specify file types.
                   7985: @item
1.72      anton    7986: ANS Forth requires the @code{.} of a double-precision number to be the
                   7987: final character in the string.  Gforth allows the @code{.} to be
                   7988: anywhere after the first digit.
1.26      crook    7989: @item
                   7990: The number conversion process does not check for overflow.
                   7991: @item
1.72      anton    7992: In an ANS Forth program @code{base} is required to be decimal when
                   7993: converting floating-point numbers.  In Gforth, number conversion to
                   7994: floating-point numbers always uses base &10, irrespective of the value
                   7995: of @code{base}.
1.26      crook    7996: @end itemize
1.1       anton    7997: 
1.49      anton    7998: You can read numbers into your programs with the words described in
1.181     anton    7999: @ref{Line input and conversion}.
1.1       anton    8000: 
1.82      anton    8001: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26      crook    8002: @subsection Interpret/Compile states
                   8003: @cindex Interpret/Compile states
1.1       anton    8004: 
1.29      crook    8005: A standard program is not permitted to change @code{state}
                   8006: explicitly. However, it can change @code{state} implicitly, using the
                   8007: words @code{[} and @code{]}. When @code{[} is executed it switches
                   8008: @code{state} to interpret state, and therefore the text interpreter
                   8009: starts interpreting. When @code{]} is executed it switches @code{state}
                   8010: to compile state and therefore the text interpreter starts
1.44      crook    8011: compiling. The most common usage for these words is for switching into
                   8012: interpret state and back from within a colon definition; this technique
1.49      anton    8013: can be used to compile a literal (for an example, @pxref{Literals}) or
                   8014: for conditional compilation (for an example, @pxref{Interpreter
                   8015: Directives}).
1.44      crook    8016: 
1.35      anton    8017: 
                   8018: @c This is a bad example: It's non-standard, and it's not necessary.
                   8019: @c However, I can't think of a good example for switching into compile
                   8020: @c state when there is no current word (@code{state}-smart words are not a
                   8021: @c good reason).  So maybe we should use an example for switching into
                   8022: @c interpret @code{state} in a colon def. - anton
1.44      crook    8023: @c nac-> I agree. I started out by putting in the example, then realised
                   8024: @c that it was non-ANS, so wrote more words around it. I hope this
                   8025: @c re-written version is acceptable to you. I do want to keep the example
                   8026: @c as it is helpful for showing what is and what is not portable, particularly
                   8027: @c where it outlaws a style in common use.
                   8028: 
1.72      anton    8029: @c anton: it's more important to show what's portable.  After we have done
1.83      anton    8030: @c that, we can also show what's not.  In any case, I have written a
                   8031: @c section Compiling Words which also deals with [ ].
1.35      anton    8032: 
1.95      anton    8033: @c  !! The following example does not work in Gforth 0.5.9 or later.
1.29      crook    8034: 
1.95      anton    8035: @c  @code{[} and @code{]} also give you the ability to switch into compile
                   8036: @c  state and back, but we cannot think of any useful Standard application
                   8037: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
                   8038: 
                   8039: @c  @example
                   8040: @c  : AA ." this is A" ;
                   8041: @c  : BB ." this is B" ;
                   8042: @c  : CC ." this is C" ;
                   8043: 
                   8044: @c  create table ] aa bb cc [
                   8045: 
                   8046: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   8047: @c    cells table + @@ execute ;
                   8048: @c  @end example
                   8049: 
                   8050: @c  This example builds a jump table; @code{0 go} will display ``@code{this
                   8051: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   8052: @c  defining @code{table} like this:
                   8053: 
                   8054: @c  @example
                   8055: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
                   8056: @c  @end example
                   8057: 
                   8058: @c  The problem with this code is that the definition of @code{table} is not
                   8059: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
                   8060: @c  @i{may} work on systems where code space and data space co-incide, the
                   8061: @c  Standard only allows data space to be assigned for a @code{CREATE}d
                   8062: @c  word. In addition, the Standard only allows @code{@@} to access data
                   8063: @c  space, whilst this example is using it to access code space. The only
                   8064: @c  portable, Standard way to build this table is to build it in data space,
                   8065: @c  like this:
                   8066: 
                   8067: @c  @example
                   8068: @c  create table ' aa , ' bb , ' cc ,
                   8069: @c  @end example
1.29      crook    8070: 
1.95      anton    8071: @c  doc-state
1.44      crook    8072: 
1.29      crook    8073: 
1.82      anton    8074: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
1.26      crook    8075: @subsection Interpreter Directives
                   8076: @cindex interpreter directives
1.72      anton    8077: @cindex conditional compilation
1.1       anton    8078: 
1.29      crook    8079: These words are usually used in interpret state; typically to control
                   8080: which parts of a source file are processed by the text
1.26      crook    8081: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   8082: supplements these with a rich set of immediate control structure words
                   8083: to compensate for the fact that the non-immediate versions can only be
1.29      crook    8084: used in compile state (@pxref{Control Structures}). Typical usages:
                   8085: 
                   8086: @example
1.72      anton    8087: FALSE Constant HAVE-ASSEMBLER
1.29      crook    8088: .
                   8089: .
1.72      anton    8090: HAVE-ASSEMBLER [IF]
1.29      crook    8091: : ASSEMBLER-FEATURE
                   8092:   ...
                   8093: ;
                   8094: [ENDIF]
                   8095: .
                   8096: .
                   8097: : SEE
                   8098:   ... \ general-purpose SEE code
1.72      anton    8099:   [ HAVE-ASSEMBLER [IF] ]
1.29      crook    8100:   ... \ assembler-specific SEE code
                   8101:   [ [ENDIF] ]
                   8102: ;
                   8103: @end example
1.1       anton    8104: 
1.44      crook    8105: 
1.26      crook    8106: doc-[IF]
                   8107: doc-[ELSE]
                   8108: doc-[THEN]
                   8109: doc-[ENDIF]
1.1       anton    8110: 
1.26      crook    8111: doc-[IFDEF]
                   8112: doc-[IFUNDEF]
1.1       anton    8113: 
1.26      crook    8114: doc-[?DO]
                   8115: doc-[DO]
                   8116: doc-[FOR]
                   8117: doc-[LOOP]
                   8118: doc-[+LOOP]
                   8119: doc-[NEXT]
1.1       anton    8120: 
1.26      crook    8121: doc-[BEGIN]
                   8122: doc-[UNTIL]
                   8123: doc-[AGAIN]
                   8124: doc-[WHILE]
                   8125: doc-[REPEAT]
1.1       anton    8126: 
1.27      crook    8127: 
1.26      crook    8128: @c -------------------------------------------------------------
1.111     anton    8129: @node The Input Stream, Word Lists, The Text Interpreter, Words
                   8130: @section The Input Stream
                   8131: @cindex input stream
                   8132: 
                   8133: @c !! integrate this better with the "Text Interpreter" section
                   8134: The text interpreter reads from the input stream, which can come from
                   8135: several sources (@pxref{Input Sources}).  Some words, in particular
                   8136: defining words, but also words like @code{'}, read parameters from the
                   8137: input stream instead of from the stack.
                   8138: 
                   8139: Such words are called parsing words, because they parse the input
                   8140: stream.  Parsing words are hard to use in other words, because it is
                   8141: hard to pass program-generated parameters through the input stream.
                   8142: They also usually have an unintuitive combination of interpretation and
                   8143: compilation semantics when implemented naively, leading to various
                   8144: approaches that try to produce a more intuitive behaviour
                   8145: (@pxref{Combined words}).
                   8146: 
                   8147: It should be obvious by now that parsing words are a bad idea.  If you
                   8148: want to implement a parsing word for convenience, also provide a factor
                   8149: of the word that does not parse, but takes the parameters on the stack.
                   8150: To implement the parsing word on top if it, you can use the following
                   8151: words:
                   8152: 
                   8153: @c anton: these belong in the input stream section
                   8154: doc-parse
1.138     anton    8155: doc-parse-name
1.111     anton    8156: doc-parse-word
                   8157: doc-name
                   8158: doc-word
                   8159: doc-refill
                   8160: 
                   8161: Conversely, if you have the bad luck (or lack of foresight) to have to
                   8162: deal with parsing words without having such factors, how do you pass a
                   8163: string that is not in the input stream to it?
                   8164: 
                   8165: doc-execute-parsing
                   8166: 
1.146     anton    8167: A definition of this word in ANS Forth is provided in
                   8168: @file{compat/execute-parsing.fs}.
                   8169: 
1.111     anton    8170: If you want to run a parsing word on a file, the following word should
                   8171: help:
                   8172: 
                   8173: doc-execute-parsing-file
                   8174: 
                   8175: @c -------------------------------------------------------------
                   8176: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26      crook    8177: @section Word Lists
                   8178: @cindex word lists
1.32      anton    8179: @cindex header space
1.1       anton    8180: 
1.36      anton    8181: A wordlist is a list of named words; you can add new words and look up
                   8182: words by name (and you can remove words in a restricted way with
                   8183: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   8184: 
                   8185: @cindex search order stack
                   8186: The text interpreter searches the wordlists present in the search order
                   8187: (a stack of wordlists), from the top to the bottom.  Within each
                   8188: wordlist, the search starts conceptually at the newest word; i.e., if
                   8189: two words in a wordlist have the same name, the newer word is found.
1.1       anton    8190: 
1.26      crook    8191: @cindex compilation word list
1.36      anton    8192: New words are added to the @dfn{compilation wordlist} (aka current
                   8193: wordlist).
1.1       anton    8194: 
1.36      anton    8195: @cindex wid
                   8196: A word list is identified by a cell-sized word list identifier (@i{wid})
                   8197: in much the same way as a file is identified by a file handle. The
                   8198: numerical value of the wid has no (portable) meaning, and might change
                   8199: from session to session.
1.1       anton    8200: 
1.29      crook    8201: The ANS Forth ``Search order'' word set is intended to provide a set of
                   8202: low-level tools that allow various different schemes to be
1.74      anton    8203: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26      crook    8204: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    8205: Forth.
1.1       anton    8206: 
1.27      crook    8207: @comment TODO: locals section refers to here, saying that every word list (aka
                   8208: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78      anton    8209: @c anton: but better in a separate subsection on wordlist internals
1.1       anton    8210: 
1.45      crook    8211: @comment TODO: document markers, reveal, tables, mappedwordlist
                   8212: 
                   8213: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    8214: @comment word from the source files, rather than some alias.
1.44      crook    8215: 
1.26      crook    8216: doc-forth-wordlist
                   8217: doc-definitions
                   8218: doc-get-current
                   8219: doc-set-current
                   8220: doc-get-order
1.185     anton    8221: doc-set-order
1.26      crook    8222: doc-wordlist
1.30      anton    8223: doc-table
1.79      anton    8224: doc->order
1.36      anton    8225: doc-previous
1.26      crook    8226: doc-also
1.185     anton    8227: doc-forth
1.26      crook    8228: doc-only
1.185     anton    8229: doc-order
1.15      anton    8230: 
1.26      crook    8231: doc-find
                   8232: doc-search-wordlist
1.15      anton    8233: 
1.26      crook    8234: doc-words
                   8235: doc-vlist
1.44      crook    8236: @c doc-words-deferred
1.1       anton    8237: 
1.74      anton    8238: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26      crook    8239: doc-root
                   8240: doc-vocabulary
                   8241: doc-seal
                   8242: doc-vocs
                   8243: doc-current
                   8244: doc-context
1.1       anton    8245: 
1.44      crook    8246: 
1.26      crook    8247: @menu
1.75      anton    8248: * Vocabularies::                
1.67      anton    8249: * Why use word lists?::         
1.75      anton    8250: * Word list example::           
1.26      crook    8251: @end menu
                   8252: 
1.75      anton    8253: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
                   8254: @subsection Vocabularies
                   8255: @cindex Vocabularies, detailed explanation
                   8256: 
                   8257: Here is an example of creating and using a new wordlist using ANS
                   8258: Forth words:
                   8259: 
                   8260: @example
                   8261: wordlist constant my-new-words-wordlist
                   8262: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
                   8263: 
                   8264: \ add it to the search order
                   8265: also my-new-words
                   8266: 
                   8267: \ alternatively, add it to the search order and make it
                   8268: \ the compilation word list
                   8269: also my-new-words definitions
                   8270: \ type "order" to see the problem
                   8271: @end example
                   8272: 
                   8273: The problem with this example is that @code{order} has no way to
                   8274: associate the name @code{my-new-words} with the wid of the word list (in
                   8275: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   8276: that has no associated name). There is no Standard way of associating a
                   8277: name with a wid.
                   8278: 
                   8279: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   8280: associates a name with a wid:
                   8281: 
                   8282: @example
                   8283: vocabulary my-new-words
                   8284: 
                   8285: \ add it to the search order
                   8286: also my-new-words
                   8287: 
                   8288: \ alternatively, add it to the search order and make it
                   8289: \ the compilation word list
                   8290: my-new-words definitions
                   8291: \ type "order" to see that the problem is solved
                   8292: @end example
                   8293: 
                   8294: 
                   8295: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26      crook    8296: @subsection Why use word lists?
                   8297: @cindex word lists - why use them?
                   8298: 
1.74      anton    8299: Here are some reasons why people use wordlists:
1.26      crook    8300: 
                   8301: @itemize @bullet
1.74      anton    8302: 
                   8303: @c anton: Gforth's hashing implementation makes the search speed
                   8304: @c independent from the number of words.  But it is linear with the number
                   8305: @c of wordlists that have to be searched, so in effect using more wordlists
                   8306: @c actually slows down compilation.
                   8307: 
                   8308: @c @item
                   8309: @c To improve compilation speed by reducing the number of header space
                   8310: @c entries that must be searched. This is achieved by creating a new
                   8311: @c word list that contains all of the definitions that are used in the
                   8312: @c definition of a Forth system but which would not usually be used by
                   8313: @c programs running on that system. That word list would be on the search
                   8314: @c list when the Forth system was compiled but would be removed from the
                   8315: @c search list for normal operation. This can be a useful technique for
                   8316: @c low-performance systems (for example, 8-bit processors in embedded
                   8317: @c systems) but is unlikely to be necessary in high-performance desktop
                   8318: @c systems.
                   8319: 
1.26      crook    8320: @item
                   8321: To prevent a set of words from being used outside the context in which
                   8322: they are valid. Two classic examples of this are an integrated editor
                   8323: (all of the edit commands are defined in a separate word list; the
                   8324: search order is set to the editor word list when the editor is invoked;
                   8325: the old search order is restored when the editor is terminated) and an
                   8326: integrated assembler (the op-codes for the machine are defined in a
                   8327: separate word list which is used when a @code{CODE} word is defined).
1.74      anton    8328: 
                   8329: @item
                   8330: To organize the words of an application or library into a user-visible
                   8331: set (in @code{forth-wordlist} or some other common wordlist) and a set
                   8332: of helper words used just for the implementation (hidden in a separate
1.75      anton    8333: wordlist).  This keeps @code{words}' output smaller, separates
                   8334: implementation and interface, and reduces the chance of name conflicts
                   8335: within the common wordlist.
1.74      anton    8336: 
1.26      crook    8337: @item
                   8338: To prevent a name-space clash between multiple definitions with the same
                   8339: name. For example, when building a cross-compiler you might have a word
                   8340: @code{IF} that generates conditional code for your target system. By
                   8341: placing this definition in a different word list you can control whether
                   8342: the host system's @code{IF} or the target system's @code{IF} get used in
                   8343: any particular context by controlling the order of the word lists on the
                   8344: search order stack.
1.74      anton    8345: 
1.26      crook    8346: @end itemize
1.1       anton    8347: 
1.74      anton    8348: The downsides of using wordlists are:
                   8349: 
                   8350: @itemize
                   8351: 
                   8352: @item
                   8353: Debugging becomes more cumbersome.
                   8354: 
                   8355: @item
                   8356: Name conflicts worked around with wordlists are still there, and you
                   8357: have to arrange the search order carefully to get the desired results;
                   8358: if you forget to do that, you get hard-to-find errors (as in any case
                   8359: where you read the code differently from the compiler; @code{see} can
1.75      anton    8360: help seeing which of several possible words the name resolves to in such
                   8361: cases).  @code{See} displays just the name of the words, not what
                   8362: wordlist they belong to, so it might be misleading.  Using unique names
                   8363: is a better approach to avoid name conflicts.
1.74      anton    8364: 
                   8365: @item
                   8366: You have to explicitly undo any changes to the search order.  In many
                   8367: cases it would be more convenient if this happened implicitly.  Gforth
                   8368: currently does not provide such a feature, but it may do so in the
                   8369: future.
                   8370: @end itemize
                   8371: 
                   8372: 
1.75      anton    8373: @node Word list example,  , Why use word lists?, Word Lists
                   8374: @subsection Word list example
                   8375: @cindex word lists - example
1.1       anton    8376: 
1.74      anton    8377: The following example is from the
                   8378: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   8379: garbage collector} and uses wordlists to separate public words from
                   8380: helper words:
                   8381: 
                   8382: @example
                   8383: get-current ( wid )
                   8384: vocabulary garbage-collector also garbage-collector definitions
                   8385: ... \ define helper words
                   8386: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
                   8387: ... \ define the public (i.e., API) words
                   8388:     \ they can refer to the helper words
                   8389: previous \ restore original search order (helper words become invisible)
                   8390: @end example
                   8391: 
1.26      crook    8392: @c -------------------------------------------------------------
                   8393: @node Environmental Queries, Files, Word Lists, Words
                   8394: @section Environmental Queries
                   8395: @cindex environmental queries
1.21      crook    8396: 
1.26      crook    8397: ANS Forth introduced the idea of ``environmental queries'' as a way
                   8398: for a program running on a system to determine certain characteristics of the system.
                   8399: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    8400: 
1.32      anton    8401: The Standard requires that the header space used for environmental queries
                   8402: be distinct from the header space used for definitions.
1.21      crook    8403: 
1.26      crook    8404: Typically, environmental queries are supported by creating a set of
1.29      crook    8405: definitions in a word list that is @i{only} used during environmental
1.26      crook    8406: queries; that is what Gforth does. There is no Standard way of adding
                   8407: definitions to the set of recognised environmental queries, but any
                   8408: implementation that supports the loading of optional word sets must have
                   8409: some mechanism for doing this (after loading the word set, the
                   8410: associated environmental query string must return @code{true}). In
                   8411: Gforth, the word list used to honour environmental queries can be
                   8412: manipulated just like any other word list.
1.21      crook    8413: 
1.44      crook    8414: 
1.26      crook    8415: doc-environment?
                   8416: doc-environment-wordlist
1.21      crook    8417: 
1.26      crook    8418: doc-gforth
                   8419: doc-os-class
1.21      crook    8420: 
1.44      crook    8421: 
1.26      crook    8422: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   8423: returning two items on the stack, querying it using @code{environment?}
                   8424: will return an additional item; the @code{true} flag that shows that the
                   8425: string was recognised.
1.21      crook    8426: 
1.26      crook    8427: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    8428: 
1.26      crook    8429: Here are some examples of using environmental queries:
1.21      crook    8430: 
1.26      crook    8431: @example
                   8432: s" address-unit-bits" environment? 0=
                   8433: [IF]
                   8434:      cr .( environmental attribute address-units-bits unknown... ) cr
1.75      anton    8435: [ELSE]
                   8436:      drop \ ensure balanced stack effect
1.26      crook    8437: [THEN]
1.21      crook    8438: 
1.75      anton    8439: \ this might occur in the prelude of a standard program that uses THROW
                   8440: s" exception" environment? [IF]
                   8441:    0= [IF]
                   8442:       : throw abort" exception thrown" ;
                   8443:    [THEN]
                   8444: [ELSE] \ we don't know, so make sure
                   8445:    : throw abort" exception thrown" ;
                   8446: [THEN]
1.21      crook    8447: 
1.26      crook    8448: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   8449:                         [ELSE] .( Not Gforth..) [THEN]
1.75      anton    8450: 
                   8451: \ a program using v*
                   8452: s" gforth" environment? [IF]
                   8453:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
                   8454:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8455:      >r swap 2swap swap 0e r> 0 ?DO
1.190     anton    8456:        dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75      anton    8457:      LOOP
                   8458:      2drop 2drop ; 
                   8459:   [THEN]
                   8460: [ELSE] \ 
                   8461:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8462:   ...
                   8463: [THEN]
1.26      crook    8464: @end example
1.21      crook    8465: 
1.26      crook    8466: Here is an example of adding a definition to the environment word list:
1.21      crook    8467: 
1.26      crook    8468: @example
                   8469: get-current environment-wordlist set-current
                   8470: true constant block
                   8471: true constant block-ext
                   8472: set-current
                   8473: @end example
1.21      crook    8474: 
1.26      crook    8475: You can see what definitions are in the environment word list like this:
1.21      crook    8476: 
1.26      crook    8477: @example
1.79      anton    8478: environment-wordlist >order words previous
1.26      crook    8479: @end example
1.21      crook    8480: 
                   8481: 
1.26      crook    8482: @c -------------------------------------------------------------
                   8483: @node Files, Blocks, Environmental Queries, Words
                   8484: @section Files
1.28      crook    8485: @cindex files
                   8486: @cindex I/O - file-handling
1.21      crook    8487: 
1.26      crook    8488: Gforth provides facilities for accessing files that are stored in the
                   8489: host operating system's file-system. Files that are processed by Gforth
                   8490: can be divided into two categories:
1.21      crook    8491: 
1.23      crook    8492: @itemize @bullet
                   8493: @item
1.29      crook    8494: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    8495: @item
1.29      crook    8496: Files that are processed by some other program (@dfn{general files}).
1.26      crook    8497: @end itemize
                   8498: 
                   8499: @menu
1.48      anton    8500: * Forth source files::          
                   8501: * General files::               
1.167     anton    8502: * Redirection::                 
1.48      anton    8503: * Search Paths::                
1.26      crook    8504: @end menu
                   8505: 
                   8506: @c -------------------------------------------------------------
                   8507: @node Forth source files, General files, Files, Files
                   8508: @subsection Forth source files
                   8509: @cindex including files
                   8510: @cindex Forth source files
1.21      crook    8511: 
1.26      crook    8512: The simplest way to interpret the contents of a file is to use one of
                   8513: these two formats:
1.21      crook    8514: 
1.26      crook    8515: @example
                   8516: include mysource.fs
                   8517: s" mysource.fs" included
                   8518: @end example
1.21      crook    8519: 
1.75      anton    8520: You usually want to include a file only if it is not included already
1.26      crook    8521: (by, say, another source file). In that case, you can use one of these
1.45      crook    8522: three formats:
1.21      crook    8523: 
1.26      crook    8524: @example
                   8525: require mysource.fs
                   8526: needs mysource.fs
                   8527: s" mysource.fs" required
                   8528: @end example
1.21      crook    8529: 
1.26      crook    8530: @cindex stack effect of included files
                   8531: @cindex including files, stack effect
1.45      crook    8532: It is good practice to write your source files such that interpreting them
                   8533: does not change the stack. Source files designed in this way can be used with
1.26      crook    8534: @code{required} and friends without complications. For example:
1.21      crook    8535: 
1.26      crook    8536: @example
1.75      anton    8537: 1024 require foo.fs drop
1.26      crook    8538: @end example
1.21      crook    8539: 
1.75      anton    8540: Here you want to pass the argument 1024 (e.g., a buffer size) to
                   8541: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
                   8542: ), which allows its use with @code{require}.  Of course with such
                   8543: parameters to required files, you have to ensure that the first
                   8544: @code{require} fits for all uses (i.e., @code{require} it early in the
                   8545: master load file).
1.44      crook    8546: 
1.26      crook    8547: doc-include-file
                   8548: doc-included
1.28      crook    8549: doc-included?
1.26      crook    8550: doc-include
                   8551: doc-required
                   8552: doc-require
                   8553: doc-needs
1.75      anton    8554: @c doc-init-included-files @c internal
                   8555: doc-sourcefilename
                   8556: doc-sourceline#
1.44      crook    8557: 
1.26      crook    8558: A definition in ANS Forth for @code{required} is provided in
                   8559: @file{compat/required.fs}.
1.21      crook    8560: 
1.26      crook    8561: @c -------------------------------------------------------------
1.167     anton    8562: @node General files, Redirection, Forth source files, Files
1.26      crook    8563: @subsection General files
                   8564: @cindex general files
                   8565: @cindex file-handling
1.21      crook    8566: 
1.75      anton    8567: Files are opened/created by name and type. The following file access
                   8568: methods (FAMs) are recognised:
1.44      crook    8569: 
1.75      anton    8570: @cindex fam (file access method)
1.26      crook    8571: doc-r/o
                   8572: doc-r/w
                   8573: doc-w/o
                   8574: doc-bin
1.1       anton    8575: 
1.44      crook    8576: 
1.26      crook    8577: When a file is opened/created, it returns a file identifier,
1.29      crook    8578: @i{wfileid} that is used for all other file commands. All file
                   8579: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    8580: successful operation and an implementation-defined non-zero value in the
                   8581: case of an error.
1.21      crook    8582: 
1.44      crook    8583: 
1.26      crook    8584: doc-open-file
                   8585: doc-create-file
1.21      crook    8586: 
1.26      crook    8587: doc-close-file
                   8588: doc-delete-file
                   8589: doc-rename-file
                   8590: doc-read-file
                   8591: doc-read-line
1.154     anton    8592: doc-key-file
                   8593: doc-key?-file
1.26      crook    8594: doc-write-file
                   8595: doc-write-line
                   8596: doc-emit-file
                   8597: doc-flush-file
1.21      crook    8598: 
1.26      crook    8599: doc-file-status
                   8600: doc-file-position
                   8601: doc-reposition-file
                   8602: doc-file-size
                   8603: doc-resize-file
1.21      crook    8604: 
1.93      anton    8605: doc-slurp-file
                   8606: doc-slurp-fid
1.112     anton    8607: doc-stdin
                   8608: doc-stdout
                   8609: doc-stderr
1.44      crook    8610: 
1.26      crook    8611: @c ---------------------------------------------------------
1.167     anton    8612: @node Redirection, Search Paths, General files, Files
                   8613: @subsection Redirection
                   8614: @cindex Redirection
                   8615: @cindex Input Redirection
                   8616: @cindex Output Redirection
                   8617: 
                   8618: You can redirect the output of @code{type} and @code{emit} and all the
                   8619: words that use them (all output words that don't have an explicit
1.174     anton    8620: target file) to an arbitrary file with the @code{outfile-execute},
                   8621: used like this:
1.167     anton    8622: 
                   8623: @example
1.174     anton    8624: : some-warning ( n -- )
                   8625:     cr ." warning# " . ;
                   8626: 
1.167     anton    8627: : print-some-warning ( n -- )
1.174     anton    8628:     ['] some-warning stderr outfile-execute ;
1.167     anton    8629: @end example
                   8630: 
1.174     anton    8631: After @code{some-warning} is executed, the original output direction
                   8632: is restored; this construct is safe against exceptions.  Similarly,
                   8633: there is @code{infile-execute} for redirecting the input of @code{key}
                   8634: and its users (any input word that does not take a file explicitly).
                   8635: 
                   8636: doc-outfile-execute
                   8637: doc-infile-execute
1.167     anton    8638: 
                   8639: If you do not want to redirect the input or output to a file, you can
                   8640: also make use of the fact that @code{key}, @code{emit} and @code{type}
                   8641: are deferred words (@pxref{Deferred Words}).  However, in that case
                   8642: you have to worry about the restoration and the protection against
                   8643: exceptions yourself; also, note that for redirecting the output in
                   8644: this way, you have to redirect both @code{emit} and @code{type}.
                   8645: 
                   8646: @c ---------------------------------------------------------
                   8647: @node Search Paths,  , Redirection, Files
1.26      crook    8648: @subsection Search Paths
                   8649: @cindex path for @code{included}
                   8650: @cindex file search path
                   8651: @cindex @code{include} search path
                   8652: @cindex search path for files
1.21      crook    8653: 
1.26      crook    8654: If you specify an absolute filename (i.e., a filename starting with
                   8655: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   8656: @samp{C:...})) for @code{included} and friends, that file is included
                   8657: just as you would expect.
1.21      crook    8658: 
1.75      anton    8659: If the filename starts with @file{./}, this refers to the directory that
                   8660: the present file was @code{included} from.  This allows files to include
                   8661: other files relative to their own position (irrespective of the current
                   8662: working directory or the absolute position).  This feature is essential
                   8663: for libraries consisting of several files, where a file may include
                   8664: other files from the library.  It corresponds to @code{#include "..."}
                   8665: in C. If the current input source is not a file, @file{.} refers to the
                   8666: directory of the innermost file being included, or, if there is no file
                   8667: being included, to the current working directory.
                   8668: 
                   8669: For relative filenames (not starting with @file{./}), Gforth uses a
                   8670: search path similar to Forth's search order (@pxref{Word Lists}). It
                   8671: tries to find the given filename in the directories present in the path,
                   8672: and includes the first one it finds. There are separate search paths for
                   8673: Forth source files and general files.  If the search path contains the
                   8674: directory @file{.}, this refers to the directory of the current file, or
                   8675: the working directory, as if the file had been specified with @file{./}.
1.21      crook    8676: 
1.26      crook    8677: Use @file{~+} to refer to the current working directory (as in the
                   8678: @code{bash}).
1.1       anton    8679: 
1.75      anton    8680: @c anton: fold the following subsubsections into this subsection?
1.1       anton    8681: 
1.48      anton    8682: @menu
1.75      anton    8683: * Source Search Paths::         
1.48      anton    8684: * General Search Paths::        
                   8685: @end menu
                   8686: 
1.26      crook    8687: @c ---------------------------------------------------------
1.75      anton    8688: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
                   8689: @subsubsection Source Search Paths
                   8690: @cindex search path control, source files
1.5       anton    8691: 
1.26      crook    8692: The search path is initialized when you start Gforth (@pxref{Invoking
1.75      anton    8693: Gforth}). You can display it and change it using @code{fpath} in
                   8694: combination with the general path handling words.
1.5       anton    8695: 
1.75      anton    8696: doc-fpath
                   8697: @c the functionality of the following words is easily available through
                   8698: @c   fpath and the general path words.  The may go away.
                   8699: @c doc-.fpath
                   8700: @c doc-fpath+
                   8701: @c doc-fpath=
                   8702: @c doc-open-fpath-file
1.44      crook    8703: 
                   8704: @noindent
1.26      crook    8705: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    8706: 
1.26      crook    8707: @example
1.75      anton    8708: fpath path= /usr/lib/forth/|./
1.26      crook    8709: require timer.fs
                   8710: @end example
1.5       anton    8711: 
1.75      anton    8712: 
1.26      crook    8713: @c ---------------------------------------------------------
1.75      anton    8714: @node General Search Paths,  , Source Search Paths, Search Paths
1.26      crook    8715: @subsubsection General Search Paths
1.75      anton    8716: @cindex search path control, source files
1.5       anton    8717: 
1.26      crook    8718: Your application may need to search files in several directories, like
                   8719: @code{included} does. To facilitate this, Gforth allows you to define
                   8720: and use your own search paths, by providing generic equivalents of the
                   8721: Forth search path words:
1.5       anton    8722: 
1.75      anton    8723: doc-open-path-file
                   8724: doc-path-allot
                   8725: doc-clear-path
                   8726: doc-also-path
1.26      crook    8727: doc-.path
                   8728: doc-path+
                   8729: doc-path=
1.5       anton    8730: 
1.75      anton    8731: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44      crook    8732: 
1.75      anton    8733: Here's an example of creating an empty search path:
                   8734: @c
1.26      crook    8735: @example
1.75      anton    8736: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26      crook    8737: @end example
1.5       anton    8738: 
1.26      crook    8739: @c -------------------------------------------------------------
                   8740: @node Blocks, Other I/O, Files, Words
                   8741: @section Blocks
1.28      crook    8742: @cindex I/O - blocks
                   8743: @cindex blocks
                   8744: 
                   8745: When you run Gforth on a modern desk-top computer, it runs under the
                   8746: control of an operating system which provides certain services.  One of
                   8747: these services is @var{file services}, which allows Forth source code
                   8748: and data to be stored in files and read into Gforth (@pxref{Files}).
                   8749: 
                   8750: Traditionally, Forth has been an important programming language on
                   8751: systems where it has interfaced directly to the underlying hardware with
                   8752: no intervening operating system. Forth provides a mechanism, called
1.29      crook    8753: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    8754: 
                   8755: A block is a 1024-byte data area, which can be used to hold data or
                   8756: Forth source code. No structure is imposed on the contents of the
                   8757: block. A block is identified by its number; blocks are numbered
                   8758: contiguously from 1 to an implementation-defined maximum.
                   8759: 
                   8760: A typical system that used blocks but no operating system might use a
                   8761: single floppy-disk drive for mass storage, with the disks formatted to
                   8762: provide 256-byte sectors. Blocks would be implemented by assigning the
                   8763: first four sectors of the disk to block 1, the second four sectors to
                   8764: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   8765: would not contain any file system information, just the set of blocks.
                   8766: 
1.29      crook    8767: @cindex blocks file
1.28      crook    8768: On systems that do provide file services, blocks are typically
1.29      crook    8769: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    8770: file}.  The size of the blocks file will be an exact multiple of 1024
                   8771: bytes, corresponding to the number of blocks it contains. This is the
                   8772: mechanism that Gforth uses.
                   8773: 
1.29      crook    8774: @cindex @file{blocks.fb}
1.75      anton    8775: Only one blocks file can be open at a time. If you use block words without
1.28      crook    8776: having specified a blocks file, Gforth defaults to the blocks file
                   8777: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75      anton    8778: locate a blocks file (@pxref{Source Search Paths}).
1.28      crook    8779: 
1.29      crook    8780: @cindex block buffers
1.28      crook    8781: When you read and write blocks under program control, Gforth uses a
1.29      crook    8782: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    8783: not used when you use @code{load} to interpret the contents of a block.
                   8784: 
1.75      anton    8785: The behaviour of the block buffers is analagous to that of a cache.
                   8786: Each block buffer has three states:
1.28      crook    8787: 
                   8788: @itemize @bullet
                   8789: @item
                   8790: Unassigned
                   8791: @item
                   8792: Assigned-clean
                   8793: @item
                   8794: Assigned-dirty
                   8795: @end itemize
                   8796: 
1.29      crook    8797: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    8798: block, the block (specified by its block number) must be assigned to a
                   8799: block buffer.
                   8800: 
                   8801: The assignment of a block to a block buffer is performed by @code{block}
                   8802: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   8803: contents of a block. Use @code{buffer} when you don't care about the
                   8804: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    8805: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    8806: with the particular block is already stored in a block buffer due to an
                   8807: earlier @code{block} command, @code{buffer} will return that block
                   8808: buffer and the existing contents of the block will be
                   8809: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    8810: block buffer for the block.}.
1.28      crook    8811: 
1.47      crook    8812: Once a block has been assigned to a block buffer using @code{block} or
1.75      anton    8813: @code{buffer}, that block buffer becomes the @i{current block
                   8814: buffer}. Data may only be manipulated (read or written) within the
                   8815: current block buffer.
1.47      crook    8816: 
                   8817: When the contents of the current block buffer has been modified it is
1.48      anton    8818: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75      anton    8819: either abandon the changes (by doing nothing) or mark the block as
                   8820: changed (assigned-dirty), using @code{update}. Using @code{update} does
                   8821: not change the blocks file; it simply changes a block buffer's state to
                   8822: @i{assigned-dirty}.  The block will be written implicitly when it's
                   8823: buffer is needed for another block, or explicitly by @code{flush} or
                   8824: @code{save-buffers}.
                   8825: 
                   8826: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
                   8827: blocks file on disk. Leaving Gforth with @code{bye} also performs a
                   8828: @code{flush}.
1.28      crook    8829: 
1.29      crook    8830: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    8831: algorithm to assign a block buffer to a block. That means that any
                   8832: particular block can only be assigned to one specific block buffer,
1.29      crook    8833: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    8834: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   8835: the new block immediately. If it is @i{assigned-dirty} its current
                   8836: contents are written back to the blocks file on disk before it is
1.28      crook    8837: allocated to the new block.
                   8838: 
                   8839: Although no structure is imposed on the contents of a block, it is
                   8840: traditional to display the contents as 16 lines each of 64 characters.  A
                   8841: block provides a single, continuous stream of input (for example, it
                   8842: acts as a single parse area) -- there are no end-of-line characters
                   8843: within a block, and no end-of-file character at the end of a
                   8844: block. There are two consequences of this:
1.26      crook    8845: 
1.28      crook    8846: @itemize @bullet
                   8847: @item
                   8848: The last character of one line wraps straight into the first character
                   8849: of the following line
                   8850: @item
                   8851: The word @code{\} -- comment to end of line -- requires special
                   8852: treatment; in the context of a block it causes all characters until the
                   8853: end of the current 64-character ``line'' to be ignored.
                   8854: @end itemize
                   8855: 
                   8856: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    8857: the current blocks file will be extended to the appropriate size and the
1.28      crook    8858: block buffer will be initialised with spaces.
                   8859: 
1.47      crook    8860: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   8861: for details) but doesn't encourage the use of blocks; the mechanism is
                   8862: only provided for backward compatibility -- ANS Forth requires blocks to
                   8863: be available when files are.
1.28      crook    8864: 
                   8865: Common techniques that are used when working with blocks include:
                   8866: 
                   8867: @itemize @bullet
                   8868: @item
                   8869: A screen editor that allows you to edit blocks without leaving the Forth
                   8870: environment.
                   8871: @item
                   8872: Shadow screens; where every code block has an associated block
                   8873: containing comments (for example: code in odd block numbers, comments in
                   8874: even block numbers). Typically, the block editor provides a convenient
                   8875: mechanism to toggle between code and comments.
                   8876: @item
                   8877: Load blocks; a single block (typically block 1) contains a number of
                   8878: @code{thru} commands which @code{load} the whole of the application.
                   8879: @end itemize
1.26      crook    8880: 
1.29      crook    8881: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   8882: integrated into a Forth programming environment.
1.26      crook    8883: 
                   8884: @comment TODO what about errors on open-blocks?
1.44      crook    8885: 
1.26      crook    8886: doc-open-blocks
                   8887: doc-use
1.75      anton    8888: doc-block-offset
1.26      crook    8889: doc-get-block-fid
                   8890: doc-block-position
1.28      crook    8891: 
1.75      anton    8892: doc-list
1.28      crook    8893: doc-scr
                   8894: 
1.184     anton    8895: doc-block
1.28      crook    8896: doc-buffer
                   8897: 
1.75      anton    8898: doc-empty-buffers
                   8899: doc-empty-buffer
1.26      crook    8900: doc-update
1.28      crook    8901: doc-updated?
1.26      crook    8902: doc-save-buffers
1.75      anton    8903: doc-save-buffer
1.26      crook    8904: doc-flush
1.28      crook    8905: 
1.26      crook    8906: doc-load
                   8907: doc-thru
                   8908: doc-+load
                   8909: doc-+thru
1.45      crook    8910: doc---gforthman--->
1.26      crook    8911: doc-block-included
                   8912: 
1.44      crook    8913: 
1.26      crook    8914: @c -------------------------------------------------------------
1.126     pazsan   8915: @node Other I/O, OS command line arguments, Blocks, Words
1.26      crook    8916: @section Other I/O
1.28      crook    8917: @cindex I/O - keyboard and display
1.26      crook    8918: 
                   8919: @menu
                   8920: * Simple numeric output::       Predefined formats
                   8921: * Formatted numeric output::    Formatted (pictured) output
                   8922: * String Formats::              How Forth stores strings in memory
1.67      anton    8923: * Displaying characters and strings::  Other stuff
1.175     anton    8924: * Terminal output::             Cursor positioning etc.
1.181     anton    8925: * Single-key input::            
                   8926: * Line input and conversion::   
1.112     anton    8927: * Pipes::                       How to create your own pipes
1.149     pazsan   8928: * Xchars and Unicode::          Non-ASCII characters
1.26      crook    8929: @end menu
                   8930: 
                   8931: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8932: @subsection Simple numeric output
1.28      crook    8933: @cindex numeric output - simple/free-format
1.5       anton    8934: 
1.26      crook    8935: The simplest output functions are those that display numbers from the
                   8936: data or floating-point stacks. Floating-point output is always displayed
                   8937: using base 10. Numbers displayed from the data stack use the value stored
                   8938: in @code{base}.
1.5       anton    8939: 
1.44      crook    8940: 
1.26      crook    8941: doc-.
                   8942: doc-dec.
                   8943: doc-hex.
                   8944: doc-u.
                   8945: doc-.r
                   8946: doc-u.r
                   8947: doc-d.
                   8948: doc-ud.
                   8949: doc-d.r
                   8950: doc-ud.r
                   8951: doc-f.
                   8952: doc-fe.
                   8953: doc-fs.
1.111     anton    8954: doc-f.rdp
1.44      crook    8955: 
1.26      crook    8956: Examples of printing the number 1234.5678E23 in the different floating-point output
                   8957: formats are shown below:
1.5       anton    8958: 
                   8959: @example
1.26      crook    8960: f. 123456779999999000000000000.
                   8961: fe. 123.456779999999E24
                   8962: fs. 1.23456779999999E26
1.5       anton    8963: @end example
                   8964: 
                   8965: 
1.26      crook    8966: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   8967: @subsection Formatted numeric output
1.28      crook    8968: @cindex formatted numeric output
1.26      crook    8969: @cindex pictured numeric output
1.28      crook    8970: @cindex numeric output - formatted
1.26      crook    8971: 
1.29      crook    8972: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    8973: output} for formatted printing of integers.  In this technique, digits
                   8974: are extracted from the number (using the current output radix defined by
                   8975: @code{base}), converted to ASCII codes and appended to a string that is
                   8976: built in a scratch-pad area of memory (@pxref{core-idef,
                   8977: Implementation-defined options, Implementation-defined
                   8978: options}). Arbitrary characters can be appended to the string during the
                   8979: extraction process. The completed string is specified by an address
                   8980: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   8981: under program control.
1.5       anton    8982: 
1.75      anton    8983: All of the integer output words described in the previous section
                   8984: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
                   8985: numeric output.
1.5       anton    8986: 
1.47      crook    8987: Three important things to remember about pictured numeric output:
1.5       anton    8988: 
1.26      crook    8989: @itemize @bullet
                   8990: @item
1.28      crook    8991: It always operates on double-precision numbers; to display a
1.49      anton    8992: single-precision number, convert it first (for ways of doing this
                   8993: @pxref{Double precision}).
1.26      crook    8994: @item
1.28      crook    8995: It always treats the double-precision number as though it were
                   8996: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    8997: @item
                   8998: The string is built up from right to left; least significant digit first.
                   8999: @end itemize
1.5       anton    9000: 
1.44      crook    9001: 
1.26      crook    9002: doc-<#
1.47      crook    9003: doc-<<#
1.26      crook    9004: doc-#
                   9005: doc-#s
                   9006: doc-hold
                   9007: doc-sign
                   9008: doc-#>
1.47      crook    9009: doc-#>>
1.5       anton    9010: 
1.26      crook    9011: doc-represent
1.111     anton    9012: doc-f>str-rdp
                   9013: doc-f>buf-rdp
1.5       anton    9014: 
1.44      crook    9015: 
                   9016: @noindent
1.26      crook    9017: Here are some examples of using pictured numeric output:
1.5       anton    9018: 
                   9019: @example
1.26      crook    9020: : my-u. ( u -- )
                   9021:   \ Simplest use of pns.. behaves like Standard u. 
                   9022:   0              \ convert to unsigned double
1.75      anton    9023:   <<#            \ start conversion
1.26      crook    9024:   #s             \ convert all digits
                   9025:   #>             \ complete conversion
1.75      anton    9026:   TYPE SPACE     \ display, with trailing space
                   9027:   #>> ;          \ release hold area
1.5       anton    9028: 
1.26      crook    9029: : cents-only ( u -- )
                   9030:   0              \ convert to unsigned double
1.75      anton    9031:   <<#            \ start conversion
1.26      crook    9032:   # #            \ convert two least-significant digits
                   9033:   #>             \ complete conversion, discard other digits
1.75      anton    9034:   TYPE SPACE     \ display, with trailing space
                   9035:   #>> ;          \ release hold area
1.5       anton    9036: 
1.26      crook    9037: : dollars-and-cents ( u -- )
                   9038:   0              \ convert to unsigned double
1.75      anton    9039:   <<#            \ start conversion
1.26      crook    9040:   # #            \ convert two least-significant digits
                   9041:   [char] . hold  \ insert decimal point
                   9042:   #s             \ convert remaining digits
                   9043:   [char] $ hold  \ append currency symbol
                   9044:   #>             \ complete conversion
1.75      anton    9045:   TYPE SPACE     \ display, with trailing space
                   9046:   #>> ;          \ release hold area
1.5       anton    9047: 
1.26      crook    9048: : my-. ( n -- )
                   9049:   \ handling negatives.. behaves like Standard .
                   9050:   s>d            \ convert to signed double
                   9051:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    9052:   <<#            \ start conversion
1.26      crook    9053:   #s             \ convert all digits
                   9054:   rot sign       \ get at sign byte, append "-" if needed
                   9055:   #>             \ complete conversion
1.75      anton    9056:   TYPE SPACE     \ display, with trailing space
                   9057:   #>> ;          \ release hold area
1.5       anton    9058: 
1.26      crook    9059: : account. ( n -- )
1.75      anton    9060:   \ accountants don't like minus signs, they use parentheses
1.26      crook    9061:   \ for negative numbers
                   9062:   s>d            \ convert to signed double
                   9063:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    9064:   <<#            \ start conversion
1.26      crook    9065:   2 pick         \ get copy of sign byte
                   9066:   0< IF [char] ) hold THEN \ right-most character of output
                   9067:   #s             \ convert all digits
                   9068:   rot            \ get at sign byte
                   9069:   0< IF [char] ( hold THEN
                   9070:   #>             \ complete conversion
1.75      anton    9071:   TYPE SPACE     \ display, with trailing space
                   9072:   #>> ;          \ release hold area
                   9073: 
1.5       anton    9074: @end example
                   9075: 
1.26      crook    9076: Here are some examples of using these words:
1.5       anton    9077: 
                   9078: @example
1.26      crook    9079: 1 my-u. 1
                   9080: hex -1 my-u. decimal FFFFFFFF
                   9081: 1 cents-only 01
                   9082: 1234 cents-only 34
                   9083: 2 dollars-and-cents $0.02
                   9084: 1234 dollars-and-cents $12.34
                   9085: 123 my-. 123
                   9086: -123 my. -123
                   9087: 123 account. 123
                   9088: -456 account. (456)
1.5       anton    9089: @end example
                   9090: 
                   9091: 
1.26      crook    9092: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   9093: @subsection String Formats
1.27      crook    9094: @cindex strings - see character strings
                   9095: @cindex character strings - formats
1.28      crook    9096: @cindex I/O - see character strings
1.75      anton    9097: @cindex counted strings
                   9098: 
                   9099: @c anton: this does not really belong here; maybe the memory section,
                   9100: @c  or the principles chapter
1.26      crook    9101: 
1.27      crook    9102: Forth commonly uses two different methods for representing character
                   9103: strings:
1.26      crook    9104: 
                   9105: @itemize @bullet
                   9106: @item
                   9107: @cindex address of counted string
1.45      crook    9108: @cindex counted string
1.29      crook    9109: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   9110: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   9111: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    9112: memory.
                   9113: @item
1.29      crook    9114: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   9115: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    9116: first byte of the string.
                   9117: @end itemize
                   9118: 
                   9119: ANS Forth encourages the use of the second format when representing
1.75      anton    9120: strings.
1.26      crook    9121: 
1.44      crook    9122: 
1.26      crook    9123: doc-count
                   9124: 
1.44      crook    9125: 
1.49      anton    9126: For words that move, copy and search for strings see @ref{Memory
                   9127: Blocks}. For words that display characters and strings see
                   9128: @ref{Displaying characters and strings}.
1.26      crook    9129: 
1.175     anton    9130: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26      crook    9131: @subsection Displaying characters and strings
1.27      crook    9132: @cindex characters - compiling and displaying
                   9133: @cindex character strings - compiling and displaying
1.26      crook    9134: 
                   9135: This section starts with a glossary of Forth words and ends with a set
                   9136: of examples.
                   9137: 
                   9138: doc-bl
                   9139: doc-space
                   9140: doc-spaces
                   9141: doc-emit
                   9142: doc-toupper
                   9143: doc-."
                   9144: doc-.(
1.98      anton    9145: doc-.\"
1.26      crook    9146: doc-type
1.44      crook    9147: doc-typewhite
1.26      crook    9148: doc-cr
1.27      crook    9149: @cindex cursor control
1.26      crook    9150: doc-s"
1.98      anton    9151: doc-s\"
1.26      crook    9152: doc-c"
                   9153: doc-char
                   9154: doc-[char]
                   9155: 
1.44      crook    9156: 
                   9157: @noindent
1.26      crook    9158: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    9159: 
                   9160: @example
1.26      crook    9161: .( text-1)
                   9162: : my-word
                   9163:   ." text-2" cr
                   9164:   .( text-3)
                   9165: ;
                   9166: 
                   9167: ." text-4"
                   9168: 
                   9169: : my-char
                   9170:   [char] ALPHABET emit
                   9171:   char emit
                   9172: ;
1.5       anton    9173: @end example
                   9174: 
1.26      crook    9175: When you load this code into Gforth, the following output is generated:
1.5       anton    9176: 
1.26      crook    9177: @example
1.30      anton    9178: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    9179: @end example
1.5       anton    9180: 
1.26      crook    9181: @itemize @bullet
                   9182: @item
                   9183: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   9184: is an immediate word; it behaves in the same way whether it is used inside
                   9185: or outside a colon definition.
                   9186: @item
                   9187: Message @code{text-4} is displayed because of Gforth's added interpretation
                   9188: semantics for @code{."}.
                   9189: @item
1.29      crook    9190: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    9191: performs the compilation semantics for @code{."} within the definition of
                   9192: @code{my-word}.
                   9193: @end itemize
1.5       anton    9194: 
1.26      crook    9195: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    9196: 
1.26      crook    9197: @example
1.30      anton    9198: @kbd{my-word @key{RET}} text-2
1.26      crook    9199:  ok
1.30      anton    9200: @kbd{my-char fred @key{RET}} Af ok
                   9201: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    9202: @end example
1.5       anton    9203: 
                   9204: @itemize @bullet
                   9205: @item
1.26      crook    9206: Message @code{text-2} is displayed because of the run-time behaviour of
                   9207: @code{."}.
                   9208: @item
                   9209: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   9210: on the stack at run-time. @code{emit} always displays the character
                   9211: when @code{my-char} is executed.
                   9212: @item
                   9213: @code{char} parses a string at run-time and the second @code{emit} displays
                   9214: the first character of the string.
1.5       anton    9215: @item
1.26      crook    9216: If you type @code{see my-char} you can see that @code{[char]} discarded
                   9217: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   9218: definition of @code{my-char}.
1.5       anton    9219: @end itemize
                   9220: 
                   9221: 
1.181     anton    9222: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175     anton    9223: @subsection Terminal output
                   9224: @cindex output to terminal
                   9225: @cindex terminal output
                   9226: 
                   9227: If you are outputting to a terminal, you may want to control the
                   9228: positioning of the cursor:
                   9229: @cindex cursor positioning
                   9230: 
                   9231: doc-at-xy
                   9232: 
                   9233: In order to know where to position the cursor, it is often helpful to
                   9234: know the size of the screen:
                   9235: @cindex terminal size 
                   9236: 
                   9237: doc-form
                   9238: 
                   9239: And sometimes you want to use:
                   9240: @cindex clear screen
                   9241: 
                   9242: doc-page
                   9243: 
                   9244: Note that on non-terminals you should use @code{12 emit}, not
                   9245: @code{page}, to get a form feed.
                   9246: 
1.5       anton    9247: 
1.181     anton    9248: @node Single-key input, Line input and conversion, Terminal output, Other I/O
                   9249: @subsection Single-key input
                   9250: @cindex single-key input
                   9251: @cindex input, single-key
                   9252: 
                   9253: If you want to get a single printable character, you can use
                   9254: @code{key}; to check whether a character is available for @code{key},
                   9255: you can use @code{key?}.
1.5       anton    9256: 
1.181     anton    9257: doc-key
                   9258: doc-key?
1.27      crook    9259: 
1.181     anton    9260: If you want to process a mix of printable and non-printable
                   9261: characters, you can do that with @code{ekey} and friends.  @code{Ekey}
                   9262: produces a keyboard event that you have to convert into a character
                   9263: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
                   9264: 
                   9265: Typical code for using EKEY looks like this:
                   9266: 
                   9267: @example
                   9268: ekey ekey>char if ( c )
                   9269:   ... \ do something with the character
                   9270: else ekey>fkey if ( key-id )
                   9271:   case
                   9272:     k-up                                  of ... endof
                   9273:     k-f1                                  of ... endof
                   9274:     k-left k-shift-mask or k-ctrl-mask or of ... endof
                   9275:     ...
                   9276:   endcase
                   9277: else ( keyboard-event )
                   9278:   drop \ just ignore an unknown keyboard event type
                   9279: then then
                   9280: @end example
1.44      crook    9281: 
1.45      crook    9282: doc-ekey
1.141     anton    9283: doc-ekey>char
1.181     anton    9284: doc-ekey>fkey
1.45      crook    9285: doc-ekey?
1.141     anton    9286: 
1.181     anton    9287: The key identifiers for cursor keys are:
1.141     anton    9288: 
                   9289: doc-k-left
                   9290: doc-k-right
1.185     anton    9291: doc-k-up
                   9292: doc-k-down
                   9293: doc-k-home
                   9294: doc-k-end
1.141     anton    9295: doc-k-prior
                   9296: doc-k-next
                   9297: doc-k-insert
                   9298: doc-k-delete
                   9299: 
1.181     anton    9300: The key identifiers for function keys (aka keypad keys) are:
1.141     anton    9301: 
1.181     anton    9302: doc-k-f1
                   9303: doc-k-f2
                   9304: doc-k-f3
                   9305: doc-k-f4
                   9306: doc-k-f5
                   9307: doc-k-f6
                   9308: doc-k-f7
                   9309: doc-k-f8
                   9310: doc-k-f9
                   9311: doc-k-f10
                   9312: doc-k-f11
                   9313: doc-k-f12
                   9314: 
                   9315: Note that @code{k-f11} and @code{k-f12} are not as widely available.
                   9316: 
                   9317: You can combine these key identifiers with masks for various shift keys:
                   9318: 
                   9319: doc-k-shift-mask
                   9320: doc-k-ctrl-mask
                   9321: doc-k-alt-mask
                   9322: 
                   9323: Note that, even if a Forth system has @code{ekey>fkey} and the key
                   9324: identifier words, the keys are not necessarily available or it may not
                   9325: necessarily be able to report all the keys and all the possible
                   9326: combinations with shift masks.  Therefore, write your programs in such
                   9327: a way that they are still useful even if the keys and key combinations
                   9328: cannot be pressed or are not recognized.
                   9329: 
                   9330: Examples: Older keyboards often do not have an F11 and F12 key.  If
                   9331: you run Gforth in an xterm, the xterm catches a number of combinations
                   9332: (e.g., @key{Shift-Up}), and never passes it to Gforth.  Finally,
                   9333: Gforth currently does not recognize and report combinations with
                   9334: multiple shift keys (so the @key{shift-ctrl-left} case in the example
                   9335: above would never be entered).
                   9336: 
                   9337: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
                   9338: you need the ANSI.SYS driver to get that behaviour); it works by
                   9339: recognizing the escape sequences that ANSI terminals send when such a
                   9340: key is pressed.  If you have a terminal that sends other escape
                   9341: sequences, you will not get useful results on Gforth.  Other Forth
                   9342: systems may work in a different way.
                   9343: 
1.200     anton    9344: Gforth also provides a few words for outputting names of function
                   9345: keys:
                   9346: 
                   9347: doc-fkey.
                   9348: doc-simple-fkey-string
                   9349: 
1.181     anton    9350: 
                   9351: @node  Line input and conversion, Pipes, Single-key input, Other I/O
                   9352: @subsection Line input and conversion
                   9353: @cindex line input from terminal
                   9354: @cindex input, linewise from terminal
                   9355: @cindex convertin strings to numbers
                   9356: @cindex I/O - see input
                   9357: 
                   9358: For ways of storing character strings in memory see @ref{String Formats}.
                   9359: 
                   9360: @comment TODO examples for >number >float accept key key? pad parse word refill
                   9361: @comment then index them
1.141     anton    9362: 
                   9363: Words for inputting one line from the keyboard:
                   9364: 
                   9365: doc-accept
                   9366: doc-edit-line
                   9367: 
                   9368: Conversion words:
                   9369: 
1.143     anton    9370: doc-s>number?
                   9371: doc-s>unumber?
1.26      crook    9372: doc->number
                   9373: doc->float
1.143     anton    9374: 
1.141     anton    9375: 
1.27      crook    9376: @comment obsolescent words..
1.141     anton    9377: Obsolescent input and conversion words:
                   9378: 
1.27      crook    9379: doc-convert
1.26      crook    9380: doc-expect
1.27      crook    9381: doc-span
1.5       anton    9382: 
                   9383: 
1.181     anton    9384: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112     anton    9385: @subsection Pipes
                   9386: @cindex pipes, creating your own
                   9387: 
                   9388: In addition to using Gforth in pipes created by other processes
                   9389: (@pxref{Gforth in pipes}), you can create your own pipe with
                   9390: @code{open-pipe}, and read from or write to it.
                   9391: 
                   9392: doc-open-pipe
                   9393: doc-close-pipe
                   9394: 
                   9395: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
                   9396: you don't catch this exception, Gforth will catch it and exit, usually
                   9397: silently (@pxref{Gforth in pipes}).  Since you probably do not want
                   9398: this, you should wrap a @code{catch} or @code{try} block around the code
                   9399: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
                   9400: problem yourself, and then return to regular processing.
                   9401: 
                   9402: doc-broken-pipe-error
                   9403: 
1.155     anton    9404: @node Xchars and Unicode,  , Pipes, Other I/O
                   9405: @subsection Xchars and Unicode
1.149     pazsan   9406: 
1.188     pazsan   9407: ASCII is only appropriate for the English language. Most western
                   9408: languages however fit somewhat into the Forth frame, since a byte is
                   9409: sufficient to encode the few special characters in each (though not
                   9410: always the same encoding can be used; latin-1 is most widely used,
                   9411: though). For other languages, different char-sets have to be used,
                   9412: several of them variable-width. Most prominent representant is
                   9413: UTF-8. Let's call these extended characters xchars. The primitive
                   9414: fixed-size characters stored as bytes are called pchars in this
                   9415: section.
                   9416: 
                   9417: The xchar words add a few data types:
                   9418: 
                   9419: @itemize
                   9420: 
                   9421: @item
                   9422: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
                   9423: and is a subset of unsigned cell. Note: UTF-8 can not store more that
                   9424: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
                   9425: character set can be used.
                   9426: 
                   9427: @item
                   9428: @var{xc-addr} is the address of an xchar in memory. Alignment
                   9429: requirements are the same as @var{c-addr}. The memory representation of an
                   9430: xchar differs from the stack representation, and depends on the
                   9431: encoding used. An xchar may use a variable number of pchars in memory.
                   9432: 
                   9433: @item
                   9434: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
                   9435: @var{xc-addr}, @var{u} pchars long.
                   9436: 
                   9437: @end itemize
                   9438: 
                   9439: doc-xc-size
                   9440: doc-x-size
                   9441: doc-xc@+
                   9442: doc-xc!+?
                   9443: doc-xchar+
                   9444: doc-xchar-
                   9445: doc-+x/string
                   9446: doc-x\string-
                   9447: doc--trailing-garbage
                   9448: doc-x-width
                   9449: doc-xkey
                   9450: doc-xemit
                   9451: 
                   9452: There's a new environment query
                   9453: 
                   9454: doc-xchar-encoding
1.112     anton    9455: 
1.121     anton    9456: @node OS command line arguments, Locals, Other I/O, Words
                   9457: @section OS command line arguments
                   9458: @cindex OS command line arguments
                   9459: @cindex command line arguments, OS
                   9460: @cindex arguments, OS command line
                   9461: 
                   9462: The usual way to pass arguments to Gforth programs on the command line
                   9463: is via the @option{-e} option, e.g.
                   9464: 
                   9465: @example
                   9466: gforth -e "123 456" foo.fs -e bye
                   9467: @end example
                   9468: 
                   9469: However, you may want to interpret the command-line arguments directly.
                   9470: In that case, you can access the (image-specific) command-line arguments
1.123     anton    9471: through @code{next-arg}:
1.121     anton    9472: 
1.123     anton    9473: doc-next-arg
1.121     anton    9474: 
1.123     anton    9475: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121     anton    9476: 
                   9477: @example
                   9478: : echo ( -- )
1.122     anton    9479:     begin
1.123     anton    9480:        next-arg 2dup 0 0 d<> while
                   9481:            type space
                   9482:     repeat
                   9483:     2drop ;
1.121     anton    9484: 
                   9485: echo cr bye
                   9486: @end example
                   9487: 
                   9488: This can be invoked with
                   9489: 
                   9490: @example
                   9491: gforth echo.fs hello world
                   9492: @end example
1.123     anton    9493: 
                   9494: and it will print
                   9495: 
                   9496: @example
                   9497: hello world
                   9498: @end example
                   9499: 
                   9500: The next lower level of dealing with the OS command line are the
                   9501: following words:
                   9502: 
                   9503: doc-arg
                   9504: doc-shift-args
                   9505: 
                   9506: Finally, at the lowest level Gforth provides the following words:
                   9507: 
                   9508: doc-argc
                   9509: doc-argv
1.121     anton    9510: 
1.78      anton    9511: @c -------------------------------------------------------------
1.126     pazsan   9512: @node Locals, Structures, OS command line arguments, Words
1.78      anton    9513: @section Locals
                   9514: @cindex locals
                   9515: 
                   9516: Local variables can make Forth programming more enjoyable and Forth
                   9517: programs easier to read. Unfortunately, the locals of ANS Forth are
                   9518: laden with restrictions. Therefore, we provide not only the ANS Forth
                   9519: locals wordset, but also our own, more powerful locals wordset (we
                   9520: implemented the ANS Forth locals wordset through our locals wordset).
1.44      crook    9521: 
1.78      anton    9522: The ideas in this section have also been published in M. Anton Ertl,
                   9523: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
                   9524: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12      anton    9525: 
                   9526: @menu
1.78      anton    9527: * Gforth locals::               
                   9528: * ANS Forth locals::            
1.5       anton    9529: @end menu
                   9530: 
1.78      anton    9531: @node Gforth locals, ANS Forth locals, Locals, Locals
                   9532: @subsection Gforth locals
                   9533: @cindex Gforth locals
                   9534: @cindex locals, Gforth style
1.5       anton    9535: 
1.78      anton    9536: Locals can be defined with
1.44      crook    9537: 
1.78      anton    9538: @example
                   9539: @{ local1 local2 ... -- comment @}
                   9540: @end example
                   9541: or
                   9542: @example
                   9543: @{ local1 local2 ... @}
                   9544: @end example
1.5       anton    9545: 
1.78      anton    9546: E.g.,
                   9547: @example
                   9548: : max @{ n1 n2 -- n3 @}
                   9549:  n1 n2 > if
                   9550:    n1
                   9551:  else
                   9552:    n2
                   9553:  endif ;
                   9554: @end example
1.44      crook    9555: 
1.78      anton    9556: The similarity of locals definitions with stack comments is intended. A
                   9557: locals definition often replaces the stack comment of a word. The order
                   9558: of the locals corresponds to the order in a stack comment and everything
                   9559: after the @code{--} is really a comment.
1.77      anton    9560: 
1.78      anton    9561: This similarity has one disadvantage: It is too easy to confuse locals
                   9562: declarations with stack comments, causing bugs and making them hard to
                   9563: find. However, this problem can be avoided by appropriate coding
                   9564: conventions: Do not use both notations in the same program. If you do,
                   9565: they should be distinguished using additional means, e.g. by position.
1.77      anton    9566: 
1.78      anton    9567: @cindex types of locals
                   9568: @cindex locals types
                   9569: The name of the local may be preceded by a type specifier, e.g.,
                   9570: @code{F:} for a floating point value:
1.5       anton    9571: 
1.78      anton    9572: @example
                   9573: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   9574: \ complex multiplication
                   9575:  Ar Br f* Ai Bi f* f-
                   9576:  Ar Bi f* Ai Br f* f+ ;
                   9577: @end example
1.44      crook    9578: 
1.78      anton    9579: @cindex flavours of locals
                   9580: @cindex locals flavours
                   9581: @cindex value-flavoured locals
                   9582: @cindex variable-flavoured locals
                   9583: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   9584: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   9585: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   9586: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   9587: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   9588: produces its address (which becomes invalid when the variable's scope is
                   9589: left). E.g., the standard word @code{emit} can be defined in terms of
                   9590: @code{type} like this:
1.5       anton    9591: 
1.78      anton    9592: @example
                   9593: : emit @{ C^ char* -- @}
                   9594:     char* 1 type ;
                   9595: @end example
1.5       anton    9596: 
1.78      anton    9597: @cindex default type of locals
                   9598: @cindex locals, default type
                   9599: A local without type specifier is a @code{W:} local. Both flavours of
                   9600: locals are initialized with values from the data or FP stack.
1.44      crook    9601: 
1.78      anton    9602: Currently there is no way to define locals with user-defined data
                   9603: structures, but we are working on it.
1.5       anton    9604: 
1.78      anton    9605: Gforth allows defining locals everywhere in a colon definition. This
                   9606: poses the following questions:
1.5       anton    9607: 
1.78      anton    9608: @menu
                   9609: * Where are locals visible by name?::  
                   9610: * How long do locals live?::    
                   9611: * Locals programming style::    
                   9612: * Locals implementation::       
                   9613: @end menu
1.44      crook    9614: 
1.78      anton    9615: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   9616: @subsubsection Where are locals visible by name?
                   9617: @cindex locals visibility
                   9618: @cindex visibility of locals
                   9619: @cindex scope of locals
1.5       anton    9620: 
1.78      anton    9621: Basically, the answer is that locals are visible where you would expect
                   9622: it in block-structured languages, and sometimes a little longer. If you
                   9623: want to restrict the scope of a local, enclose its definition in
                   9624: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    9625: 
                   9626: 
1.78      anton    9627: doc-scope
                   9628: doc-endscope
1.5       anton    9629: 
                   9630: 
1.78      anton    9631: These words behave like control structure words, so you can use them
                   9632: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   9633: arbitrary ways.
1.77      anton    9634: 
1.78      anton    9635: If you want a more exact answer to the visibility question, here's the
                   9636: basic principle: A local is visible in all places that can only be
                   9637: reached through the definition of the local@footnote{In compiler
                   9638: construction terminology, all places dominated by the definition of the
                   9639: local.}. In other words, it is not visible in places that can be reached
                   9640: without going through the definition of the local. E.g., locals defined
                   9641: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   9642: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   9643: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77      anton    9644: 
1.78      anton    9645: The reasoning behind this solution is: We want to have the locals
                   9646: visible as long as it is meaningful. The user can always make the
                   9647: visibility shorter by using explicit scoping. In a place that can
                   9648: only be reached through the definition of a local, the meaning of a
                   9649: local name is clear. In other places it is not: How is the local
                   9650: initialized at the control flow path that does not contain the
                   9651: definition? Which local is meant, if the same name is defined twice in
                   9652: two independent control flow paths?
1.77      anton    9653: 
1.78      anton    9654: This should be enough detail for nearly all users, so you can skip the
                   9655: rest of this section. If you really must know all the gory details and
                   9656: options, read on.
1.77      anton    9657: 
1.78      anton    9658: In order to implement this rule, the compiler has to know which places
                   9659: are unreachable. It knows this automatically after @code{AHEAD},
                   9660: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   9661: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   9662: compiler that the control flow never reaches that place. If
                   9663: @code{UNREACHABLE} is not used where it could, the only consequence is
                   9664: that the visibility of some locals is more limited than the rule above
                   9665: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   9666: lie to the compiler), buggy code will be produced.
1.77      anton    9667: 
1.5       anton    9668: 
1.78      anton    9669: doc-unreachable
1.5       anton    9670: 
1.23      crook    9671: 
1.78      anton    9672: Another problem with this rule is that at @code{BEGIN}, the compiler
                   9673: does not know which locals will be visible on the incoming
                   9674: back-edge. All problems discussed in the following are due to this
                   9675: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   9676: loops as examples; the discussion also applies to @code{?DO} and other
                   9677: loops). Perhaps the most insidious example is:
1.26      crook    9678: @example
1.78      anton    9679: AHEAD
                   9680: BEGIN
                   9681:   x
                   9682: [ 1 CS-ROLL ] THEN
                   9683:   @{ x @}
                   9684:   ...
                   9685: UNTIL
1.26      crook    9686: @end example
1.23      crook    9687: 
1.78      anton    9688: This should be legal according to the visibility rule. The use of
                   9689: @code{x} can only be reached through the definition; but that appears
                   9690: textually below the use.
                   9691: 
                   9692: From this example it is clear that the visibility rules cannot be fully
                   9693: implemented without major headaches. Our implementation treats common
                   9694: cases as advertised and the exceptions are treated in a safe way: The
                   9695: compiler makes a reasonable guess about the locals visible after a
                   9696: @code{BEGIN}; if it is too pessimistic, the
                   9697: user will get a spurious error about the local not being defined; if the
                   9698: compiler is too optimistic, it will notice this later and issue a
                   9699: warning. In the case above the compiler would complain about @code{x}
                   9700: being undefined at its use. You can see from the obscure examples in
                   9701: this section that it takes quite unusual control structures to get the
                   9702: compiler into trouble, and even then it will often do fine.
1.23      crook    9703: 
1.78      anton    9704: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   9705: is that all locals visible before the @code{BEGIN} will also be
                   9706: visible after the @code{BEGIN}. This guess is valid for all loops that
                   9707: are entered only through the @code{BEGIN}, in particular, for normal
                   9708: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   9709: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   9710: compiler. When the branch to the @code{BEGIN} is finally generated by
                   9711: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   9712: warns the user if it was too optimistic:
1.26      crook    9713: @example
1.78      anton    9714: IF
                   9715:   @{ x @}
                   9716: BEGIN
                   9717:   \ x ? 
                   9718: [ 1 cs-roll ] THEN
                   9719:   ...
                   9720: UNTIL
1.26      crook    9721: @end example
1.23      crook    9722: 
1.78      anton    9723: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   9724: optimistically assumes that it lives until the @code{THEN}. It notices
                   9725: this difference when it compiles the @code{UNTIL} and issues a
                   9726: warning. The user can avoid the warning, and make sure that @code{x}
                   9727: is not used in the wrong area by using explicit scoping:
                   9728: @example
                   9729: IF
                   9730:   SCOPE
                   9731:   @{ x @}
                   9732:   ENDSCOPE
                   9733: BEGIN
                   9734: [ 1 cs-roll ] THEN
                   9735:   ...
                   9736: UNTIL
                   9737: @end example
1.23      crook    9738: 
1.78      anton    9739: Since the guess is optimistic, there will be no spurious error messages
                   9740: about undefined locals.
1.44      crook    9741: 
1.78      anton    9742: If the @code{BEGIN} is not reachable from above (e.g., after
                   9743: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   9744: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   9745: defined later. Therefore, the compiler assumes that no locals are
                   9746: visible after the @code{BEGIN}. However, the user can use
                   9747: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   9748: visible at the BEGIN as at the point where the top control-flow stack
                   9749: item was created.
1.23      crook    9750: 
1.44      crook    9751: 
1.78      anton    9752: doc-assume-live
1.26      crook    9753: 
1.23      crook    9754: 
1.78      anton    9755: @noindent
                   9756: E.g.,
                   9757: @example
                   9758: @{ x @}
                   9759: AHEAD
                   9760: ASSUME-LIVE
                   9761: BEGIN
                   9762:   x
                   9763: [ 1 CS-ROLL ] THEN
                   9764:   ...
                   9765: UNTIL
                   9766: @end example
1.44      crook    9767: 
1.78      anton    9768: Other cases where the locals are defined before the @code{BEGIN} can be
                   9769: handled by inserting an appropriate @code{CS-ROLL} before the
                   9770: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   9771: behind the @code{ASSUME-LIVE}).
1.23      crook    9772: 
1.78      anton    9773: Cases where locals are defined after the @code{BEGIN} (but should be
                   9774: visible immediately after the @code{BEGIN}) can only be handled by
                   9775: rearranging the loop. E.g., the ``most insidious'' example above can be
                   9776: arranged into:
                   9777: @example
                   9778: BEGIN
                   9779:   @{ x @}
                   9780:   ... 0=
                   9781: WHILE
                   9782:   x
                   9783: REPEAT
                   9784: @end example
1.44      crook    9785: 
1.78      anton    9786: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
                   9787: @subsubsection How long do locals live?
                   9788: @cindex locals lifetime
                   9789: @cindex lifetime of locals
1.23      crook    9790: 
1.78      anton    9791: The right answer for the lifetime question would be: A local lives at
                   9792: least as long as it can be accessed. For a value-flavoured local this
                   9793: means: until the end of its visibility. However, a variable-flavoured
                   9794: local could be accessed through its address far beyond its visibility
                   9795: scope. Ultimately, this would mean that such locals would have to be
                   9796: garbage collected. Since this entails un-Forth-like implementation
                   9797: complexities, I adopted the same cowardly solution as some other
                   9798: languages (e.g., C): The local lives only as long as it is visible;
                   9799: afterwards its address is invalid (and programs that access it
                   9800: afterwards are erroneous).
1.23      crook    9801: 
1.78      anton    9802: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
                   9803: @subsubsection Locals programming style
                   9804: @cindex locals programming style
                   9805: @cindex programming style, locals
1.23      crook    9806: 
1.78      anton    9807: The freedom to define locals anywhere has the potential to change
                   9808: programming styles dramatically. In particular, the need to use the
                   9809: return stack for intermediate storage vanishes. Moreover, all stack
                   9810: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9811: determined arguments) can be eliminated: If the stack items are in the
                   9812: wrong order, just write a locals definition for all of them; then
                   9813: write the items in the order you want.
1.23      crook    9814: 
1.78      anton    9815: This seems a little far-fetched and eliminating stack manipulations is
                   9816: unlikely to become a conscious programming objective. Still, the number
                   9817: of stack manipulations will be reduced dramatically if local variables
                   9818: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
                   9819: a traditional implementation of @code{max}).
1.23      crook    9820: 
1.78      anton    9821: This shows one potential benefit of locals: making Forth programs more
                   9822: readable. Of course, this benefit will only be realized if the
                   9823: programmers continue to honour the principle of factoring instead of
                   9824: using the added latitude to make the words longer.
1.23      crook    9825: 
1.78      anton    9826: @cindex single-assignment style for locals
                   9827: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9828: every value-flavoured local has only a single assignment and many
                   9829: advantages of functional languages apply to Forth. I.e., programs are
                   9830: easier to analyse, to optimize and to read: It is clear from the
                   9831: definition what the local stands for, it does not turn into something
                   9832: different later.
1.23      crook    9833: 
1.78      anton    9834: E.g., a definition using @code{TO} might look like this:
                   9835: @example
                   9836: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9837:  u1 u2 min 0
                   9838:  ?do
                   9839:    addr1 c@@ addr2 c@@ -
                   9840:    ?dup-if
                   9841:      unloop exit
                   9842:    then
                   9843:    addr1 char+ TO addr1
                   9844:    addr2 char+ TO addr2
                   9845:  loop
                   9846:  u1 u2 - ;
1.26      crook    9847: @end example
1.78      anton    9848: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9849: every loop iteration. @code{strcmp} is a typical example of the
                   9850: readability problems of using @code{TO}. When you start reading
                   9851: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9852: string. Only near the end of the loop you realize that it is something
                   9853: else.
1.23      crook    9854: 
1.78      anton    9855: This can be avoided by defining two locals at the start of the loop that
                   9856: are initialized with the right value for the current iteration.
                   9857: @example
                   9858: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9859:  addr1 addr2
                   9860:  u1 u2 min 0 
                   9861:  ?do @{ s1 s2 @}
                   9862:    s1 c@@ s2 c@@ -
                   9863:    ?dup-if
                   9864:      unloop exit
                   9865:    then
                   9866:    s1 char+ s2 char+
                   9867:  loop
                   9868:  2drop
                   9869:  u1 u2 - ;
                   9870: @end example
                   9871: Here it is clear from the start that @code{s1} has a different value
                   9872: in every loop iteration.
1.23      crook    9873: 
1.78      anton    9874: @node Locals implementation,  , Locals programming style, Gforth locals
                   9875: @subsubsection Locals implementation
                   9876: @cindex locals implementation
                   9877: @cindex implementation of locals
1.23      crook    9878: 
1.78      anton    9879: @cindex locals stack
                   9880: Gforth uses an extra locals stack. The most compelling reason for
                   9881: this is that the return stack is not float-aligned; using an extra stack
                   9882: also eliminates the problems and restrictions of using the return stack
                   9883: as locals stack. Like the other stacks, the locals stack grows toward
                   9884: lower addresses. A few primitives allow an efficient implementation:
                   9885: 
                   9886: 
                   9887: doc-@local#
                   9888: doc-f@local#
                   9889: doc-laddr#
                   9890: doc-lp+!#
                   9891: doc-lp!
                   9892: doc->l
                   9893: doc-f>l
                   9894: 
                   9895: 
                   9896: In addition to these primitives, some specializations of these
                   9897: primitives for commonly occurring inline arguments are provided for
                   9898: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9899: @code{@@local#} for the inline argument 0. The following compiling words
                   9900: compile the right specialized version, or the general version, as
                   9901: appropriate:
1.23      crook    9902: 
1.5       anton    9903: 
1.107     dvdkhlng 9904: @c doc-compile-@local
                   9905: @c doc-compile-f@local
1.78      anton    9906: doc-compile-lp+!
1.5       anton    9907: 
                   9908: 
1.78      anton    9909: Combinations of conditional branches and @code{lp+!#} like
                   9910: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9911: is taken) are provided for efficiency and correctness in loops.
1.5       anton    9912: 
1.78      anton    9913: A special area in the dictionary space is reserved for keeping the
                   9914: local variable names. @code{@{} switches the dictionary pointer to this
                   9915: area and @code{@}} switches it back and generates the locals
                   9916: initializing code. @code{W:} etc.@ are normal defining words. This
                   9917: special area is cleared at the start of every colon definition.
1.5       anton    9918: 
1.78      anton    9919: @cindex word list for defining locals
                   9920: A special feature of Gforth's dictionary is used to implement the
                   9921: definition of locals without type specifiers: every word list (aka
                   9922: vocabulary) has its own methods for searching
                   9923: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   9924: with a special search method: When it is searched for a word, it
                   9925: actually creates that word using @code{W:}. @code{@{} changes the search
                   9926: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   9927: and then the word list for defining locals without type specifiers.
1.5       anton    9928: 
1.78      anton    9929: The lifetime rules support a stack discipline within a colon
                   9930: definition: The lifetime of a local is either nested with other locals
                   9931: lifetimes or it does not overlap them.
1.23      crook    9932: 
1.78      anton    9933: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   9934: pointer manipulation is generated. Between control structure words
                   9935: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   9936: is the simplest of the other three control flow words. It has to
                   9937: restore the locals stack depth of the corresponding @code{BEGIN}
                   9938: before branching. The code looks like this:
                   9939: @format
                   9940: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   9941: @code{branch} <begin>
                   9942: @end format
1.26      crook    9943: 
1.78      anton    9944: @code{UNTIL} is a little more complicated: If it branches back, it
                   9945: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   9946: the locals stack must not be changed. The compiler generates the
                   9947: following code:
                   9948: @format
                   9949: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   9950: @end format
                   9951: The locals stack pointer is only adjusted if the branch is taken.
1.44      crook    9952: 
1.78      anton    9953: @code{THEN} can produce somewhat inefficient code:
                   9954: @format
                   9955: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   9956: <orig target>:
                   9957: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   9958: @end format
                   9959: The second @code{lp+!#} adjusts the locals stack pointer from the
                   9960: level at the @i{orig} point to the level after the @code{THEN}. The
                   9961: first @code{lp+!#} adjusts the locals stack pointer from the current
                   9962: level to the level at the orig point, so the complete effect is an
                   9963: adjustment from the current level to the right level after the
                   9964: @code{THEN}.
1.26      crook    9965: 
1.78      anton    9966: @cindex locals information on the control-flow stack
                   9967: @cindex control-flow stack items, locals information
                   9968: In a conventional Forth implementation a dest control-flow stack entry
                   9969: is just the target address and an orig entry is just the address to be
                   9970: patched. Our locals implementation adds a word list to every orig or dest
                   9971: item. It is the list of locals visible (or assumed visible) at the point
                   9972: described by the entry. Our implementation also adds a tag to identify
                   9973: the kind of entry, in particular to differentiate between live and dead
                   9974: (reachable and unreachable) orig entries.
1.26      crook    9975: 
1.78      anton    9976: A few unusual operations have to be performed on locals word lists:
1.44      crook    9977: 
1.5       anton    9978: 
1.78      anton    9979: doc-common-list
                   9980: doc-sub-list?
                   9981: doc-list-size
1.52      anton    9982: 
                   9983: 
1.78      anton    9984: Several features of our locals word list implementation make these
                   9985: operations easy to implement: The locals word lists are organised as
                   9986: linked lists; the tails of these lists are shared, if the lists
                   9987: contain some of the same locals; and the address of a name is greater
                   9988: than the address of the names behind it in the list.
1.5       anton    9989: 
1.78      anton    9990: Another important implementation detail is the variable
                   9991: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   9992: determine if they can be reached directly or only through the branch
                   9993: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   9994: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   9995: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5       anton    9996: 
1.78      anton    9997: Counted loops are similar to other loops in most respects, but
                   9998: @code{LEAVE} requires special attention: It performs basically the same
                   9999: service as @code{AHEAD}, but it does not create a control-flow stack
                   10000: entry. Therefore the information has to be stored elsewhere;
                   10001: traditionally, the information was stored in the target fields of the
                   10002: branches created by the @code{LEAVE}s, by organizing these fields into a
                   10003: linked list. Unfortunately, this clever trick does not provide enough
                   10004: space for storing our extended control flow information. Therefore, we
                   10005: introduce another stack, the leave stack. It contains the control-flow
                   10006: stack entries for all unresolved @code{LEAVE}s.
1.44      crook    10007: 
1.78      anton    10008: Local names are kept until the end of the colon definition, even if
                   10009: they are no longer visible in any control-flow path. In a few cases
                   10010: this may lead to increased space needs for the locals name area, but
                   10011: usually less than reclaiming this space would cost in code size.
1.5       anton    10012: 
1.44      crook    10013: 
1.78      anton    10014: @node ANS Forth locals,  , Gforth locals, Locals
                   10015: @subsection ANS Forth locals
                   10016: @cindex locals, ANS Forth style
1.5       anton    10017: 
1.78      anton    10018: The ANS Forth locals wordset does not define a syntax for locals, but
                   10019: words that make it possible to define various syntaxes. One of the
                   10020: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   10021: wordset, i.e.:
1.29      crook    10022: 
                   10023: @example
1.78      anton    10024: @{ local1 local2 ... -- comment @}
                   10025: @end example
                   10026: @noindent
                   10027: or
                   10028: @example
                   10029: @{ local1 local2 ... @}
1.29      crook    10030: @end example
                   10031: 
1.78      anton    10032: The order of the locals corresponds to the order in a stack comment. The
                   10033: restrictions are:
1.5       anton    10034: 
1.78      anton    10035: @itemize @bullet
                   10036: @item
                   10037: Locals can only be cell-sized values (no type specifiers are allowed).
                   10038: @item
                   10039: Locals can be defined only outside control structures.
                   10040: @item
                   10041: Locals can interfere with explicit usage of the return stack. For the
                   10042: exact (and long) rules, see the standard. If you don't use return stack
                   10043: accessing words in a definition using locals, you will be all right. The
                   10044: purpose of this rule is to make locals implementation on the return
                   10045: stack easier.
                   10046: @item
                   10047: The whole definition must be in one line.
                   10048: @end itemize
1.5       anton    10049: 
1.78      anton    10050: Locals defined in ANS Forth behave like @code{VALUE}s
                   10051: (@pxref{Values}). I.e., they are initialized from the stack. Using their
                   10052: name produces their value. Their value can be changed using @code{TO}.
1.77      anton    10053: 
1.78      anton    10054: Since the syntax above is supported by Gforth directly, you need not do
                   10055: anything to use it. If you want to port a program using this syntax to
                   10056: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   10057: syntax on the other system.
1.5       anton    10058: 
1.78      anton    10059: Note that a syntax shown in the standard, section A.13 looks
                   10060: similar, but is quite different in having the order of locals
                   10061: reversed. Beware!
1.5       anton    10062: 
1.78      anton    10063: The ANS Forth locals wordset itself consists of one word:
1.5       anton    10064: 
1.78      anton    10065: doc-(local)
1.5       anton    10066: 
1.78      anton    10067: The ANS Forth locals extension wordset defines a syntax using
                   10068: @code{locals|}, but it is so awful that we strongly recommend not to use
                   10069: it. We have implemented this syntax to make porting to Gforth easy, but
                   10070: do not document it here. The problem with this syntax is that the locals
                   10071: are defined in an order reversed with respect to the standard stack
                   10072: comment notation, making programs harder to read, and easier to misread
                   10073: and miswrite. The only merit of this syntax is that it is easy to
                   10074: implement using the ANS Forth locals wordset.
1.53      anton    10075: 
                   10076: 
1.78      anton    10077: @c ----------------------------------------------------------
                   10078: @node Structures, Object-oriented Forth, Locals, Words
                   10079: @section  Structures
                   10080: @cindex structures
                   10081: @cindex records
1.53      anton    10082: 
1.78      anton    10083: This section presents the structure package that comes with Gforth. A
                   10084: version of the package implemented in ANS Forth is available in
                   10085: @file{compat/struct.fs}. This package was inspired by a posting on
                   10086: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   10087: possibly John Hayes). A version of this section has been published in
                   10088: M. Anton Ertl,
                   10089: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
                   10090: Another Forth Structures Package}, Forth Dimensions 19(3), pages
                   10091: 13--16. Marcel Hendrix provided helpful comments.
1.53      anton    10092: 
1.78      anton    10093: @menu
                   10094: * Why explicit structure support?::  
                   10095: * Structure Usage::             
                   10096: * Structure Naming Convention::  
                   10097: * Structure Implementation::    
                   10098: * Structure Glossary::          
1.183     anton    10099: * Forth200x Structures::        
1.78      anton    10100: @end menu
1.55      anton    10101: 
1.78      anton    10102: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   10103: @subsection Why explicit structure support?
1.53      anton    10104: 
1.78      anton    10105: @cindex address arithmetic for structures
                   10106: @cindex structures using address arithmetic
                   10107: If we want to use a structure containing several fields, we could simply
                   10108: reserve memory for it, and access the fields using address arithmetic
                   10109: (@pxref{Address arithmetic}). As an example, consider a structure with
                   10110: the following fields
1.57      anton    10111: 
1.78      anton    10112: @table @code
                   10113: @item a
                   10114: is a float
                   10115: @item b
                   10116: is a cell
                   10117: @item c
                   10118: is a float
                   10119: @end table
1.57      anton    10120: 
1.78      anton    10121: Given the (float-aligned) base address of the structure we get the
                   10122: address of the field
1.52      anton    10123: 
1.78      anton    10124: @table @code
                   10125: @item a
                   10126: without doing anything further.
                   10127: @item b
                   10128: with @code{float+}
                   10129: @item c
                   10130: with @code{float+ cell+ faligned}
                   10131: @end table
1.52      anton    10132: 
1.78      anton    10133: It is easy to see that this can become quite tiring. 
1.52      anton    10134: 
1.78      anton    10135: Moreover, it is not very readable, because seeing a
                   10136: @code{cell+} tells us neither which kind of structure is
                   10137: accessed nor what field is accessed; we have to somehow infer the kind
                   10138: of structure, and then look up in the documentation, which field of
                   10139: that structure corresponds to that offset.
1.53      anton    10140: 
1.78      anton    10141: Finally, this kind of address arithmetic also causes maintenance
                   10142: troubles: If you add or delete a field somewhere in the middle of the
                   10143: structure, you have to find and change all computations for the fields
                   10144: afterwards.
1.52      anton    10145: 
1.78      anton    10146: So, instead of using @code{cell+} and friends directly, how
                   10147: about storing the offsets in constants:
1.52      anton    10148: 
1.78      anton    10149: @example
                   10150: 0 constant a-offset
                   10151: 0 float+ constant b-offset
                   10152: 0 float+ cell+ faligned c-offset
                   10153: @end example
1.64      pazsan   10154: 
1.78      anton    10155: Now we can get the address of field @code{x} with @code{x-offset
                   10156: +}. This is much better in all respects. Of course, you still
                   10157: have to change all later offset definitions if you add a field. You can
                   10158: fix this by declaring the offsets in the following way:
1.57      anton    10159: 
1.78      anton    10160: @example
                   10161: 0 constant a-offset
                   10162: a-offset float+ constant b-offset
                   10163: b-offset cell+ faligned constant c-offset
                   10164: @end example
1.57      anton    10165: 
1.78      anton    10166: Since we always use the offsets with @code{+}, we could use a defining
                   10167: word @code{cfield} that includes the @code{+} in the action of the
                   10168: defined word:
1.64      pazsan   10169: 
1.78      anton    10170: @example
                   10171: : cfield ( n "name" -- )
                   10172:     create ,
                   10173: does> ( name execution: addr1 -- addr2 )
                   10174:     @@ + ;
1.64      pazsan   10175: 
1.78      anton    10176: 0 cfield a
                   10177: 0 a float+ cfield b
                   10178: 0 b cell+ faligned cfield c
                   10179: @end example
1.64      pazsan   10180: 
1.78      anton    10181: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64      pazsan   10182: 
1.78      anton    10183: The structure field words now can be used quite nicely. However,
                   10184: their definition is still a bit cumbersome: We have to repeat the
                   10185: name, the information about size and alignment is distributed before
                   10186: and after the field definitions etc.  The structure package presented
                   10187: here addresses these problems.
1.64      pazsan   10188: 
1.78      anton    10189: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   10190: @subsection Structure Usage
                   10191: @cindex structure usage
1.57      anton    10192: 
1.78      anton    10193: @cindex @code{field} usage
                   10194: @cindex @code{struct} usage
                   10195: @cindex @code{end-struct} usage
                   10196: You can define a structure for a (data-less) linked list with:
1.57      anton    10197: @example
1.78      anton    10198: struct
                   10199:     cell% field list-next
                   10200: end-struct list%
1.57      anton    10201: @end example
                   10202: 
1.78      anton    10203: With the address of the list node on the stack, you can compute the
                   10204: address of the field that contains the address of the next node with
                   10205: @code{list-next}. E.g., you can determine the length of a list
                   10206: with:
1.57      anton    10207: 
                   10208: @example
1.78      anton    10209: : list-length ( list -- n )
                   10210: \ "list" is a pointer to the first element of a linked list
                   10211: \ "n" is the length of the list
                   10212:     0 BEGIN ( list1 n1 )
                   10213:         over
                   10214:     WHILE ( list1 n1 )
                   10215:         1+ swap list-next @@ swap
                   10216:     REPEAT
                   10217:     nip ;
1.57      anton    10218: @end example
                   10219: 
1.78      anton    10220: You can reserve memory for a list node in the dictionary with
                   10221: @code{list% %allot}, which leaves the address of the list node on the
                   10222: stack. For the equivalent allocation on the heap you can use @code{list%
                   10223: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   10224: use @code{list% %allocate}). You can get the the size of a list
                   10225: node with @code{list% %size} and its alignment with @code{list%
                   10226: %alignment}.
                   10227: 
                   10228: Note that in ANS Forth the body of a @code{create}d word is
                   10229: @code{aligned} but not necessarily @code{faligned};
                   10230: therefore, if you do a:
1.57      anton    10231: 
                   10232: @example
1.78      anton    10233: create @emph{name} foo% %allot drop
1.57      anton    10234: @end example
                   10235: 
1.78      anton    10236: @noindent
                   10237: then the memory alloted for @code{foo%} is guaranteed to start at the
                   10238: body of @code{@emph{name}} only if @code{foo%} contains only character,
                   10239: cell and double fields.  Therefore, if your structure contains floats,
                   10240: better use
1.57      anton    10241: 
                   10242: @example
1.78      anton    10243: foo% %allot constant @emph{name}
1.57      anton    10244: @end example
                   10245: 
1.78      anton    10246: @cindex structures containing structures
                   10247: You can include a structure @code{foo%} as a field of
                   10248: another structure, like this:
1.65      anton    10249: @example
1.78      anton    10250: struct
                   10251: ...
                   10252:     foo% field ...
                   10253: ...
                   10254: end-struct ...
1.65      anton    10255: @end example
1.52      anton    10256: 
1.78      anton    10257: @cindex structure extension
                   10258: @cindex extended records
                   10259: Instead of starting with an empty structure, you can extend an
                   10260: existing structure. E.g., a plain linked list without data, as defined
                   10261: above, is hardly useful; You can extend it to a linked list of integers,
                   10262: like this:@footnote{This feature is also known as @emph{extended
                   10263: records}. It is the main innovation in the Oberon language; in other
                   10264: words, adding this feature to Modula-2 led Wirth to create a new
                   10265: language, write a new compiler etc.  Adding this feature to Forth just
                   10266: required a few lines of code.}
1.52      anton    10267: 
1.78      anton    10268: @example
                   10269: list%
                   10270:     cell% field intlist-int
                   10271: end-struct intlist%
                   10272: @end example
1.55      anton    10273: 
1.78      anton    10274: @code{intlist%} is a structure with two fields:
                   10275: @code{list-next} and @code{intlist-int}.
1.55      anton    10276: 
1.78      anton    10277: @cindex structures containing arrays
                   10278: You can specify an array type containing @emph{n} elements of
                   10279: type @code{foo%} like this:
1.55      anton    10280: 
                   10281: @example
1.78      anton    10282: foo% @emph{n} *
1.56      anton    10283: @end example
1.55      anton    10284: 
1.78      anton    10285: You can use this array type in any place where you can use a normal
                   10286: type, e.g., when defining a @code{field}, or with
                   10287: @code{%allot}.
                   10288: 
                   10289: @cindex first field optimization
                   10290: The first field is at the base address of a structure and the word for
                   10291: this field (e.g., @code{list-next}) actually does not change the address
                   10292: on the stack. You may be tempted to leave it away in the interest of
                   10293: run-time and space efficiency. This is not necessary, because the
                   10294: structure package optimizes this case: If you compile a first-field
                   10295: words, no code is generated. So, in the interest of readability and
                   10296: maintainability you should include the word for the field when accessing
                   10297: the field.
1.52      anton    10298: 
                   10299: 
1.78      anton    10300: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   10301: @subsection Structure Naming Convention
                   10302: @cindex structure naming convention
1.52      anton    10303: 
1.78      anton    10304: The field names that come to (my) mind are often quite generic, and,
                   10305: if used, would cause frequent name clashes. E.g., many structures
                   10306: probably contain a @code{counter} field. The structure names
                   10307: that come to (my) mind are often also the logical choice for the names
                   10308: of words that create such a structure.
1.52      anton    10309: 
1.78      anton    10310: Therefore, I have adopted the following naming conventions: 
1.52      anton    10311: 
1.78      anton    10312: @itemize @bullet
                   10313: @cindex field naming convention
                   10314: @item
                   10315: The names of fields are of the form
                   10316: @code{@emph{struct}-@emph{field}}, where
                   10317: @code{@emph{struct}} is the basic name of the structure, and
                   10318: @code{@emph{field}} is the basic name of the field. You can
                   10319: think of field words as converting the (address of the)
                   10320: structure into the (address of the) field.
1.52      anton    10321: 
1.78      anton    10322: @cindex structure naming convention
                   10323: @item
                   10324: The names of structures are of the form
                   10325: @code{@emph{struct}%}, where
                   10326: @code{@emph{struct}} is the basic name of the structure.
                   10327: @end itemize
1.52      anton    10328: 
1.78      anton    10329: This naming convention does not work that well for fields of extended
                   10330: structures; e.g., the integer list structure has a field
                   10331: @code{intlist-int}, but has @code{list-next}, not
                   10332: @code{intlist-next}.
1.53      anton    10333: 
1.78      anton    10334: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   10335: @subsection Structure Implementation
                   10336: @cindex structure implementation
                   10337: @cindex implementation of structures
1.52      anton    10338: 
1.78      anton    10339: The central idea in the implementation is to pass the data about the
                   10340: structure being built on the stack, not in some global
                   10341: variable. Everything else falls into place naturally once this design
                   10342: decision is made.
1.53      anton    10343: 
1.78      anton    10344: The type description on the stack is of the form @emph{align
                   10345: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   10346: very simple.
1.53      anton    10347: 
1.78      anton    10348: @code{field} is a defining word that uses @code{Create}
                   10349: and @code{DOES>}. The body of the field contains the offset
                   10350: of the field, and the normal @code{DOES>} action is simply:
1.53      anton    10351: 
                   10352: @example
1.78      anton    10353: @@ +
1.53      anton    10354: @end example
                   10355: 
1.78      anton    10356: @noindent
                   10357: i.e., add the offset to the address, giving the stack effect
                   10358: @i{addr1 -- addr2} for a field.
                   10359: 
                   10360: @cindex first field optimization, implementation
                   10361: This simple structure is slightly complicated by the optimization
                   10362: for fields with offset 0, which requires a different
                   10363: @code{DOES>}-part (because we cannot rely on there being
                   10364: something on the stack if such a field is invoked during
                   10365: compilation). Therefore, we put the different @code{DOES>}-parts
                   10366: in separate words, and decide which one to invoke based on the
                   10367: offset. For a zero offset, the field is basically a noop; it is
                   10368: immediate, and therefore no code is generated when it is compiled.
1.53      anton    10369: 
1.183     anton    10370: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78      anton    10371: @subsection Structure Glossary
                   10372: @cindex structure glossary
1.53      anton    10373: 
1.5       anton    10374: 
1.78      anton    10375: doc-%align
                   10376: doc-%alignment
                   10377: doc-%alloc
                   10378: doc-%allocate
                   10379: doc-%allot
                   10380: doc-cell%
                   10381: doc-char%
                   10382: doc-dfloat%
                   10383: doc-double%
                   10384: doc-end-struct
                   10385: doc-field
                   10386: doc-float%
                   10387: doc-naligned
                   10388: doc-sfloat%
                   10389: doc-%size
                   10390: doc-struct
1.54      anton    10391: 
                   10392: 
1.183     anton    10393: @node Forth200x Structures,  , Structure Glossary, Structures
                   10394: @subsection Forth200x Structures
                   10395: @cindex Structures in Forth200x
                   10396: 
                   10397: The Forth 200x standard defines a slightly less convenient form of
                   10398: structures.  In general (when using @code{field+}, you have to perform
                   10399: the alignment yourself, but there are a number of convenience words
                   10400: (e.g., @code{field:} that perform the alignment for you.
                   10401: 
                   10402: A typical usage example is:
                   10403: 
                   10404: @example
                   10405: 0
                   10406:   field:                   s-a
                   10407:   faligned 2 floats +field s-b
                   10408: constant s-struct
                   10409: @end example
                   10410: 
                   10411: An alternative way of writing this structure is:
                   10412: 
                   10413: @example
                   10414: begin-structure s-struct
                   10415:   field:                   s-a
                   10416:   faligned 2 floats +field s-b
                   10417: end-structure
                   10418: @end example
                   10419: 
                   10420: doc-begin-structure
                   10421: doc-end-structure
                   10422: doc-+field
                   10423: doc-cfield:
                   10424: doc-field:
                   10425: doc-2field:
                   10426: doc-ffield:
                   10427: doc-sffield:
                   10428: doc-dffield:
                   10429: 
1.26      crook    10430: @c -------------------------------------------------------------
1.78      anton    10431: @node Object-oriented Forth, Programming Tools, Structures, Words
                   10432: @section Object-oriented Forth
                   10433: 
                   10434: Gforth comes with three packages for object-oriented programming:
                   10435: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   10436: is preloaded, so you have to @code{include} them before use. The most
                   10437: important differences between these packages (and others) are discussed
                   10438: in @ref{Comparison with other object models}. All packages are written
                   10439: in ANS Forth and can be used with any other ANS Forth.
1.5       anton    10440: 
1.78      anton    10441: @menu
                   10442: * Why object-oriented programming?::  
                   10443: * Object-Oriented Terminology::  
                   10444: * Objects::                     
                   10445: * OOF::                         
                   10446: * Mini-OOF::                    
                   10447: * Comparison with other object models::  
                   10448: @end menu
1.5       anton    10449: 
1.78      anton    10450: @c ----------------------------------------------------------------
                   10451: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   10452: @subsection Why object-oriented programming?
                   10453: @cindex object-oriented programming motivation
                   10454: @cindex motivation for object-oriented programming
1.44      crook    10455: 
1.78      anton    10456: Often we have to deal with several data structures (@emph{objects}),
                   10457: that have to be treated similarly in some respects, but differently in
                   10458: others. Graphical objects are the textbook example: circles, triangles,
                   10459: dinosaurs, icons, and others, and we may want to add more during program
                   10460: development. We want to apply some operations to any graphical object,
                   10461: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   10462: has to do something different for every kind of object.
                   10463: @comment TODO add some other operations eg perimeter, area
                   10464: @comment and tie in to concrete examples later..
1.5       anton    10465: 
1.78      anton    10466: We could implement @code{draw} as a big @code{CASE}
                   10467: control structure that executes the appropriate code depending on the
                   10468: kind of object to be drawn. This would be not be very elegant, and,
                   10469: moreover, we would have to change @code{draw} every time we add
                   10470: a new kind of graphical object (say, a spaceship).
1.44      crook    10471: 
1.78      anton    10472: What we would rather do is: When defining spaceships, we would tell
                   10473: the system: ``Here's how you @code{draw} a spaceship; you figure
                   10474: out the rest''.
1.5       anton    10475: 
1.78      anton    10476: This is the problem that all systems solve that (rightfully) call
                   10477: themselves object-oriented; the object-oriented packages presented here
                   10478: solve this problem (and not much else).
                   10479: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44      crook    10480: 
1.78      anton    10481: @c ------------------------------------------------------------------------
                   10482: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   10483: @subsection Object-Oriented Terminology
                   10484: @cindex object-oriented terminology
                   10485: @cindex terminology for object-oriented programming
1.5       anton    10486: 
1.78      anton    10487: This section is mainly for reference, so you don't have to understand
                   10488: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   10489: short:
1.44      crook    10490: 
1.78      anton    10491: @table @emph
                   10492: @cindex class
                   10493: @item class
                   10494: a data structure definition with some extras.
1.5       anton    10495: 
1.78      anton    10496: @cindex object
                   10497: @item object
                   10498: an instance of the data structure described by the class definition.
1.5       anton    10499: 
1.78      anton    10500: @cindex instance variables
                   10501: @item instance variables
                   10502: fields of the data structure.
1.5       anton    10503: 
1.78      anton    10504: @cindex selector
                   10505: @cindex method selector
                   10506: @cindex virtual function
                   10507: @item selector
                   10508: (or @emph{method selector}) a word (e.g.,
                   10509: @code{draw}) that performs an operation on a variety of data
                   10510: structures (classes). A selector describes @emph{what} operation to
                   10511: perform. In C++ terminology: a (pure) virtual function.
1.5       anton    10512: 
1.78      anton    10513: @cindex method
                   10514: @item method
                   10515: the concrete definition that performs the operation
                   10516: described by the selector for a specific class. A method specifies
                   10517: @emph{how} the operation is performed for a specific class.
1.5       anton    10518: 
1.78      anton    10519: @cindex selector invocation
                   10520: @cindex message send
                   10521: @cindex invoking a selector
                   10522: @item selector invocation
                   10523: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   10524: is used for determining which method is used. In Smalltalk terminology:
                   10525: a message (consisting of the selector and the other arguments) is sent
                   10526: to the object.
1.5       anton    10527: 
1.78      anton    10528: @cindex receiving object
                   10529: @item receiving object
                   10530: the object used for determining the method executed by a selector
                   10531: invocation. In the @file{objects.fs} model, it is the object that is on
                   10532: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   10533: the Smalltalk @emph{message} terminology.)
1.5       anton    10534: 
1.78      anton    10535: @cindex child class
                   10536: @cindex parent class
                   10537: @cindex inheritance
                   10538: @item child class
                   10539: a class that has (@emph{inherits}) all properties (instance variables,
                   10540: selectors, methods) from a @emph{parent class}. In Smalltalk
                   10541: terminology: The subclass inherits from the superclass. In C++
                   10542: terminology: The derived class inherits from the base class.
1.5       anton    10543: 
1.78      anton    10544: @end table
1.5       anton    10545: 
1.78      anton    10546: @c If you wonder about the message sending terminology, it comes from
                   10547: @c a time when each object had it's own task and objects communicated via
                   10548: @c message passing; eventually the Smalltalk developers realized that
                   10549: @c they can do most things through simple (indirect) calls. They kept the
                   10550: @c terminology.
1.5       anton    10551: 
1.78      anton    10552: @c --------------------------------------------------------------
                   10553: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   10554: @subsection The @file{objects.fs} model
                   10555: @cindex objects
                   10556: @cindex object-oriented programming
1.26      crook    10557: 
1.78      anton    10558: @cindex @file{objects.fs}
                   10559: @cindex @file{oof.fs}
1.26      crook    10560: 
1.78      anton    10561: This section describes the @file{objects.fs} package. This material also
                   10562: has been published in M. Anton Ertl,
                   10563: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
                   10564: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
                   10565: 37--43.
                   10566: @c McKewan's and Zsoter's packages
1.26      crook    10567: 
1.78      anton    10568: This section assumes that you have read @ref{Structures}.
1.5       anton    10569: 
1.78      anton    10570: The techniques on which this model is based have been used to implement
                   10571: the parser generator, Gray, and have also been used in Gforth for
                   10572: implementing the various flavours of word lists (hashed or not,
                   10573: case-sensitive or not, special-purpose word lists for locals etc.).
1.5       anton    10574: 
                   10575: 
1.26      crook    10576: @menu
1.78      anton    10577: * Properties of the Objects model::  
                   10578: * Basic Objects Usage::         
                   10579: * The Objects base class::      
                   10580: * Creating objects::            
                   10581: * Object-Oriented Programming Style::  
                   10582: * Class Binding::               
                   10583: * Method conveniences::         
                   10584: * Classes and Scoping::         
                   10585: * Dividing classes::            
                   10586: * Object Interfaces::           
                   10587: * Objects Implementation::      
                   10588: * Objects Glossary::            
1.26      crook    10589: @end menu
1.5       anton    10590: 
1.78      anton    10591: Marcel Hendrix provided helpful comments on this section.
1.5       anton    10592: 
1.78      anton    10593: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   10594: @subsubsection Properties of the @file{objects.fs} model
                   10595: @cindex @file{objects.fs} properties
1.5       anton    10596: 
1.78      anton    10597: @itemize @bullet
                   10598: @item
                   10599: It is straightforward to pass objects on the stack. Passing
                   10600: selectors on the stack is a little less convenient, but possible.
1.44      crook    10601: 
1.78      anton    10602: @item
                   10603: Objects are just data structures in memory, and are referenced by their
                   10604: address. You can create words for objects with normal defining words
                   10605: like @code{constant}. Likewise, there is no difference between instance
                   10606: variables that contain objects and those that contain other data.
1.5       anton    10607: 
1.78      anton    10608: @item
                   10609: Late binding is efficient and easy to use.
1.44      crook    10610: 
1.78      anton    10611: @item
                   10612: It avoids parsing, and thus avoids problems with state-smartness
                   10613: and reduced extensibility; for convenience there are a few parsing
                   10614: words, but they have non-parsing counterparts. There are also a few
                   10615: defining words that parse. This is hard to avoid, because all standard
                   10616: defining words parse (except @code{:noname}); however, such
                   10617: words are not as bad as many other parsing words, because they are not
                   10618: state-smart.
1.5       anton    10619: 
1.78      anton    10620: @item
                   10621: It does not try to incorporate everything. It does a few things and does
                   10622: them well (IMO). In particular, this model was not designed to support
                   10623: information hiding (although it has features that may help); you can use
                   10624: a separate package for achieving this.
1.5       anton    10625: 
1.78      anton    10626: @item
                   10627: It is layered; you don't have to learn and use all features to use this
                   10628: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   10629: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
                   10630: are optional and independent of each other.
1.5       anton    10631: 
1.78      anton    10632: @item
                   10633: An implementation in ANS Forth is available.
1.5       anton    10634: 
1.78      anton    10635: @end itemize
1.5       anton    10636: 
1.44      crook    10637: 
1.78      anton    10638: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   10639: @subsubsection Basic @file{objects.fs} Usage
                   10640: @cindex basic objects usage
                   10641: @cindex objects, basic usage
1.5       anton    10642: 
1.78      anton    10643: You can define a class for graphical objects like this:
1.44      crook    10644: 
1.78      anton    10645: @cindex @code{class} usage
                   10646: @cindex @code{end-class} usage
                   10647: @cindex @code{selector} usage
1.5       anton    10648: @example
1.78      anton    10649: object class \ "object" is the parent class
                   10650:   selector draw ( x y graphical -- )
                   10651: end-class graphical
                   10652: @end example
                   10653: 
                   10654: This code defines a class @code{graphical} with an
                   10655: operation @code{draw}.  We can perform the operation
                   10656: @code{draw} on any @code{graphical} object, e.g.:
                   10657: 
                   10658: @example
                   10659: 100 100 t-rex draw
1.26      crook    10660: @end example
1.5       anton    10661: 
1.78      anton    10662: @noindent
                   10663: where @code{t-rex} is a word (say, a constant) that produces a
                   10664: graphical object.
                   10665: 
                   10666: @comment TODO add a 2nd operation eg perimeter.. and use for
                   10667: @comment a concrete example
1.5       anton    10668: 
1.78      anton    10669: @cindex abstract class
                   10670: How do we create a graphical object? With the present definitions,
                   10671: we cannot create a useful graphical object. The class
                   10672: @code{graphical} describes graphical objects in general, but not
                   10673: any concrete graphical object type (C++ users would call it an
                   10674: @emph{abstract class}); e.g., there is no method for the selector
                   10675: @code{draw} in the class @code{graphical}.
1.5       anton    10676: 
1.78      anton    10677: For concrete graphical objects, we define child classes of the
                   10678: class @code{graphical}, e.g.:
1.5       anton    10679: 
1.78      anton    10680: @cindex @code{overrides} usage
                   10681: @cindex @code{field} usage in class definition
1.26      crook    10682: @example
1.78      anton    10683: graphical class \ "graphical" is the parent class
                   10684:   cell% field circle-radius
1.5       anton    10685: 
1.78      anton    10686: :noname ( x y circle -- )
                   10687:   circle-radius @@ draw-circle ;
                   10688: overrides draw
1.5       anton    10689: 
1.78      anton    10690: :noname ( n-radius circle -- )
                   10691:   circle-radius ! ;
                   10692: overrides construct
1.5       anton    10693: 
1.78      anton    10694: end-class circle
                   10695: @end example
1.44      crook    10696: 
1.78      anton    10697: Here we define a class @code{circle} as a child of @code{graphical},
                   10698: with field @code{circle-radius} (which behaves just like a field
                   10699: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   10700: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   10701: defined in @code{object}, the parent class of @code{graphical}).
1.5       anton    10702: 
1.78      anton    10703: Now we can create a circle on the heap (i.e.,
                   10704: @code{allocate}d memory) with:
1.44      crook    10705: 
1.78      anton    10706: @cindex @code{heap-new} usage
1.5       anton    10707: @example
1.78      anton    10708: 50 circle heap-new constant my-circle
1.5       anton    10709: @end example
                   10710: 
1.78      anton    10711: @noindent
                   10712: @code{heap-new} invokes @code{construct}, thus
                   10713: initializing the field @code{circle-radius} with 50. We can draw
                   10714: this new circle at (100,100) with:
1.5       anton    10715: 
                   10716: @example
1.78      anton    10717: 100 100 my-circle draw
1.5       anton    10718: @end example
                   10719: 
1.78      anton    10720: @cindex selector invocation, restrictions
                   10721: @cindex class definition, restrictions
                   10722: Note: You can only invoke a selector if the object on the TOS
                   10723: (the receiving object) belongs to the class where the selector was
                   10724: defined or one of its descendents; e.g., you can invoke
                   10725: @code{draw} only for objects belonging to @code{graphical}
                   10726: or its descendents (e.g., @code{circle}).  Immediately before
                   10727: @code{end-class}, the search order has to be the same as
                   10728: immediately after @code{class}.
                   10729: 
                   10730: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   10731: @subsubsection The @file{object.fs} base class
                   10732: @cindex @code{object} class
                   10733: 
                   10734: When you define a class, you have to specify a parent class.  So how do
                   10735: you start defining classes? There is one class available from the start:
                   10736: @code{object}. It is ancestor for all classes and so is the
                   10737: only class that has no parent. It has two selectors: @code{construct}
                   10738: and @code{print}.
                   10739: 
                   10740: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   10741: @subsubsection Creating objects
                   10742: @cindex creating objects
                   10743: @cindex object creation
                   10744: @cindex object allocation options
                   10745: 
                   10746: @cindex @code{heap-new} discussion
                   10747: @cindex @code{dict-new} discussion
                   10748: @cindex @code{construct} discussion
                   10749: You can create and initialize an object of a class on the heap with
                   10750: @code{heap-new} ( ... class -- object ) and in the dictionary
                   10751: (allocation with @code{allot}) with @code{dict-new} (
                   10752: ... class -- object ). Both words invoke @code{construct}, which
                   10753: consumes the stack items indicated by "..." above.
                   10754: 
                   10755: @cindex @code{init-object} discussion
                   10756: @cindex @code{class-inst-size} discussion
                   10757: If you want to allocate memory for an object yourself, you can get its
                   10758: alignment and size with @code{class-inst-size 2@@} ( class --
                   10759: align size ). Once you have memory for an object, you can initialize
                   10760: it with @code{init-object} ( ... class object -- );
                   10761: @code{construct} does only a part of the necessary work.
                   10762: 
                   10763: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   10764: @subsubsection Object-Oriented Programming Style
                   10765: @cindex object-oriented programming style
                   10766: @cindex programming style, object-oriented
1.5       anton    10767: 
1.78      anton    10768: This section is not exhaustive.
1.5       anton    10769: 
1.78      anton    10770: @cindex stack effects of selectors
                   10771: @cindex selectors and stack effects
                   10772: In general, it is a good idea to ensure that all methods for the
                   10773: same selector have the same stack effect: when you invoke a selector,
                   10774: you often have no idea which method will be invoked, so, unless all
                   10775: methods have the same stack effect, you will not know the stack effect
                   10776: of the selector invocation.
1.5       anton    10777: 
1.78      anton    10778: One exception to this rule is methods for the selector
                   10779: @code{construct}. We know which method is invoked, because we
                   10780: specify the class to be constructed at the same place. Actually, I
                   10781: defined @code{construct} as a selector only to give the users a
                   10782: convenient way to specify initialization. The way it is used, a
                   10783: mechanism different from selector invocation would be more natural
                   10784: (but probably would take more code and more space to explain).
1.5       anton    10785: 
1.78      anton    10786: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   10787: @subsubsection Class Binding
                   10788: @cindex class binding
                   10789: @cindex early binding
1.5       anton    10790: 
1.78      anton    10791: @cindex late binding
                   10792: Normal selector invocations determine the method at run-time depending
                   10793: on the class of the receiving object. This run-time selection is called
                   10794: @i{late binding}.
1.5       anton    10795: 
1.78      anton    10796: Sometimes it's preferable to invoke a different method. For example,
                   10797: you might want to use the simple method for @code{print}ing
                   10798: @code{object}s instead of the possibly long-winded @code{print} method
                   10799: of the receiver class. You can achieve this by replacing the invocation
                   10800: of @code{print} with:
1.5       anton    10801: 
1.78      anton    10802: @cindex @code{[bind]} usage
1.5       anton    10803: @example
1.78      anton    10804: [bind] object print
1.5       anton    10805: @end example
                   10806: 
1.78      anton    10807: @noindent
                   10808: in compiled code or:
                   10809: 
                   10810: @cindex @code{bind} usage
1.5       anton    10811: @example
1.78      anton    10812: bind object print
1.5       anton    10813: @end example
                   10814: 
1.78      anton    10815: @cindex class binding, alternative to
                   10816: @noindent
                   10817: in interpreted code. Alternatively, you can define the method with a
                   10818: name (e.g., @code{print-object}), and then invoke it through the
                   10819: name. Class binding is just a (often more convenient) way to achieve
                   10820: the same effect; it avoids name clutter and allows you to invoke
                   10821: methods directly without naming them first.
1.5       anton    10822: 
1.78      anton    10823: @cindex superclass binding
                   10824: @cindex parent class binding
                   10825: A frequent use of class binding is this: When we define a method
                   10826: for a selector, we often want the method to do what the selector does
                   10827: in the parent class, and a little more. There is a special word for
                   10828: this purpose: @code{[parent]}; @code{[parent]
                   10829: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   10830: selector}}, where @code{@emph{parent}} is the parent
                   10831: class of the current class. E.g., a method definition might look like:
1.44      crook    10832: 
1.78      anton    10833: @cindex @code{[parent]} usage
                   10834: @example
                   10835: :noname
                   10836:   dup [parent] foo \ do parent's foo on the receiving object
                   10837:   ... \ do some more
                   10838: ; overrides foo
                   10839: @end example
1.6       pazsan   10840: 
1.78      anton    10841: @cindex class binding as optimization
                   10842: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10843: March 1997), Andrew McKewan presents class binding as an optimization
                   10844: technique. I recommend not using it for this purpose unless you are in
                   10845: an emergency. Late binding is pretty fast with this model anyway, so the
                   10846: benefit of using class binding is small; the cost of using class binding
                   10847: where it is not appropriate is reduced maintainability.
1.44      crook    10848: 
1.78      anton    10849: While we are at programming style questions: You should bind
                   10850: selectors only to ancestor classes of the receiving object. E.g., say,
                   10851: you know that the receiving object is of class @code{foo} or its
                   10852: descendents; then you should bind only to @code{foo} and its
                   10853: ancestors.
1.12      anton    10854: 
1.78      anton    10855: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10856: @subsubsection Method conveniences
                   10857: @cindex method conveniences
1.44      crook    10858: 
1.78      anton    10859: In a method you usually access the receiving object pretty often.  If
                   10860: you define the method as a plain colon definition (e.g., with
                   10861: @code{:noname}), you may have to do a lot of stack
                   10862: gymnastics. To avoid this, you can define the method with @code{m:
                   10863: ... ;m}. E.g., you could define the method for
                   10864: @code{draw}ing a @code{circle} with
1.6       pazsan   10865: 
1.78      anton    10866: @cindex @code{this} usage
                   10867: @cindex @code{m:} usage
                   10868: @cindex @code{;m} usage
                   10869: @example
                   10870: m: ( x y circle -- )
                   10871:   ( x y ) this circle-radius @@ draw-circle ;m
                   10872: @end example
1.6       pazsan   10873: 
1.78      anton    10874: @cindex @code{exit} in @code{m: ... ;m}
                   10875: @cindex @code{exitm} discussion
                   10876: @cindex @code{catch} in @code{m: ... ;m}
                   10877: When this method is executed, the receiver object is removed from the
                   10878: stack; you can access it with @code{this} (admittedly, in this
                   10879: example the use of @code{m: ... ;m} offers no advantage). Note
                   10880: that I specify the stack effect for the whole method (i.e. including
                   10881: the receiver object), not just for the code between @code{m:}
                   10882: and @code{;m}. You cannot use @code{exit} in
                   10883: @code{m:...;m}; instead, use
                   10884: @code{exitm}.@footnote{Moreover, for any word that calls
                   10885: @code{catch} and was defined before loading
                   10886: @code{objects.fs}, you have to redefine it like I redefined
                   10887: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12      anton    10888: 
1.78      anton    10889: @cindex @code{inst-var} usage
                   10890: You will frequently use sequences of the form @code{this
                   10891: @emph{field}} (in the example above: @code{this
                   10892: circle-radius}). If you use the field only in this way, you can
                   10893: define it with @code{inst-var} and eliminate the
                   10894: @code{this} before the field name. E.g., the @code{circle}
                   10895: class above could also be defined with:
1.6       pazsan   10896: 
1.78      anton    10897: @example
                   10898: graphical class
                   10899:   cell% inst-var radius
1.6       pazsan   10900: 
1.78      anton    10901: m: ( x y circle -- )
                   10902:   radius @@ draw-circle ;m
                   10903: overrides draw
1.6       pazsan   10904: 
1.78      anton    10905: m: ( n-radius circle -- )
                   10906:   radius ! ;m
                   10907: overrides construct
1.6       pazsan   10908: 
1.78      anton    10909: end-class circle
                   10910: @end example
1.6       pazsan   10911: 
1.78      anton    10912: @code{radius} can only be used in @code{circle} and its
                   10913: descendent classes and inside @code{m:...;m}.
1.6       pazsan   10914: 
1.78      anton    10915: @cindex @code{inst-value} usage
                   10916: You can also define fields with @code{inst-value}, which is
                   10917: to @code{inst-var} what @code{value} is to
                   10918: @code{variable}.  You can change the value of such a field with
                   10919: @code{[to-inst]}.  E.g., we could also define the class
                   10920: @code{circle} like this:
1.44      crook    10921: 
1.78      anton    10922: @example
                   10923: graphical class
                   10924:   inst-value radius
1.6       pazsan   10925: 
1.78      anton    10926: m: ( x y circle -- )
                   10927:   radius draw-circle ;m
                   10928: overrides draw
1.44      crook    10929: 
1.78      anton    10930: m: ( n-radius circle -- )
                   10931:   [to-inst] radius ;m
                   10932: overrides construct
1.6       pazsan   10933: 
1.78      anton    10934: end-class circle
                   10935: @end example
1.6       pazsan   10936: 
1.78      anton    10937: @c !! :m is easy to confuse with m:.  Another name would be better.
1.6       pazsan   10938: 
1.78      anton    10939: @c Finally, you can define named methods with @code{:m}.  One use of this
                   10940: @c feature is the definition of words that occur only in one class and are
                   10941: @c not intended to be overridden, but which still need method context
                   10942: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   10943: @c would be bound frequently, if defined anonymously.
1.6       pazsan   10944: 
                   10945: 
1.78      anton    10946: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
                   10947: @subsubsection Classes and Scoping
                   10948: @cindex classes and scoping
                   10949: @cindex scoping and classes
1.6       pazsan   10950: 
1.78      anton    10951: Inheritance is frequent, unlike structure extension. This exacerbates
                   10952: the problem with the field name convention (@pxref{Structure Naming
                   10953: Convention}): One always has to remember in which class the field was
                   10954: originally defined; changing a part of the class structure would require
                   10955: changes for renaming in otherwise unaffected code.
1.6       pazsan   10956: 
1.78      anton    10957: @cindex @code{inst-var} visibility
                   10958: @cindex @code{inst-value} visibility
                   10959: To solve this problem, I added a scoping mechanism (which was not in my
                   10960: original charter): A field defined with @code{inst-var} (or
                   10961: @code{inst-value}) is visible only in the class where it is defined and in
                   10962: the descendent classes of this class.  Using such fields only makes
                   10963: sense in @code{m:}-defined methods in these classes anyway.
1.6       pazsan   10964: 
1.78      anton    10965: This scoping mechanism allows us to use the unadorned field name,
                   10966: because name clashes with unrelated words become much less likely.
1.6       pazsan   10967: 
1.78      anton    10968: @cindex @code{protected} discussion
                   10969: @cindex @code{private} discussion
                   10970: Once we have this mechanism, we can also use it for controlling the
                   10971: visibility of other words: All words defined after
                   10972: @code{protected} are visible only in the current class and its
                   10973: descendents. @code{public} restores the compilation
                   10974: (i.e. @code{current}) word list that was in effect before. If you
                   10975: have several @code{protected}s without an intervening
                   10976: @code{public} or @code{set-current}, @code{public}
                   10977: will restore the compilation word list in effect before the first of
                   10978: these @code{protected}s.
1.6       pazsan   10979: 
1.78      anton    10980: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   10981: @subsubsection Dividing classes
                   10982: @cindex Dividing classes
                   10983: @cindex @code{methods}...@code{end-methods}
1.6       pazsan   10984: 
1.78      anton    10985: You may want to do the definition of methods separate from the
                   10986: definition of the class, its selectors, fields, and instance variables,
                   10987: i.e., separate the implementation from the definition.  You can do this
                   10988: in the following way:
1.6       pazsan   10989: 
1.78      anton    10990: @example
                   10991: graphical class
                   10992:   inst-value radius
                   10993: end-class circle
1.6       pazsan   10994: 
1.78      anton    10995: ... \ do some other stuff
1.6       pazsan   10996: 
1.78      anton    10997: circle methods \ now we are ready
1.44      crook    10998: 
1.78      anton    10999: m: ( x y circle -- )
                   11000:   radius draw-circle ;m
                   11001: overrides draw
1.6       pazsan   11002: 
1.78      anton    11003: m: ( n-radius circle -- )
                   11004:   [to-inst] radius ;m
                   11005: overrides construct
1.44      crook    11006: 
1.78      anton    11007: end-methods
                   11008: @end example
1.7       pazsan   11009: 
1.78      anton    11010: You can use several @code{methods}...@code{end-methods} sections.  The
                   11011: only things you can do to the class in these sections are: defining
                   11012: methods, and overriding the class's selectors.  You must not define new
                   11013: selectors or fields.
1.7       pazsan   11014: 
1.78      anton    11015: Note that you often have to override a selector before using it.  In
                   11016: particular, you usually have to override @code{construct} with a new
                   11017: method before you can invoke @code{heap-new} and friends.  E.g., you
                   11018: must not create a circle before the @code{overrides construct} sequence
                   11019: in the example above.
1.7       pazsan   11020: 
1.78      anton    11021: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
                   11022: @subsubsection Object Interfaces
                   11023: @cindex object interfaces
                   11024: @cindex interfaces for objects
1.7       pazsan   11025: 
1.78      anton    11026: In this model you can only call selectors defined in the class of the
                   11027: receiving objects or in one of its ancestors. If you call a selector
                   11028: with a receiving object that is not in one of these classes, the
                   11029: result is undefined; if you are lucky, the program crashes
                   11030: immediately.
1.7       pazsan   11031: 
1.78      anton    11032: @cindex selectors common to hardly-related classes
                   11033: Now consider the case when you want to have a selector (or several)
                   11034: available in two classes: You would have to add the selector to a
                   11035: common ancestor class, in the worst case to @code{object}. You
                   11036: may not want to do this, e.g., because someone else is responsible for
                   11037: this ancestor class.
1.7       pazsan   11038: 
1.78      anton    11039: The solution for this problem is interfaces. An interface is a
                   11040: collection of selectors. If a class implements an interface, the
                   11041: selectors become available to the class and its descendents. A class
                   11042: can implement an unlimited number of interfaces. For the problem
                   11043: discussed above, we would define an interface for the selector(s), and
                   11044: both classes would implement the interface.
1.7       pazsan   11045: 
1.78      anton    11046: As an example, consider an interface @code{storage} for
                   11047: writing objects to disk and getting them back, and a class
                   11048: @code{foo} that implements it. The code would look like this:
1.7       pazsan   11049: 
1.78      anton    11050: @cindex @code{interface} usage
                   11051: @cindex @code{end-interface} usage
                   11052: @cindex @code{implementation} usage
                   11053: @example
                   11054: interface
                   11055:   selector write ( file object -- )
                   11056:   selector read1 ( file object -- )
                   11057: end-interface storage
1.13      pazsan   11058: 
1.78      anton    11059: bar class
                   11060:   storage implementation
1.13      pazsan   11061: 
1.78      anton    11062: ... overrides write
                   11063: ... overrides read1
                   11064: ...
                   11065: end-class foo
                   11066: @end example
1.13      pazsan   11067: 
1.78      anton    11068: @noindent
                   11069: (I would add a word @code{read} @i{( file -- object )} that uses
                   11070: @code{read1} internally, but that's beyond the point illustrated
                   11071: here.)
1.13      pazsan   11072: 
1.78      anton    11073: Note that you cannot use @code{protected} in an interface; and
                   11074: of course you cannot define fields.
1.13      pazsan   11075: 
1.78      anton    11076: In the Neon model, all selectors are available for all classes;
                   11077: therefore it does not need interfaces. The price you pay in this model
                   11078: is slower late binding, and therefore, added complexity to avoid late
                   11079: binding.
1.13      pazsan   11080: 
1.78      anton    11081: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   11082: @subsubsection @file{objects.fs} Implementation
                   11083: @cindex @file{objects.fs} implementation
1.13      pazsan   11084: 
1.78      anton    11085: @cindex @code{object-map} discussion
                   11086: An object is a piece of memory, like one of the data structures
                   11087: described with @code{struct...end-struct}. It has a field
                   11088: @code{object-map} that points to the method map for the object's
                   11089: class.
1.13      pazsan   11090: 
1.78      anton    11091: @cindex method map
                   11092: @cindex virtual function table
                   11093: The @emph{method map}@footnote{This is Self terminology; in C++
                   11094: terminology: virtual function table.} is an array that contains the
                   11095: execution tokens (@i{xt}s) of the methods for the object's class. Each
                   11096: selector contains an offset into a method map.
1.13      pazsan   11097: 
1.78      anton    11098: @cindex @code{selector} implementation, class
                   11099: @code{selector} is a defining word that uses
                   11100: @code{CREATE} and @code{DOES>}. The body of the
                   11101: selector contains the offset; the @code{DOES>} action for a
                   11102: class selector is, basically:
1.8       pazsan   11103: 
                   11104: @example
1.78      anton    11105: ( object addr ) @@ over object-map @@ + @@ execute
1.13      pazsan   11106: @end example
                   11107: 
1.78      anton    11108: Since @code{object-map} is the first field of the object, it
                   11109: does not generate any code. As you can see, calling a selector has a
                   11110: small, constant cost.
1.26      crook    11111: 
1.78      anton    11112: @cindex @code{current-interface} discussion
                   11113: @cindex class implementation and representation
                   11114: A class is basically a @code{struct} combined with a method
                   11115: map. During the class definition the alignment and size of the class
                   11116: are passed on the stack, just as with @code{struct}s, so
                   11117: @code{field} can also be used for defining class
                   11118: fields. However, passing more items on the stack would be
                   11119: inconvenient, so @code{class} builds a data structure in memory,
                   11120: which is accessed through the variable
                   11121: @code{current-interface}. After its definition is complete, the
                   11122: class is represented on the stack by a pointer (e.g., as parameter for
                   11123: a child class definition).
1.26      crook    11124: 
1.78      anton    11125: A new class starts off with the alignment and size of its parent,
                   11126: and a copy of the parent's method map. Defining new fields extends the
                   11127: size and alignment; likewise, defining new selectors extends the
                   11128: method map. @code{overrides} just stores a new @i{xt} in the method
                   11129: map at the offset given by the selector.
1.13      pazsan   11130: 
1.78      anton    11131: @cindex class binding, implementation
                   11132: Class binding just gets the @i{xt} at the offset given by the selector
                   11133: from the class's method map and @code{compile,}s (in the case of
                   11134: @code{[bind]}) it.
1.13      pazsan   11135: 
1.78      anton    11136: @cindex @code{this} implementation
                   11137: @cindex @code{catch} and @code{this}
                   11138: @cindex @code{this} and @code{catch}
                   11139: I implemented @code{this} as a @code{value}. At the
                   11140: start of an @code{m:...;m} method the old @code{this} is
                   11141: stored to the return stack and restored at the end; and the object on
                   11142: the TOS is stored @code{TO this}. This technique has one
                   11143: disadvantage: If the user does not leave the method via
                   11144: @code{;m}, but via @code{throw} or @code{exit},
                   11145: @code{this} is not restored (and @code{exit} may
                   11146: crash). To deal with the @code{throw} problem, I have redefined
                   11147: @code{catch} to save and restore @code{this}; the same
                   11148: should be done with any word that can catch an exception. As for
                   11149: @code{exit}, I simply forbid it (as a replacement, there is
                   11150: @code{exitm}).
1.13      pazsan   11151: 
1.78      anton    11152: @cindex @code{inst-var} implementation
                   11153: @code{inst-var} is just the same as @code{field}, with
                   11154: a different @code{DOES>} action:
1.13      pazsan   11155: @example
1.78      anton    11156: @@ this +
1.8       pazsan   11157: @end example
1.78      anton    11158: Similar for @code{inst-value}.
1.8       pazsan   11159: 
1.78      anton    11160: @cindex class scoping implementation
                   11161: Each class also has a word list that contains the words defined with
                   11162: @code{inst-var} and @code{inst-value}, and its protected
                   11163: words. It also has a pointer to its parent. @code{class} pushes
                   11164: the word lists of the class and all its ancestors onto the search order stack,
                   11165: and @code{end-class} drops them.
1.20      pazsan   11166: 
1.78      anton    11167: @cindex interface implementation
                   11168: An interface is like a class without fields, parent and protected
                   11169: words; i.e., it just has a method map. If a class implements an
                   11170: interface, its method map contains a pointer to the method map of the
                   11171: interface. The positive offsets in the map are reserved for class
                   11172: methods, therefore interface map pointers have negative
                   11173: offsets. Interfaces have offsets that are unique throughout the
                   11174: system, unlike class selectors, whose offsets are only unique for the
                   11175: classes where the selector is available (invokable).
1.20      pazsan   11176: 
1.78      anton    11177: This structure means that interface selectors have to perform one
                   11178: indirection more than class selectors to find their method. Their body
                   11179: contains the interface map pointer offset in the class method map, and
                   11180: the method offset in the interface method map. The
                   11181: @code{does>} action for an interface selector is, basically:
1.20      pazsan   11182: 
                   11183: @example
1.78      anton    11184: ( object selector-body )
                   11185: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   11186: swap object-map @@ + @@ ( object selector-body map )
                   11187: swap selector-offset @@ + @@ execute
1.20      pazsan   11188: @end example
                   11189: 
1.78      anton    11190: where @code{object-map} and @code{selector-offset} are
                   11191: first fields and generate no code.
1.20      pazsan   11192: 
1.78      anton    11193: As a concrete example, consider the following code:
1.20      pazsan   11194: 
                   11195: @example
1.78      anton    11196: interface
                   11197:   selector if1sel1
                   11198:   selector if1sel2
                   11199: end-interface if1
1.20      pazsan   11200: 
1.78      anton    11201: object class
                   11202:   if1 implementation
                   11203:   selector cl1sel1
                   11204:   cell% inst-var cl1iv1
1.20      pazsan   11205: 
1.78      anton    11206: ' m1 overrides construct
                   11207: ' m2 overrides if1sel1
                   11208: ' m3 overrides if1sel2
                   11209: ' m4 overrides cl1sel2
                   11210: end-class cl1
1.20      pazsan   11211: 
1.78      anton    11212: create obj1 object dict-new drop
                   11213: create obj2 cl1    dict-new drop
                   11214: @end example
1.20      pazsan   11215: 
1.78      anton    11216: The data structure created by this code (including the data structure
                   11217: for @code{object}) is shown in the
                   11218: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
                   11219: @comment TODO add this diagram..
1.20      pazsan   11220: 
1.78      anton    11221: @node Objects Glossary,  , Objects Implementation, Objects
                   11222: @subsubsection @file{objects.fs} Glossary
                   11223: @cindex @file{objects.fs} Glossary
1.20      pazsan   11224: 
                   11225: 
1.78      anton    11226: doc---objects-bind
                   11227: doc---objects-<bind>
                   11228: doc---objects-bind'
                   11229: doc---objects-[bind]
                   11230: doc---objects-class
                   11231: doc---objects-class->map
                   11232: doc---objects-class-inst-size
                   11233: doc---objects-class-override!
1.79      anton    11234: doc---objects-class-previous
                   11235: doc---objects-class>order
1.78      anton    11236: doc---objects-construct
                   11237: doc---objects-current'
                   11238: doc---objects-[current]
                   11239: doc---objects-current-interface
                   11240: doc---objects-dict-new
                   11241: doc---objects-end-class
                   11242: doc---objects-end-class-noname
                   11243: doc---objects-end-interface
                   11244: doc---objects-end-interface-noname
                   11245: doc---objects-end-methods
                   11246: doc---objects-exitm
                   11247: doc---objects-heap-new
                   11248: doc---objects-implementation
                   11249: doc---objects-init-object
                   11250: doc---objects-inst-value
                   11251: doc---objects-inst-var
                   11252: doc---objects-interface
                   11253: doc---objects-m:
                   11254: doc---objects-:m
                   11255: doc---objects-;m
                   11256: doc---objects-method
                   11257: doc---objects-methods
                   11258: doc---objects-object
                   11259: doc---objects-overrides
                   11260: doc---objects-[parent]
                   11261: doc---objects-print
                   11262: doc---objects-protected
                   11263: doc---objects-public
                   11264: doc---objects-selector
                   11265: doc---objects-this
                   11266: doc---objects-<to-inst>
                   11267: doc---objects-[to-inst]
                   11268: doc---objects-to-this
                   11269: doc---objects-xt-new
1.20      pazsan   11270: 
                   11271: 
1.78      anton    11272: @c -------------------------------------------------------------
                   11273: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   11274: @subsection The @file{oof.fs} model
                   11275: @cindex oof
                   11276: @cindex object-oriented programming
1.20      pazsan   11277: 
1.78      anton    11278: @cindex @file{objects.fs}
                   11279: @cindex @file{oof.fs}
1.20      pazsan   11280: 
1.78      anton    11281: This section describes the @file{oof.fs} package.
1.20      pazsan   11282: 
1.78      anton    11283: The package described in this section has been used in bigFORTH since 1991, and
                   11284: used for two large applications: a chromatographic system used to
                   11285: create new medicaments, and a graphic user interface library (MINOS).
1.20      pazsan   11286: 
1.78      anton    11287: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   11288: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   11289: 10(2), 1994.
1.20      pazsan   11290: 
1.78      anton    11291: @menu
                   11292: * Properties of the OOF model::  
                   11293: * Basic OOF Usage::             
                   11294: * The OOF base class::          
                   11295: * Class Declaration::           
                   11296: * Class Implementation::        
                   11297: @end menu
1.20      pazsan   11298: 
1.78      anton    11299: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   11300: @subsubsection Properties of the @file{oof.fs} model
                   11301: @cindex @file{oof.fs} properties
1.20      pazsan   11302: 
1.78      anton    11303: @itemize @bullet
                   11304: @item
                   11305: This model combines object oriented programming with information
                   11306: hiding. It helps you writing large application, where scoping is
                   11307: necessary, because it provides class-oriented scoping.
1.20      pazsan   11308: 
1.78      anton    11309: @item
                   11310: Named objects, object pointers, and object arrays can be created,
                   11311: selector invocation uses the ``object selector'' syntax. Selector invocation
                   11312: to objects and/or selectors on the stack is a bit less convenient, but
                   11313: possible.
1.44      crook    11314: 
1.78      anton    11315: @item
                   11316: Selector invocation and instance variable usage of the active object is
                   11317: straightforward, since both make use of the active object.
1.44      crook    11318: 
1.78      anton    11319: @item
                   11320: Late binding is efficient and easy to use.
1.20      pazsan   11321: 
1.78      anton    11322: @item
                   11323: State-smart objects parse selectors. However, extensibility is provided
                   11324: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20      pazsan   11325: 
1.78      anton    11326: @item
                   11327: An implementation in ANS Forth is available.
1.20      pazsan   11328: 
1.78      anton    11329: @end itemize
1.23      crook    11330: 
                   11331: 
1.78      anton    11332: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   11333: @subsubsection Basic @file{oof.fs} Usage
                   11334: @cindex @file{oof.fs} usage
1.23      crook    11335: 
1.78      anton    11336: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23      crook    11337: 
1.78      anton    11338: You can define a class for graphical objects like this:
1.23      crook    11339: 
1.78      anton    11340: @cindex @code{class} usage
                   11341: @cindex @code{class;} usage
                   11342: @cindex @code{method} usage
                   11343: @example
                   11344: object class graphical \ "object" is the parent class
1.139     pazsan   11345:   method draw ( x y -- )
1.78      anton    11346: class;
                   11347: @end example
1.23      crook    11348: 
1.78      anton    11349: This code defines a class @code{graphical} with an
                   11350: operation @code{draw}.  We can perform the operation
                   11351: @code{draw} on any @code{graphical} object, e.g.:
1.23      crook    11352: 
1.78      anton    11353: @example
                   11354: 100 100 t-rex draw
                   11355: @end example
1.23      crook    11356: 
1.78      anton    11357: @noindent
                   11358: where @code{t-rex} is an object or object pointer, created with e.g.
                   11359: @code{graphical : t-rex}.
1.23      crook    11360: 
1.78      anton    11361: @cindex abstract class
                   11362: How do we create a graphical object? With the present definitions,
                   11363: we cannot create a useful graphical object. The class
                   11364: @code{graphical} describes graphical objects in general, but not
                   11365: any concrete graphical object type (C++ users would call it an
                   11366: @emph{abstract class}); e.g., there is no method for the selector
                   11367: @code{draw} in the class @code{graphical}.
1.23      crook    11368: 
1.78      anton    11369: For concrete graphical objects, we define child classes of the
                   11370: class @code{graphical}, e.g.:
1.23      crook    11371: 
1.78      anton    11372: @example
                   11373: graphical class circle \ "graphical" is the parent class
                   11374:   cell var circle-radius
                   11375: how:
                   11376:   : draw ( x y -- )
                   11377:     circle-radius @@ draw-circle ;
1.23      crook    11378: 
1.139     pazsan   11379:   : init ( n-radius -- )
1.78      anton    11380:     circle-radius ! ;
                   11381: class;
                   11382: @end example
1.1       anton    11383: 
1.78      anton    11384: Here we define a class @code{circle} as a child of @code{graphical},
                   11385: with a field @code{circle-radius}; it defines new methods for the
                   11386: selectors @code{draw} and @code{init} (@code{init} is defined in
                   11387: @code{object}, the parent class of @code{graphical}).
1.1       anton    11388: 
1.78      anton    11389: Now we can create a circle in the dictionary with:
1.1       anton    11390: 
1.78      anton    11391: @example
                   11392: 50 circle : my-circle
                   11393: @end example
1.21      crook    11394: 
1.78      anton    11395: @noindent
                   11396: @code{:} invokes @code{init}, thus initializing the field
                   11397: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   11398: with:
1.1       anton    11399: 
1.78      anton    11400: @example
                   11401: 100 100 my-circle draw
                   11402: @end example
1.1       anton    11403: 
1.78      anton    11404: @cindex selector invocation, restrictions
                   11405: @cindex class definition, restrictions
                   11406: Note: You can only invoke a selector if the receiving object belongs to
                   11407: the class where the selector was defined or one of its descendents;
                   11408: e.g., you can invoke @code{draw} only for objects belonging to
                   11409: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   11410: mechanism will check if you try to invoke a selector that is not
                   11411: defined in this class hierarchy, so you'll get an error at compilation
                   11412: time.
1.1       anton    11413: 
                   11414: 
1.78      anton    11415: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   11416: @subsubsection The @file{oof.fs} base class
                   11417: @cindex @file{oof.fs} base class
1.1       anton    11418: 
1.78      anton    11419: When you define a class, you have to specify a parent class.  So how do
                   11420: you start defining classes? There is one class available from the start:
                   11421: @code{object}. You have to use it as ancestor for all classes. It is the
                   11422: only class that has no parent. Classes are also objects, except that
                   11423: they don't have instance variables; class manipulation such as
                   11424: inheritance or changing definitions of a class is handled through
                   11425: selectors of the class @code{object}.
1.1       anton    11426: 
1.78      anton    11427: @code{object} provides a number of selectors:
1.1       anton    11428: 
1.78      anton    11429: @itemize @bullet
                   11430: @item
                   11431: @code{class} for subclassing, @code{definitions} to add definitions
                   11432: later on, and @code{class?} to get type informations (is the class a
                   11433: subclass of the class passed on the stack?).
1.1       anton    11434: 
1.78      anton    11435: doc---object-class
                   11436: doc---object-definitions
                   11437: doc---object-class?
1.1       anton    11438: 
                   11439: 
1.26      crook    11440: @item
1.78      anton    11441: @code{init} and @code{dispose} as constructor and destructor of the
                   11442: object. @code{init} is invocated after the object's memory is allocated,
                   11443: while @code{dispose} also handles deallocation. Thus if you redefine
                   11444: @code{dispose}, you have to call the parent's dispose with @code{super
                   11445: dispose}, too.
                   11446: 
                   11447: doc---object-init
                   11448: doc---object-dispose
                   11449: 
1.1       anton    11450: 
1.26      crook    11451: @item
1.78      anton    11452: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   11453: @code{[]} to create named and unnamed objects and object arrays or
                   11454: object pointers.
                   11455: 
                   11456: doc---object-new
                   11457: doc---object-new[]
                   11458: doc---object-:
                   11459: doc---object-ptr
                   11460: doc---object-asptr
                   11461: doc---object-[]
                   11462: 
1.1       anton    11463: 
1.26      crook    11464: @item
1.78      anton    11465: @code{::} and @code{super} for explicit scoping. You should use explicit
                   11466: scoping only for super classes or classes with the same set of instance
                   11467: variables. Explicitly-scoped selectors use early binding.
1.21      crook    11468: 
1.78      anton    11469: doc---object-::
                   11470: doc---object-super
1.21      crook    11471: 
                   11472: 
1.26      crook    11473: @item
1.78      anton    11474: @code{self} to get the address of the object
1.21      crook    11475: 
1.78      anton    11476: doc---object-self
1.21      crook    11477: 
                   11478: 
1.78      anton    11479: @item
                   11480: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   11481: pointers and instance defers.
1.21      crook    11482: 
1.78      anton    11483: doc---object-bind
                   11484: doc---object-bound
                   11485: doc---object-link
                   11486: doc---object-is
1.21      crook    11487: 
                   11488: 
1.78      anton    11489: @item
                   11490: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   11491: form the stack, and @code{postpone} to generate selector invocation code.
1.21      crook    11492: 
1.78      anton    11493: doc---object-'
                   11494: doc---object-postpone
1.21      crook    11495: 
                   11496: 
1.78      anton    11497: @item
                   11498: @code{with} and @code{endwith} to select the active object from the
                   11499: stack, and enable its scope. Using @code{with} and @code{endwith}
                   11500: also allows you to create code using selector @code{postpone} without being
                   11501: trapped by the state-smart objects.
1.21      crook    11502: 
1.78      anton    11503: doc---object-with
                   11504: doc---object-endwith
1.21      crook    11505: 
                   11506: 
1.78      anton    11507: @end itemize
1.21      crook    11508: 
1.78      anton    11509: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   11510: @subsubsection Class Declaration
                   11511: @cindex class declaration
1.21      crook    11512: 
1.78      anton    11513: @itemize @bullet
                   11514: @item
                   11515: Instance variables
1.21      crook    11516: 
1.78      anton    11517: doc---oof-var
1.21      crook    11518: 
                   11519: 
1.78      anton    11520: @item
                   11521: Object pointers
1.21      crook    11522: 
1.78      anton    11523: doc---oof-ptr
                   11524: doc---oof-asptr
1.21      crook    11525: 
                   11526: 
1.78      anton    11527: @item
                   11528: Instance defers
1.21      crook    11529: 
1.78      anton    11530: doc---oof-defer
1.21      crook    11531: 
                   11532: 
1.78      anton    11533: @item
                   11534: Method selectors
1.21      crook    11535: 
1.78      anton    11536: doc---oof-early
                   11537: doc---oof-method
1.21      crook    11538: 
                   11539: 
1.78      anton    11540: @item
                   11541: Class-wide variables
1.21      crook    11542: 
1.78      anton    11543: doc---oof-static
1.21      crook    11544: 
                   11545: 
1.78      anton    11546: @item
                   11547: End declaration
1.1       anton    11548: 
1.78      anton    11549: doc---oof-how:
                   11550: doc---oof-class;
1.21      crook    11551: 
                   11552: 
1.78      anton    11553: @end itemize
1.21      crook    11554: 
1.78      anton    11555: @c -------------------------------------------------------------
                   11556: @node Class Implementation,  , Class Declaration, OOF
                   11557: @subsubsection Class Implementation
                   11558: @cindex class implementation
1.21      crook    11559: 
1.78      anton    11560: @c -------------------------------------------------------------
                   11561: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   11562: @subsection The @file{mini-oof.fs} model
                   11563: @cindex mini-oof
1.21      crook    11564: 
1.78      anton    11565: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79      anton    11566: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78      anton    11567: and reduces to the bare minimum of features. This is based on a posting
                   11568: of Bernd Paysan in comp.lang.forth.
1.21      crook    11569: 
1.78      anton    11570: @menu
                   11571: * Basic Mini-OOF Usage::        
                   11572: * Mini-OOF Example::            
                   11573: * Mini-OOF Implementation::     
                   11574: @end menu
1.21      crook    11575: 
1.78      anton    11576: @c -------------------------------------------------------------
                   11577: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
                   11578: @subsubsection Basic @file{mini-oof.fs} Usage
                   11579: @cindex mini-oof usage
1.21      crook    11580: 
1.78      anton    11581: There is a base class (@code{class}, which allocates one cell for the
                   11582: object pointer) plus seven other words: to define a method, a variable,
                   11583: a class; to end a class, to resolve binding, to allocate an object and
                   11584: to compile a class method.
                   11585: @comment TODO better description of the last one
1.26      crook    11586: 
1.21      crook    11587: 
1.78      anton    11588: doc-object
                   11589: doc-method
                   11590: doc-var
                   11591: doc-class
                   11592: doc-end-class
                   11593: doc-defines
                   11594: doc-new
                   11595: doc-::
1.21      crook    11596: 
                   11597: 
                   11598: 
1.78      anton    11599: @c -------------------------------------------------------------
                   11600: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   11601: @subsubsection Mini-OOF Example
                   11602: @cindex mini-oof example
1.1       anton    11603: 
1.78      anton    11604: A short example shows how to use this package. This example, in slightly
                   11605: extended form, is supplied as @file{moof-exm.fs}
                   11606: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20      pazsan   11607: 
1.26      crook    11608: @example
1.78      anton    11609: object class
                   11610:   method init
                   11611:   method draw
                   11612: end-class graphical
1.26      crook    11613: @end example
1.20      pazsan   11614: 
1.78      anton    11615: This code defines a class @code{graphical} with an
                   11616: operation @code{draw}.  We can perform the operation
                   11617: @code{draw} on any @code{graphical} object, e.g.:
1.20      pazsan   11618: 
1.26      crook    11619: @example
1.78      anton    11620: 100 100 t-rex draw
1.26      crook    11621: @end example
1.12      anton    11622: 
1.78      anton    11623: where @code{t-rex} is an object or object pointer, created with e.g.
                   11624: @code{graphical new Constant t-rex}.
1.12      anton    11625: 
1.78      anton    11626: For concrete graphical objects, we define child classes of the
                   11627: class @code{graphical}, e.g.:
1.12      anton    11628: 
1.26      crook    11629: @example
                   11630: graphical class
1.78      anton    11631:   cell var circle-radius
                   11632: end-class circle \ "graphical" is the parent class
1.12      anton    11633: 
1.78      anton    11634: :noname ( x y -- )
                   11635:   circle-radius @@ draw-circle ; circle defines draw
                   11636: :noname ( r -- )
                   11637:   circle-radius ! ; circle defines init
                   11638: @end example
1.12      anton    11639: 
1.78      anton    11640: There is no implicit init method, so we have to define one. The creation
                   11641: code of the object now has to call init explicitely.
1.21      crook    11642: 
1.78      anton    11643: @example
                   11644: circle new Constant my-circle
                   11645: 50 my-circle init
1.12      anton    11646: @end example
                   11647: 
1.78      anton    11648: It is also possible to add a function to create named objects with
                   11649: automatic call of @code{init}, given that all objects have @code{init}
                   11650: on the same place:
1.38      anton    11651: 
1.78      anton    11652: @example
                   11653: : new: ( .. o "name" -- )
                   11654:     new dup Constant init ;
                   11655: 80 circle new: large-circle
                   11656: @end example
1.12      anton    11657: 
1.78      anton    11658: We can draw this new circle at (100,100) with:
1.12      anton    11659: 
1.78      anton    11660: @example
                   11661: 100 100 my-circle draw
                   11662: @end example
1.12      anton    11663: 
1.78      anton    11664: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
                   11665: @subsubsection @file{mini-oof.fs} Implementation
1.12      anton    11666: 
1.78      anton    11667: Object-oriented systems with late binding typically use a
                   11668: ``vtable''-approach: the first variable in each object is a pointer to a
                   11669: table, which contains the methods as function pointers. The vtable
                   11670: may also contain other information.
1.12      anton    11671: 
1.79      anton    11672: So first, let's declare selectors:
1.37      anton    11673: 
                   11674: @example
1.79      anton    11675: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
1.78      anton    11676:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
                   11677: @end example
1.37      anton    11678: 
1.79      anton    11679: During selector declaration, the number of selectors and instance
                   11680: variables is on the stack (in address units). @code{method} creates one
                   11681: selector and increments the selector number. To execute a selector, it
1.78      anton    11682: takes the object, fetches the vtable pointer, adds the offset, and
1.79      anton    11683: executes the method @i{xt} stored there. Each selector takes the object
                   11684: it is invoked with as top of stack parameter; it passes the parameters
                   11685: (including the object) unchanged to the appropriate method which should
1.78      anton    11686: consume that object.
1.37      anton    11687: 
1.78      anton    11688: Now, we also have to declare instance variables
1.37      anton    11689: 
1.78      anton    11690: @example
1.79      anton    11691: : var ( m v size "name" -- m v' ) Create  over , +
1.78      anton    11692:   DOES> ( o -- addr ) @@ + ;
1.37      anton    11693: @end example
                   11694: 
1.78      anton    11695: As before, a word is created with the current offset. Instance
                   11696: variables can have different sizes (cells, floats, doubles, chars), so
                   11697: all we do is take the size and add it to the offset. If your machine
                   11698: has alignment restrictions, put the proper @code{aligned} or
                   11699: @code{faligned} before the variable, to adjust the variable
                   11700: offset. That's why it is on the top of stack.
1.37      anton    11701: 
1.78      anton    11702: We need a starting point (the base object) and some syntactic sugar:
1.37      anton    11703: 
1.78      anton    11704: @example
                   11705: Create object  1 cells , 2 cells ,
1.79      anton    11706: : class ( class -- class selectors vars ) dup 2@@ ;
1.78      anton    11707: @end example
1.12      anton    11708: 
1.78      anton    11709: For inheritance, the vtable of the parent object has to be
                   11710: copied when a new, derived class is declared. This gives all the
                   11711: methods of the parent class, which can be overridden, though.
1.12      anton    11712: 
1.78      anton    11713: @example
1.79      anton    11714: : end-class  ( class selectors vars "name" -- )
1.78      anton    11715:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   11716:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
                   11717: @end example
1.12      anton    11718: 
1.78      anton    11719: The first line creates the vtable, initialized with
                   11720: @code{noop}s. The second line is the inheritance mechanism, it
                   11721: copies the xts from the parent vtable.
1.12      anton    11722: 
1.78      anton    11723: We still have no way to define new methods, let's do that now:
1.12      anton    11724: 
1.26      crook    11725: @example
1.79      anton    11726: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78      anton    11727: @end example
1.12      anton    11728: 
1.78      anton    11729: To allocate a new object, we need a word, too:
1.12      anton    11730: 
1.78      anton    11731: @example
                   11732: : new ( class -- o )  here over @@ allot swap over ! ;
1.12      anton    11733: @end example
                   11734: 
1.78      anton    11735: Sometimes derived classes want to access the method of the
                   11736: parent object. There are two ways to achieve this with Mini-OOF:
                   11737: first, you could use named words, and second, you could look up the
                   11738: vtable of the parent object.
1.12      anton    11739: 
1.78      anton    11740: @example
                   11741: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
                   11742: @end example
1.12      anton    11743: 
                   11744: 
1.78      anton    11745: Nothing can be more confusing than a good example, so here is
                   11746: one. First let's declare a text object (called
                   11747: @code{button}), that stores text and position:
1.12      anton    11748: 
1.78      anton    11749: @example
                   11750: object class
                   11751:   cell var text
                   11752:   cell var len
                   11753:   cell var x
                   11754:   cell var y
                   11755:   method init
                   11756:   method draw
                   11757: end-class button
                   11758: @end example
1.12      anton    11759: 
1.78      anton    11760: @noindent
                   11761: Now, implement the two methods, @code{draw} and @code{init}:
1.21      crook    11762: 
1.26      crook    11763: @example
1.78      anton    11764: :noname ( o -- )
                   11765:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
                   11766:  button defines draw
                   11767: :noname ( addr u o -- )
                   11768:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
                   11769:  button defines init
1.26      crook    11770: @end example
1.12      anton    11771: 
1.78      anton    11772: @noindent
                   11773: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79      anton    11774: new data and no new selectors:
1.78      anton    11775: 
                   11776: @example
                   11777: button class
                   11778: end-class bold-button
1.12      anton    11779: 
1.78      anton    11780: : bold   27 emit ." [1m" ;
                   11781: : normal 27 emit ." [0m" ;
                   11782: @end example
1.1       anton    11783: 
1.78      anton    11784: @noindent
                   11785: The class @code{bold-button} has a different draw method to
                   11786: @code{button}, but the new method is defined in terms of the draw method
                   11787: for @code{button}:
1.20      pazsan   11788: 
1.78      anton    11789: @example
                   11790: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   11791: @end example
1.21      crook    11792: 
1.78      anton    11793: @noindent
1.79      anton    11794: Finally, create two objects and apply selectors:
1.21      crook    11795: 
1.26      crook    11796: @example
1.78      anton    11797: button new Constant foo
                   11798: s" thin foo" foo init
                   11799: page
                   11800: foo draw
                   11801: bold-button new Constant bar
                   11802: s" fat bar" bar init
                   11803: 1 bar y !
                   11804: bar draw
1.26      crook    11805: @end example
1.21      crook    11806: 
                   11807: 
1.78      anton    11808: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   11809: @subsection Comparison with other object models
                   11810: @cindex comparison of object models
                   11811: @cindex object models, comparison
                   11812: 
                   11813: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   11814: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   11815: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   11816: relation of the object models described here to two well-known and two
                   11817: closely-related (by the use of method maps) models.  Andras Zsoter
                   11818: helped us with this section.
                   11819: 
                   11820: @cindex Neon model
                   11821: The most popular model currently seems to be the Neon model (see
                   11822: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   11823: 1997) by Andrew McKewan) but this model has a number of limitations
                   11824: @footnote{A longer version of this critique can be
                   11825: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   11826: Dimensions, May 1997) by Anton Ertl.}:
                   11827: 
                   11828: @itemize @bullet
                   11829: @item
                   11830: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11831: to pass objects on the stack.
1.21      crook    11832: 
1.78      anton    11833: @item
                   11834: It requires that the selector parses the input stream (at
1.79      anton    11835: compile time); this leads to reduced extensibility and to bugs that are
1.78      anton    11836: hard to find.
1.21      crook    11837: 
1.78      anton    11838: @item
1.79      anton    11839: It allows using every selector on every object; this eliminates the
                   11840: need for interfaces, but makes it harder to create efficient
                   11841: implementations.
1.78      anton    11842: @end itemize
1.21      crook    11843: 
1.78      anton    11844: @cindex Pountain's object-oriented model
                   11845: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11846: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11847: object-oriented programming, because it hardly deals with late
                   11848: binding. Instead, it focuses on features like information hiding and
                   11849: overloading that are characteristic of modular languages like Ada (83).
1.26      crook    11850: 
1.78      anton    11851: @cindex Zsoter's object-oriented model
1.79      anton    11852: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
                   11853: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
                   11854: describes a model that makes heavy use of an active object (like
                   11855: @code{this} in @file{objects.fs}): The active object is not only used
                   11856: for accessing all fields, but also specifies the receiving object of
                   11857: every selector invocation; you have to change the active object
                   11858: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   11859: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   11860: the method entry point is unnecessary with Zsoter's model, because the
                   11861: receiving object is the active object already. On the other hand, the
                   11862: explicit change is absolutely necessary in that model, because otherwise
                   11863: no one could ever change the active object. An ANS Forth implementation
                   11864: of this model is available through
                   11865: @uref{http://www.forth.org/oopf.html}.
1.21      crook    11866: 
1.78      anton    11867: @cindex @file{oof.fs}, differences to other models
                   11868: The @file{oof.fs} model combines information hiding and overloading
                   11869: resolution (by keeping names in various word lists) with object-oriented
                   11870: programming. It sets the active object implicitly on method entry, but
                   11871: also allows explicit changing (with @code{>o...o>} or with
                   11872: @code{with...endwith}). It uses parsing and state-smart objects and
                   11873: classes for resolving overloading and for early binding: the object or
                   11874: class parses the selector and determines the method from this. If the
                   11875: selector is not parsed by an object or class, it performs a call to the
                   11876: selector for the active object (late binding), like Zsoter's model.
                   11877: Fields are always accessed through the active object. The big
                   11878: disadvantage of this model is the parsing and the state-smartness, which
                   11879: reduces extensibility and increases the opportunities for subtle bugs;
                   11880: essentially, you are only safe if you never tick or @code{postpone} an
                   11881: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21      crook    11882: 
1.78      anton    11883: @cindex @file{mini-oof.fs}, differences to other models
                   11884: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11885: version of the @file{objects.fs} model, but syntactically it is a
                   11886: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21      crook    11887: 
                   11888: 
1.78      anton    11889: @c -------------------------------------------------------------
1.150     anton    11890: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78      anton    11891: @section Programming Tools
                   11892: @cindex programming tools
1.21      crook    11893: 
1.78      anton    11894: @c !! move this and assembler down below OO stuff.
1.21      crook    11895: 
1.78      anton    11896: @menu
1.150     anton    11897: * Examining::                   Data and Code.
                   11898: * Forgetting words::            Usually before reloading.
1.78      anton    11899: * Debugging::                   Simple and quick.
                   11900: * Assertions::                  Making your programs self-checking.
                   11901: * Singlestep Debugger::         Executing your program word by word.
                   11902: @end menu
1.21      crook    11903: 
1.78      anton    11904: @node Examining, Forgetting words, Programming Tools, Programming Tools
                   11905: @subsection Examining data and code
                   11906: @cindex examining data and code
                   11907: @cindex data examination
                   11908: @cindex code examination
1.44      crook    11909: 
1.78      anton    11910: The following words inspect the stack non-destructively:
1.21      crook    11911: 
1.78      anton    11912: doc-.s
                   11913: doc-f.s
1.158     anton    11914: doc-maxdepth-.s
1.44      crook    11915: 
1.78      anton    11916: There is a word @code{.r} but it does @i{not} display the return stack!
                   11917: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21      crook    11918: 
1.78      anton    11919: doc-depth
                   11920: doc-fdepth
                   11921: doc-clearstack
1.124     anton    11922: doc-clearstacks
1.21      crook    11923: 
1.78      anton    11924: The following words inspect memory.
1.21      crook    11925: 
1.78      anton    11926: doc-?
                   11927: doc-dump
1.21      crook    11928: 
1.78      anton    11929: And finally, @code{see} allows to inspect code:
1.21      crook    11930: 
1.78      anton    11931: doc-see
                   11932: doc-xt-see
1.111     anton    11933: doc-simple-see
                   11934: doc-simple-see-range
1.182     anton    11935: doc-see-code
                   11936: doc-see-code-range
1.21      crook    11937: 
1.78      anton    11938: @node Forgetting words, Debugging, Examining, Programming Tools
                   11939: @subsection Forgetting words
                   11940: @cindex words, forgetting
                   11941: @cindex forgeting words
1.21      crook    11942: 
1.78      anton    11943: @c  anton: other, maybe better places for this subsection: Defining Words;
                   11944: @c  Dictionary allocation.  At least a reference should be there.
1.21      crook    11945: 
1.78      anton    11946: Forth allows you to forget words (and everything that was alloted in the
                   11947: dictonary after them) in a LIFO manner.
1.21      crook    11948: 
1.78      anton    11949: doc-marker
1.21      crook    11950: 
1.78      anton    11951: The most common use of this feature is during progam development: when
                   11952: you change a source file, forget all the words it defined and load it
                   11953: again (since you also forget everything defined after the source file
                   11954: was loaded, you have to reload that, too).  Note that effects like
                   11955: storing to variables and destroyed system words are not undone when you
                   11956: forget words.  With a system like Gforth, that is fast enough at
                   11957: starting up and compiling, I find it more convenient to exit and restart
                   11958: Gforth, as this gives me a clean slate.
1.21      crook    11959: 
1.78      anton    11960: Here's an example of using @code{marker} at the start of a source file
                   11961: that you are debugging; it ensures that you only ever have one copy of
                   11962: the file's definitions compiled at any time:
1.21      crook    11963: 
1.78      anton    11964: @example
                   11965: [IFDEF] my-code
                   11966:     my-code
                   11967: [ENDIF]
1.26      crook    11968: 
1.78      anton    11969: marker my-code
                   11970: init-included-files
1.21      crook    11971: 
1.78      anton    11972: \ .. definitions start here
                   11973: \ .
                   11974: \ .
                   11975: \ end
                   11976: @end example
1.21      crook    11977: 
1.26      crook    11978: 
1.78      anton    11979: @node Debugging, Assertions, Forgetting words, Programming Tools
                   11980: @subsection Debugging
                   11981: @cindex debugging
1.21      crook    11982: 
1.78      anton    11983: Languages with a slow edit/compile/link/test development loop tend to
                   11984: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21      crook    11985: 
1.78      anton    11986: A much better (faster) way in fast-compiling languages is to add
                   11987: printing code at well-selected places, let the program run, look at
                   11988: the output, see where things went wrong, add more printing code, etc.,
                   11989: until the bug is found.
1.21      crook    11990: 
1.78      anton    11991: The simple debugging aids provided in @file{debugs.fs}
                   11992: are meant to support this style of debugging.
1.21      crook    11993: 
1.78      anton    11994: The word @code{~~} prints debugging information (by default the source
                   11995: location and the stack contents). It is easy to insert. If you use Emacs
                   11996: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
                   11997: query-replace them with nothing). The deferred words
1.101     anton    11998: @code{printdebugdata} and @code{.debugline} control the output of
1.78      anton    11999: @code{~~}. The default source location output format works well with
                   12000: Emacs' compilation mode, so you can step through the program at the
                   12001: source level using @kbd{C-x `} (the advantage over a stepping debugger
                   12002: is that you can step in any direction and you know where the crash has
                   12003: happened or where the strange data has occurred).
1.21      crook    12004: 
1.78      anton    12005: doc-~~
                   12006: doc-printdebugdata
1.101     anton    12007: doc-.debugline
1.203     anton    12008: doc-debug-fid
1.21      crook    12009: 
1.106     anton    12010: @cindex filenames in @code{~~} output
                   12011: @code{~~} (and assertions) will usually print the wrong file name if a
                   12012: marker is executed in the same file after their occurance.  They will
                   12013: print @samp{*somewhere*} as file name if a marker is executed in the
                   12014: same file before their occurance.
                   12015: 
                   12016: 
1.78      anton    12017: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
                   12018: @subsection Assertions
                   12019: @cindex assertions
1.21      crook    12020: 
1.78      anton    12021: It is a good idea to make your programs self-checking, especially if you
                   12022: make an assumption that may become invalid during maintenance (for
                   12023: example, that a certain field of a data structure is never zero). Gforth
                   12024: supports @dfn{assertions} for this purpose. They are used like this:
1.21      crook    12025: 
                   12026: @example
1.78      anton    12027: assert( @i{flag} )
1.26      crook    12028: @end example
                   12029: 
1.78      anton    12030: The code between @code{assert(} and @code{)} should compute a flag, that
                   12031: should be true if everything is alright and false otherwise. It should
                   12032: not change anything else on the stack. The overall stack effect of the
                   12033: assertion is @code{( -- )}. E.g.
1.21      crook    12034: 
1.26      crook    12035: @example
1.78      anton    12036: assert( 1 1 + 2 = ) \ what we learn in school
                   12037: assert( dup 0<> ) \ assert that the top of stack is not zero
                   12038: assert( false ) \ this code should not be reached
1.21      crook    12039: @end example
                   12040: 
1.78      anton    12041: The need for assertions is different at different times. During
                   12042: debugging, we want more checking, in production we sometimes care more
                   12043: for speed. Therefore, assertions can be turned off, i.e., the assertion
                   12044: becomes a comment. Depending on the importance of an assertion and the
                   12045: time it takes to check it, you may want to turn off some assertions and
                   12046: keep others turned on. Gforth provides several levels of assertions for
                   12047: this purpose:
                   12048: 
                   12049: 
                   12050: doc-assert0(
                   12051: doc-assert1(
                   12052: doc-assert2(
                   12053: doc-assert3(
                   12054: doc-assert(
                   12055: doc-)
1.21      crook    12056: 
                   12057: 
1.78      anton    12058: The variable @code{assert-level} specifies the highest assertions that
                   12059: are turned on. I.e., at the default @code{assert-level} of one,
                   12060: @code{assert0(} and @code{assert1(} assertions perform checking, while
                   12061: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26      crook    12062: 
1.78      anton    12063: The value of @code{assert-level} is evaluated at compile-time, not at
                   12064: run-time. Therefore you cannot turn assertions on or off at run-time;
                   12065: you have to set the @code{assert-level} appropriately before compiling a
                   12066: piece of code. You can compile different pieces of code at different
                   12067: @code{assert-level}s (e.g., a trusted library at level 1 and
                   12068: newly-written code at level 3).
1.26      crook    12069: 
                   12070: 
1.78      anton    12071: doc-assert-level
1.26      crook    12072: 
                   12073: 
1.78      anton    12074: If an assertion fails, a message compatible with Emacs' compilation mode
                   12075: is produced and the execution is aborted (currently with @code{ABORT"}.
                   12076: If there is interest, we will introduce a special throw code. But if you
                   12077: intend to @code{catch} a specific condition, using @code{throw} is
                   12078: probably more appropriate than an assertion).
1.106     anton    12079: 
                   12080: @cindex filenames in assertion output
                   12081: Assertions (and @code{~~}) will usually print the wrong file name if a
                   12082: marker is executed in the same file after their occurance.  They will
                   12083: print @samp{*somewhere*} as file name if a marker is executed in the
                   12084: same file before their occurance.
1.44      crook    12085: 
1.78      anton    12086: Definitions in ANS Forth for these assertion words are provided
                   12087: in @file{compat/assert.fs}.
1.26      crook    12088: 
1.44      crook    12089: 
1.78      anton    12090: @node Singlestep Debugger,  , Assertions, Programming Tools
                   12091: @subsection Singlestep Debugger
                   12092: @cindex singlestep Debugger
                   12093: @cindex debugging Singlestep
1.44      crook    12094: 
1.189     anton    12095: The singlestep debugger works only with the engine @code{gforth-itc}.
1.112     anton    12096: 
1.78      anton    12097: When you create a new word there's often the need to check whether it
                   12098: behaves correctly or not. You can do this by typing @code{dbg
                   12099: badword}. A debug session might look like this:
1.26      crook    12100: 
1.78      anton    12101: @example
                   12102: : badword 0 DO i . LOOP ;  ok
                   12103: 2 dbg badword 
                   12104: : badword  
                   12105: Scanning code...
1.44      crook    12106: 
1.78      anton    12107: Nesting debugger ready!
1.44      crook    12108: 
1.78      anton    12109: 400D4738  8049BC4 0              -> [ 2 ] 00002 00000 
                   12110: 400D4740  8049F68 DO             -> [ 0 ] 
                   12111: 400D4744  804A0C8 i              -> [ 1 ] 00000 
                   12112: 400D4748 400C5E60 .              -> 0 [ 0 ] 
                   12113: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   12114: 400D4744  804A0C8 i              -> [ 1 ] 00001 
                   12115: 400D4748 400C5E60 .              -> 1 [ 0 ] 
                   12116: 400D474C  8049D0C LOOP           -> [ 0 ] 
                   12117: 400D4758  804B384 ;              ->  ok
                   12118: @end example
1.21      crook    12119: 
1.78      anton    12120: Each line displayed is one step. You always have to hit return to
                   12121: execute the next word that is displayed. If you don't want to execute
                   12122: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
                   12123: an overview what keys are available:
1.44      crook    12124: 
1.78      anton    12125: @table @i
1.44      crook    12126: 
1.78      anton    12127: @item @key{RET}
                   12128: Next; Execute the next word.
1.21      crook    12129: 
1.78      anton    12130: @item n
                   12131: Nest; Single step through next word.
1.44      crook    12132: 
1.78      anton    12133: @item u
                   12134: Unnest; Stop debugging and execute rest of word. If we got to this word
                   12135: with nest, continue debugging with the calling word.
1.44      crook    12136: 
1.78      anton    12137: @item d
                   12138: Done; Stop debugging and execute rest.
1.21      crook    12139: 
1.78      anton    12140: @item s
                   12141: Stop; Abort immediately.
1.44      crook    12142: 
1.78      anton    12143: @end table
1.44      crook    12144: 
1.78      anton    12145: Debugging large application with this mechanism is very difficult, because
                   12146: you have to nest very deeply into the program before the interesting part
                   12147: begins. This takes a lot of time. 
1.26      crook    12148: 
1.78      anton    12149: To do it more directly put a @code{BREAK:} command into your source code.
                   12150: When program execution reaches @code{BREAK:} the single step debugger is
                   12151: invoked and you have all the features described above.
1.44      crook    12152: 
1.78      anton    12153: If you have more than one part to debug it is useful to know where the
                   12154: program has stopped at the moment. You can do this by the 
                   12155: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
                   12156: string is typed out when the ``breakpoint'' is reached.
1.44      crook    12157: 
1.26      crook    12158: 
1.78      anton    12159: doc-dbg
                   12160: doc-break:
                   12161: doc-break"
1.44      crook    12162: 
1.150     anton    12163: @c ------------------------------------------------------------
                   12164: @node C Interface, Assembler and Code Words, Programming Tools, Words
                   12165: @section C Interface
                   12166: @cindex C interface
                   12167: @cindex foreign language interface
                   12168: @cindex interface to C functions
                   12169: 
1.178     anton    12170: Note that the C interface is not yet complete; callbacks are missing,
                   12171: as well as a way of declaring structs, unions, and their fields.
1.150     anton    12172: 
                   12173: @menu
                   12174: * Calling C Functions::         
                   12175: * Declaring C Functions::       
1.180     anton    12176: * Calling C function pointers::  
1.196     anton    12177: * Defining library interfaces::  
                   12178: * Declaring OS-level libraries::  
1.150     anton    12179: * Callbacks::                   
1.178     anton    12180: * C interface internals::       
1.155     anton    12181: * Low-Level C Interface Words::  
1.150     anton    12182: @end menu
                   12183: 
1.151     pazsan   12184: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150     anton    12185: @subsection Calling C functions
1.155     anton    12186: @cindex C functions, calls to
                   12187: @cindex calling C functions
1.150     anton    12188: 
1.151     pazsan   12189: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150     anton    12190: can call it as follows: You push the arguments on the stack(s), and
                   12191: then call the word for the C function.  The arguments have to be
                   12192: pushed in the same order as the arguments appear in the C
                   12193: documentation (i.e., the first argument is deepest on the stack).
                   12194: Integer and pointer arguments have to be pushed on the data stack,
                   12195: floating-point arguments on the FP stack; these arguments are consumed
1.155     anton    12196: by the called C function.
1.150     anton    12197: 
1.155     anton    12198: On returning from the C function, the return value, if any, resides on
                   12199: the appropriate stack: an integer return value is pushed on the data
                   12200: stack, an FP return value on the FP stack, and a void return value
                   12201: results in not pushing anything.  Note that most C functions have a
                   12202: return value, even if that is often not used in C; in Forth, you have
                   12203: to @code{drop} this return value explicitly if you do not use it.
1.150     anton    12204: 
1.177     anton    12205: The C interface automatically converts between the C type and the
                   12206: Forth type as necessary, on a best-effort basis (in some cases, there
                   12207: may be some loss).
1.150     anton    12208: 
                   12209: As an example, consider the POSIX function @code{lseek()}:
                   12210: 
                   12211: @example
                   12212: off_t lseek(int fd, off_t offset, int whence);
                   12213: @end example
                   12214: 
                   12215: This function takes three integer arguments, and returns an integer
                   12216: argument, so a Forth call for setting the current file offset to the
                   12217: start of the file could look like this:
                   12218: 
                   12219: @example
                   12220: fd @@ 0 SEEK_SET lseek -1 = if
                   12221:   ... \ error handling
                   12222: then
                   12223: @end example
                   12224: 
                   12225: You might be worried that an @code{off_t} does not fit into a cell, so
                   12226: you could not pass larger offsets to lseek, and might get only a part
1.155     anton    12227: of the return values.  In that case, in your declaration of the
                   12228: function (@pxref{Declaring C Functions}) you should declare it to use
                   12229: double-cells for the off_t argument and return value, and maybe give
                   12230: the resulting Forth word a different name, like @code{dlseek}; the
                   12231: result could be called like this:
1.150     anton    12232: 
                   12233: @example
                   12234: fd @@ 0. SEEK_SET dlseek -1. d= if
                   12235:   ... \ error handling
                   12236: then
                   12237: @end example
                   12238: 
                   12239: Passing and returning structs or unions is currently not supported by
                   12240: our interface@footnote{If you know the calling convention of your C
                   12241: compiler, you usually can call such functions in some way, but that
                   12242: way is usually not portable between platforms, and sometimes not even
                   12243: between C compilers.}.
                   12244: 
1.177     anton    12245: Calling functions with a variable number of arguments (@emph{variadic}
                   12246: functions, e.g., @code{printf()}) is only supported by having you
                   12247: declare one function-calling word for each argument pattern, and
                   12248: calling the appropriate word for the desired pattern.
                   12249: 
1.150     anton    12250: 
1.155     anton    12251: 
1.180     anton    12252: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150     anton    12253: @subsection Declaring C Functions
1.155     anton    12254: @cindex C functions, declarations
                   12255: @cindex declaring C functions
1.150     anton    12256: 
                   12257: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177     anton    12258: it.  The declaration consists of two parts: 
                   12259: 
                   12260: @table @b
                   12261: 
                   12262: @item The C part
1.179     anton    12263: is the C declaration of the function, or more typically and portably,
                   12264: a C-style @code{#include} of a file that contains the declaration of
                   12265: the C function.
1.177     anton    12266: 
                   12267: @item The Forth part
                   12268: declares the Forth types of the parameters and the Forth word name
                   12269: corresponding to the C function.
                   12270: 
                   12271: @end table
                   12272: 
                   12273: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
                   12274: declarations are:
                   12275: 
                   12276: @example
                   12277: \c #define _FILE_OFFSET_BITS 64
                   12278: \c #include <sys/types.h>
                   12279: \c #include <unistd.h>
                   12280: c-function lseek lseek n n n -- n
                   12281: c-function dlseek lseek n d n -- d
                   12282: @end example
                   12283: 
1.178     anton    12284: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177     anton    12285: of the line is ordinary C code.  You can use as many lines of C
                   12286: declarations as you like, and they are visible for all further
                   12287: function declarations.
                   12288: 
                   12289: The Forth part declares each interface word with @code{c-function},
                   12290: followed by the Forth name of the word, the C name of the called
                   12291: function, and the stack effect of the word.  The stack effect contains
1.178     anton    12292: an arbitrary number of types of parameters, then @code{--}, and then
1.177     anton    12293: exactly one type for the return value.  The possible types are:
                   12294: 
                   12295: @table @code
                   12296: 
                   12297: @item n
                   12298: single-cell integer
                   12299: 
                   12300: @item a
                   12301: address (single-cell)
                   12302: 
                   12303: @item d
                   12304: double-cell integer
                   12305: 
                   12306: @item r
                   12307: floating-point value
                   12308: 
                   12309: @item func
                   12310: C function pointer
                   12311: 
                   12312: @item void
                   12313: no value (used as return type for void functions)
                   12314: 
                   12315: @end table
                   12316: 
                   12317: @cindex variadic C functions
                   12318: 
                   12319: To deal with variadic C functions, you can declare one Forth word for
                   12320: every pattern you want to use, e.g.:
                   12321: 
                   12322: @example
                   12323: \c #include <stdio.h>
                   12324: c-function printf-nr printf a n r -- n
                   12325: c-function printf-rn printf a r n -- n
                   12326: @end example
                   12327: 
                   12328: Note that with C functions declared as variadic (or if you don't
                   12329: provide a prototype), the C interface has no C type to convert to, so
                   12330: no automatic conversion happens, which may lead to portability
                   12331: problems in some cases.  In such cases you can perform the conversion
                   12332: explicitly on the C level, e.g., as follows:
                   12333: 
                   12334: @example
1.178     anton    12335: \c #define printfll(s,ll) printf(s,(long long)ll)
                   12336: c-function printfll printfll a n -- n
1.177     anton    12337: @end example
                   12338: 
                   12339: Here, instead of calling @code{printf()} directly, we define a macro
1.178     anton    12340: that casts (converts) the Forth single-cell integer into a
                   12341: C @code{long long} before calling @code{printf()}.
1.177     anton    12342: 
                   12343: doc-\c
                   12344: doc-c-function
1.207     pazsan   12345: doc-c-value
                   12346: doc-c-variable
1.177     anton    12347: 
                   12348: In order to work, this C interface invokes GCC at run-time and uses
1.178     anton    12349: dynamic linking.  If these features are not available, there are
                   12350: other, less convenient and less portable C interfaces in @file{lib.fs}
                   12351: and @file{oldlib.fs}.  These interfaces are mostly undocumented and
                   12352: mostly incompatible with each other and with the documented C
                   12353: interface; you can find some examples for the @file{lib.fs} interface
                   12354: in @file{lib.fs}.
1.177     anton    12355: 
                   12356: 
1.196     anton    12357: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
1.180     anton    12358: @subsection Calling C function pointers from Forth
                   12359: @cindex C function pointers, calling from Forth
1.177     anton    12360: 
1.180     anton    12361: If you come across a C function pointer (e.g., in some C-constructed
                   12362: structure) and want to call it from your Forth program, you can also
                   12363: use the features explained until now to achieve that, as follows:
1.150     anton    12364: 
1.180     anton    12365: Let us assume that there is a C function pointer type @code{func1}
                   12366: defined in some header file @file{func1.h}, and you know that these
                   12367: functions take one integer argument and return an integer result; and
                   12368: you want to call functions through such pointers.  Just define
1.155     anton    12369: 
1.180     anton    12370: @example
                   12371: \c #include <func1.h>
                   12372: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
                   12373: c-function call-func1 call_func1 n func -- n
                   12374: @end example
                   12375: 
                   12376: and then you can call a function pointed to by, say @code{func1a} as
                   12377: follows:
                   12378: 
                   12379: @example
                   12380: -5 func1a call-func1 .
                   12381: @end example
                   12382: 
                   12383: In the C part, @code{call_func} is defined as a macro to avoid having
                   12384: to declare the exact parameter and return types, so the C compiler
                   12385: knows them from the declaration of @code{func1}.
                   12386: 
                   12387: The Forth word @code{call-func1} is similar to @code{execute}, except
                   12388: that it takes a C @code{func1} pointer instead of a Forth execution
                   12389: token, and it is specific to @code{func1} pointers.  For each type of
                   12390: function pointer you want to call from Forth, you have to define
                   12391: a separate calling word.
                   12392: 
                   12393: 
1.196     anton    12394: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
                   12395: @subsection Defining library interfaces
                   12396: @cindex giving a name to a library interface
                   12397: @cindex library interface names
                   12398: 
                   12399: You can give a name to a bunch of C function declarations (a library
                   12400: interface), as follows:
                   12401: 
                   12402: @example
                   12403: c-library lseek-lib
                   12404: \c #define _FILE_OFFSET_BITS 64
                   12405: ...
                   12406: end-c-library
                   12407: @end example
                   12408: 
1.202     anton    12409: The effect of giving such a name to the interface is that the names of
                   12410: the generated files will contain that name, and when you use the
                   12411: interface a second time, it will use the existing files instead of
                   12412: generating and compiling them again, saving you time.  Note that even
                   12413: if you change the declarations, the old (stale) files will be used,
                   12414: probably leading to errors.  So, during development of the
                   12415: declarations we recommend not using @code{c-library}.  Normally these
                   12416: files are cached in @file{$HOME/.gforth/libcc-named}, so by deleting
                   12417: that directory you can get rid of stale files.
                   12418: 
                   12419: Note that you should use @code{c-library} before everything else
                   12420: having anything to do with that library, as it resets some setup
                   12421: stuff.  The idea is that the typical use is to put each
                   12422: @code{c-library}...@code{end-library} unit in its own file, and to be
                   12423: able to include these files in any order.
1.196     anton    12424: 
                   12425: Note that the library name is not allocated in the dictionary and
                   12426: therefore does not shadow dictionary names.  It is used in the file
                   12427: system, so you have to use naming conventions appropriate for file
                   12428: systems.  Also, you must not call a function you declare after
                   12429: @code{c-library} before you perform @code{end-c-library}.
                   12430: 
                   12431: A major benefit of these named library interfaces is that, once they
                   12432: are generated, the tools used to generated them (in particular, the C
                   12433: compiler and libtool) are no longer needed, so the interface can be
                   12434: used even on machines that do not have the tools installed.
                   12435: 
                   12436: doc-c-library-name
                   12437: doc-c-library
                   12438: doc-end-c-library
                   12439: 
                   12440: 
                   12441: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
                   12442: @subsection Declaring OS-level libraries
1.195     anton    12443: @cindex Shared libraries in C interface
                   12444: @cindex Dynamically linked libraries in C interface
                   12445: @cindex Libraries in C interface
                   12446: 
1.196     anton    12447: For calling some C functions, you need to link with a specific
                   12448: OS-level library that contains that function.  E.g., the @code{sin}
                   12449: function requires linking a special library by using the command line
                   12450: switch @code{-lm}.  In our C iterface you do the equivalent thing by
                   12451: calling @code{add-lib} as follows:
1.195     anton    12452: 
                   12453: @example
                   12454: clear-libs
                   12455: s" m" add-lib
                   12456: \c #include <math.h>
                   12457: c-function sin sin r -- r
                   12458: @end example
                   12459: 
                   12460: First, you clear any libraries that may have been declared earlier
                   12461: (you don't need them for @code{sin}); then you add the @code{m}
                   12462: library (actually @code{libm.so} or somesuch) to the currently
                   12463: declared libraries; you can add as many as you need.  Finally you
                   12464: declare the function as shown above.  Typically you will use the same
                   12465: set of library declarations for many function declarations; you need
                   12466: to write only one set for that, right at the beginning.
                   12467: 
1.196     anton    12468: Note that you must not call @code{clear-libs} inside
                   12469: @code{c-library...end-c-library}; however, @code{c-library} performs
                   12470: the function of @code{clear-libs}, so @code{clear-libs} is not
                   12471: necessary, and you usually want to put @code{add-lib} calls inside
                   12472: @code{c-library...end-c-library}.
                   12473: 
1.195     anton    12474: doc-clear-libs
                   12475: doc-add-lib
                   12476: 
                   12477: 
1.196     anton    12478: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
1.150     anton    12479: @subsection Callbacks
1.155     anton    12480: @cindex Callback functions written in Forth
                   12481: @cindex C function pointers to Forth words
                   12482: 
1.177     anton    12483: Callbacks are not yet supported by the documented C interface.  You
                   12484: can use the undocumented @file{lib.fs} interface for callbacks.
                   12485: 
1.155     anton    12486: In some cases you have to pass a function pointer to a C function,
                   12487: i.e., the library wants to call back to your application (and the
                   12488: pointed-to function is called a callback function).  You can pass the
                   12489: address of an existing C function (that you get with @code{lib-sym},
                   12490: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
                   12491: function, you probably want to define the function as a Forth word.
                   12492: 
                   12493: @c I don't understand the existing callback interface from the example - anton
                   12494: 
1.165     anton    12495: 
                   12496: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
                   12497: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
                   12498: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
                   12499: @c > > C-Funktionsadresse auf dem TOS).
                   12500: @c >
                   12501: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
                   12502: @c > gesehen habe, wozu das gut ist.
                   12503: @c 
                   12504: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch 
                   12505: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen 
                   12506: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit 
                   12507: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte 
                   12508: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit 
                   12509: @c demselben Prototyp.
                   12510: 
                   12511: 
1.178     anton    12512: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177     anton    12513: @subsection How the C interface works
                   12514: 
                   12515: The documented C interface works by generating a C code out of the
                   12516: declarations.
                   12517: 
                   12518: In particular, for every Forth word declared with @code{c-function},
                   12519: it generates a wrapper function in C that takes the Forth data from
                   12520: the Forth stacks, and calls the target C function with these data as
                   12521: arguments.  The C compiler then performs an implicit conversion
                   12522: between the Forth type from the stack, and the C type for the
                   12523: parameter, which is given by the C function prototype.  After the C
                   12524: function returns, the return value is likewise implicitly converted to
                   12525: a Forth type and written back on the stack.
                   12526: 
                   12527: The @code{\c} lines are literally included in the C code (but without
                   12528: the @code{\c}), and provide the necessary declarations so that the C
                   12529: compiler knows the C types and has enough information to perform the
                   12530: conversion.
                   12531: 
                   12532: These wrapper functions are eventually compiled and dynamically linked
                   12533: into Gforth, and then they can be called.
                   12534: 
1.195     anton    12535: The libraries added with @code{add-lib} are used in the compile
                   12536: command line to specify dependent libraries with @code{-l@var{lib}},
                   12537: causing these libraries to be dynamically linked when the wrapper
                   12538: function is linked.
                   12539: 
1.177     anton    12540: 
1.178     anton    12541: @node Low-Level C Interface Words,  , C interface internals, C Interface
1.155     anton    12542: @subsection Low-Level C Interface Words
1.44      crook    12543: 
1.155     anton    12544: doc-open-lib
                   12545: doc-lib-sym
1.196     anton    12546: doc-lib-error
1.177     anton    12547: doc-call-c
1.26      crook    12548: 
1.78      anton    12549: @c -------------------------------------------------------------
1.150     anton    12550: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78      anton    12551: @section Assembler and Code Words
                   12552: @cindex assembler
                   12553: @cindex code words
1.44      crook    12554: 
1.78      anton    12555: @menu
                   12556: * Code and ;code::              
                   12557: * Common Assembler::            Assembler Syntax
                   12558: * Common Disassembler::         
                   12559: * 386 Assembler::               Deviations and special cases
                   12560: * Alpha Assembler::             Deviations and special cases
                   12561: * MIPS assembler::              Deviations and special cases
1.161     anton    12562: * PowerPC assembler::           Deviations and special cases
1.193     dvdkhlng 12563: * ARM Assembler::               Deviations and special cases
1.78      anton    12564: * Other assemblers::            How to write them
                   12565: @end menu
1.21      crook    12566: 
1.78      anton    12567: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
                   12568: @subsection @code{Code} and @code{;code}
1.26      crook    12569: 
1.78      anton    12570: Gforth provides some words for defining primitives (words written in
                   12571: machine code), and for defining the machine-code equivalent of
                   12572: @code{DOES>}-based defining words. However, the machine-independent
                   12573: nature of Gforth poses a few problems: First of all, Gforth runs on
                   12574: several architectures, so it can provide no standard assembler. What's
                   12575: worse is that the register allocation not only depends on the processor,
                   12576: but also on the @code{gcc} version and options used.
1.44      crook    12577: 
1.78      anton    12578: The words that Gforth offers encapsulate some system dependences (e.g.,
                   12579: the header structure), so a system-independent assembler may be used in
                   12580: Gforth. If you do not have an assembler, you can compile machine code
                   12581: directly with @code{,} and @code{c,}@footnote{This isn't portable,
                   12582: because these words emit stuff in @i{data} space; it works because
                   12583: Gforth has unified code/data spaces. Assembler isn't likely to be
                   12584: portable anyway.}.
1.21      crook    12585: 
1.44      crook    12586: 
1.78      anton    12587: doc-assembler
                   12588: doc-init-asm
                   12589: doc-code
                   12590: doc-end-code
                   12591: doc-;code
                   12592: doc-flush-icache
1.44      crook    12593: 
1.21      crook    12594: 
1.78      anton    12595: If @code{flush-icache} does not work correctly, @code{code} words
                   12596: etc. will not work (reliably), either.
1.44      crook    12597: 
1.78      anton    12598: The typical usage of these @code{code} words can be shown most easily by
                   12599: analogy to the equivalent high-level defining words:
1.44      crook    12600: 
1.78      anton    12601: @example
                   12602: : foo                              code foo
                   12603:    <high-level Forth words>              <assembler>
                   12604: ;                                  end-code
                   12605:                                 
                   12606: : bar                              : bar
                   12607:    <high-level Forth words>           <high-level Forth words>
                   12608:    CREATE                             CREATE
                   12609:       <high-level Forth words>           <high-level Forth words>
                   12610:    DOES>                              ;code
                   12611:       <high-level Forth words>           <assembler>
                   12612: ;                                  end-code
                   12613: @end example
1.21      crook    12614: 
1.78      anton    12615: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44      crook    12616: 
1.78      anton    12617: @cindex registers of the inner interpreter
                   12618: In the assembly code you will want to refer to the inner interpreter's
                   12619: registers (e.g., the data stack pointer) and you may want to use other
                   12620: registers for temporary storage. Unfortunately, the register allocation
                   12621: is installation-dependent.
1.44      crook    12622: 
1.78      anton    12623: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100     anton    12624: (return stack pointer) may be in different places in @code{gforth} and
                   12625: @code{gforth-fast}, or different installations.  This means that you
                   12626: cannot write a @code{NEXT} routine that works reliably on both versions
                   12627: or different installations; so for doing @code{NEXT}, I recommend
                   12628: jumping to @code{' noop >code-address}, which contains nothing but a
                   12629: @code{NEXT}.
1.21      crook    12630: 
1.78      anton    12631: For general accesses to the inner interpreter's registers, the easiest
                   12632: solution is to use explicit register declarations (@pxref{Explicit Reg
                   12633: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
                   12634: all of the inner interpreter's registers: You have to compile Gforth
                   12635: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
                   12636: the appropriate declarations must be present in the @code{machine.h}
                   12637: file (see @code{mips.h} for an example; you can find a full list of all
                   12638: declarable register symbols with @code{grep register engine.c}). If you
                   12639: give explicit registers to all variables that are declared at the
                   12640: beginning of @code{engine()}, you should be able to use the other
                   12641: caller-saved registers for temporary storage. Alternatively, you can use
                   12642: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
                   12643: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
                   12644: reserve a register (however, this restriction on register allocation may
                   12645: slow Gforth significantly).
1.44      crook    12646: 
1.78      anton    12647: If this solution is not viable (e.g., because @code{gcc} does not allow
                   12648: you to explicitly declare all the registers you need), you have to find
                   12649: out by looking at the code where the inner interpreter's registers
                   12650: reside and which registers can be used for temporary storage. You can
                   12651: get an assembly listing of the engine's code with @code{make engine.s}.
1.44      crook    12652: 
1.78      anton    12653: In any case, it is good practice to abstract your assembly code from the
                   12654: actual register allocation. E.g., if the data stack pointer resides in
                   12655: register @code{$17}, create an alias for this register called @code{sp},
                   12656: and use that in your assembly code.
1.21      crook    12657: 
1.78      anton    12658: @cindex code words, portable
                   12659: Another option for implementing normal and defining words efficiently
                   12660: is to add the desired functionality to the source of Gforth. For normal
                   12661: words you just have to edit @file{primitives} (@pxref{Automatic
                   12662: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
                   12663: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
                   12664: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44      crook    12665: 
1.78      anton    12666: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
                   12667: @subsection Common Assembler
1.44      crook    12668: 
1.78      anton    12669: The assemblers in Gforth generally use a postfix syntax, i.e., the
                   12670: instruction name follows the operands.
1.21      crook    12671: 
1.78      anton    12672: The operands are passed in the usual order (the same that is used in the
                   12673: manual of the architecture).  Since they all are Forth words, they have
                   12674: to be separated by spaces; you can also use Forth words to compute the
                   12675: operands.
1.44      crook    12676: 
1.78      anton    12677: The instruction names usually end with a @code{,}.  This makes it easier
                   12678: to visually separate instructions if you put several of them on one
                   12679: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21      crook    12680: 
1.78      anton    12681: Registers are usually specified by number; e.g., (decimal) @code{11}
                   12682: specifies registers R11 and F11 on the Alpha architecture (which one,
                   12683: depends on the instruction).  The usual names are also available, e.g.,
                   12684: @code{s2} for R11 on Alpha.
1.21      crook    12685: 
1.78      anton    12686: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
                   12687: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
                   12688: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
                   12689: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}.  The
                   12690: conditions are specified in a way specific to each assembler.
1.1       anton    12691: 
1.78      anton    12692: Note that the register assignments of the Gforth engine can change
                   12693: between Gforth versions, or even between different compilations of the
                   12694: same Gforth version (e.g., if you use a different GCC version).  So if
                   12695: you want to refer to Gforth's registers (e.g., the stack pointer or
                   12696: TOS), I recommend defining your own words for refering to these
                   12697: registers, and using them later on; then you can easily adapt to a
                   12698: changed register assignment.  The stability of the register assignment
                   12699: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1       anton    12700: 
1.100     anton    12701: The most common use of these registers is to dispatch to the next word
                   12702: (the @code{next} routine).  A portable way to do this is to jump to
                   12703: @code{' noop >code-address} (of course, this is less efficient than
                   12704: integrating the @code{next} code and scheduling it well).
1.1       anton    12705: 
1.96      anton    12706: Another difference between Gforth version is that the top of stack is
                   12707: kept in memory in @code{gforth} and, on most platforms, in a register in
                   12708: @code{gforth-fast}.
                   12709: 
1.78      anton    12710: @node  Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
                   12711: @subsection Common Disassembler
1.127     anton    12712: @cindex disassembler, general
                   12713: @cindex gdb disassembler
1.1       anton    12714: 
1.78      anton    12715: You can disassemble a @code{code} word with @code{see}
                   12716: (@pxref{Debugging}).  You can disassemble a section of memory with
1.1       anton    12717: 
1.127     anton    12718: doc-discode
1.44      crook    12719: 
1.127     anton    12720: There are two kinds of disassembler for Gforth: The Forth disassembler
                   12721: (available on some CPUs) and the gdb disassembler (available on
                   12722: platforms with @command{gdb} and @command{mktemp}).  If both are
                   12723: available, the Forth disassembler is used by default.  If you prefer
                   12724: the gdb disassembler, say
                   12725: 
                   12726: @example
                   12727: ' disasm-gdb is discode
                   12728: @end example
                   12729: 
                   12730: If neither is available, @code{discode} performs @code{dump}.
                   12731: 
                   12732: The Forth disassembler generally produces output that can be fed into the
1.78      anton    12733: assembler (i.e., same syntax, etc.).  It also includes additional
                   12734: information in comments.  In particular, the address of the instruction
                   12735: is given in a comment before the instruction.
1.1       anton    12736: 
1.127     anton    12737: The gdb disassembler produces output in the same format as the gdb
                   12738: @code{disassemble} command (@pxref{Machine Code,,Source and machine
                   12739: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
                   12740: the 386 and AMD64 architectures).
                   12741: 
1.78      anton    12742: @code{See} may display more or less than the actual code of the word,
                   12743: because the recognition of the end of the code is unreliable.  You can
1.127     anton    12744: use @code{discode} if it did not display enough.  It may display more, if
1.78      anton    12745: the code word is not immediately followed by a named word.  If you have
1.116     anton    12746: something else there, you can follow the word with @code{align latest ,}
1.78      anton    12747: to ensure that the end is recognized.
1.21      crook    12748: 
1.78      anton    12749: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
                   12750: @subsection 386 Assembler
1.44      crook    12751: 
1.78      anton    12752: The 386 assembler included in Gforth was written by Bernd Paysan, it's
                   12753: available under GPL, and originally part of bigFORTH.
1.21      crook    12754: 
1.78      anton    12755: The 386 disassembler included in Gforth was written by Andrew McKewan
                   12756: and is in the public domain.
1.21      crook    12757: 
1.91      anton    12758: The disassembler displays code in an Intel-like prefix syntax.
1.21      crook    12759: 
1.78      anton    12760: The assembler uses a postfix syntax with reversed parameters.
1.1       anton    12761: 
1.78      anton    12762: The assembler includes all instruction of the Athlon, i.e. 486 core
                   12763: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
                   12764: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
                   12765: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1       anton    12766: 
1.78      anton    12767: There are several prefixes to switch between different operation sizes,
                   12768: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
                   12769: double-word accesses. Addressing modes can be switched with @code{.wa}
                   12770: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
                   12771: need a prefix for byte register names (@code{AL} et al).
1.1       anton    12772: 
1.78      anton    12773: For floating point operations, the prefixes are @code{.fs} (IEEE
                   12774: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
                   12775: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21      crook    12776: 
1.78      anton    12777: The MMX opcodes don't have size prefixes, they are spelled out like in
                   12778: the Intel assembler. Instead of move from and to memory, there are
                   12779: PLDQ/PLDD and PSTQ/PSTD.
1.21      crook    12780: 
1.78      anton    12781: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
                   12782: ax.  Immediate values are indicated by postfixing them with @code{#},
1.91      anton    12783: e.g., @code{3 #}.  Here are some examples of addressing modes in various
                   12784: syntaxes:
1.21      crook    12785: 
1.26      crook    12786: @example
1.91      anton    12787: Gforth          Intel (NASM)   AT&T (gas)      Name
                   12788: .w ax           ax             %ax             register (16 bit)
                   12789: ax              eax            %eax            register (32 bit)
                   12790: 3 #             offset 3       $3              immediate
                   12791: 1000 #)         byte ptr 1000  1000            displacement
                   12792: bx )            [ebx]          (%ebx)          base
                   12793: 100 di d)       100[edi]       100(%edi)       base+displacement
                   12794: 20 ax *4 i#)    20[eax*4]      20(,%eax,4)     (index*scale)+displacement
                   12795: di ax *4 i)     [edi][eax*4]   (%edi,%eax,4)   base+(index*scale)
                   12796: 4 bx cx di)     4[ebx][ecx]    4(%ebx,%ecx)    base+index+displacement
                   12797: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
                   12798: @end example
                   12799: 
                   12800: You can use @code{L)} and @code{LI)} instead of @code{D)} and
                   12801: @code{DI)} to enforce 32-bit displacement fields (useful for
                   12802: later patching).
1.21      crook    12803: 
1.78      anton    12804: Some example of instructions are:
1.1       anton    12805: 
                   12806: @example
1.78      anton    12807: ax bx mov             \ move ebx,eax
                   12808: 3 # ax mov            \ mov eax,3
1.137     pazsan   12809: 100 di d) ax mov      \ mov eax,100[edi]
1.78      anton    12810: 4 bx cx di) ax mov    \ mov eax,4[ebx][ecx]
                   12811: .w ax bx mov          \ mov bx,ax
1.1       anton    12812: @end example
                   12813: 
1.78      anton    12814: The following forms are supported for binary instructions:
1.1       anton    12815: 
                   12816: @example
1.78      anton    12817: <reg> <reg> <inst>
                   12818: <n> # <reg> <inst>
                   12819: <mem> <reg> <inst>
                   12820: <reg> <mem> <inst>
1.136     pazsan   12821: <n> # <mem> <inst>
1.1       anton    12822: @end example
                   12823: 
1.136     pazsan   12824: The shift/rotate syntax is:
1.1       anton    12825: 
1.26      crook    12826: @example
1.78      anton    12827: <reg/mem> 1 # shl \ shortens to shift without immediate
                   12828: <reg/mem> 4 # shl
                   12829: <reg/mem> cl shl
1.26      crook    12830: @end example
1.1       anton    12831: 
1.78      anton    12832: Precede string instructions (@code{movs} etc.) with @code{.b} to get
                   12833: the byte version.
1.1       anton    12834: 
1.78      anton    12835: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
                   12836: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
                   12837: pc < >= <= >}. (Note that most of these words shadow some Forth words
                   12838: when @code{assembler} is in front of @code{forth} in the search path,
                   12839: e.g., in @code{code} words).  Currently the control structure words use
                   12840: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
                   12841: to shuffle them (you can also use @code{swap} etc.).
1.21      crook    12842: 
1.78      anton    12843: Here is an example of a @code{code} word (assumes that the stack pointer
                   12844: is in esi and the TOS is in ebx):
1.21      crook    12845: 
1.26      crook    12846: @example
1.78      anton    12847: code my+ ( n1 n2 -- n )
                   12848:     4 si D) bx add
                   12849:     4 # si add
                   12850:     Next
                   12851: end-code
1.26      crook    12852: @end example
1.21      crook    12853: 
1.161     anton    12854: 
1.78      anton    12855: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
                   12856: @subsection Alpha Assembler
1.21      crook    12857: 
1.78      anton    12858: The Alpha assembler and disassembler were originally written by Bernd
                   12859: Thallner.
1.26      crook    12860: 
1.78      anton    12861: The register names @code{a0}--@code{a5} are not available to avoid
                   12862: shadowing hex numbers.
1.2       jwilke   12863: 
1.78      anton    12864: Immediate forms of arithmetic instructions are distinguished by a
                   12865: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
                   12866: does not count as arithmetic instruction).
1.2       jwilke   12867: 
1.78      anton    12868: You have to specify all operands to an instruction, even those that
                   12869: other assemblers consider optional, e.g., the destination register for
                   12870: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2       jwilke   12871: 
1.78      anton    12872: You can specify conditions for @code{if,} by removing the first @code{b}
                   12873: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2       jwilke   12874: 
1.26      crook    12875: @example
1.78      anton    12876: 11 fgt if, \ if F11>0e
                   12877:   ...
                   12878: endif,
1.26      crook    12879: @end example
1.2       jwilke   12880: 
1.78      anton    12881: @code{fbgt,} gives @code{fgt}.  
                   12882: 
1.161     anton    12883: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78      anton    12884: @subsection MIPS assembler
1.2       jwilke   12885: 
1.78      anton    12886: The MIPS assembler was originally written by Christian Pirker.
1.2       jwilke   12887: 
1.78      anton    12888: Currently the assembler and disassembler only cover the MIPS-I
                   12889: architecture (R3000), and don't support FP instructions.
1.2       jwilke   12890: 
1.78      anton    12891: The register names @code{$a0}--@code{$a3} are not available to avoid
                   12892: shadowing hex numbers.
1.2       jwilke   12893: 
1.78      anton    12894: Because there is no way to distinguish registers from immediate values,
                   12895: you have to explicitly use the immediate forms of instructions, i.e.,
                   12896: @code{addiu,}, not just @code{addu,} (@command{as} does this
                   12897: implicitly).
1.2       jwilke   12898: 
1.78      anton    12899: If the architecture manual specifies several formats for the instruction
                   12900: (e.g., for @code{jalr,}), you usually have to use the one with more
                   12901: arguments (i.e., two for @code{jalr,}).  When in doubt, see
                   12902: @code{arch/mips/testasm.fs} for an example of correct use.
1.2       jwilke   12903: 
1.78      anton    12904: Branches and jumps in the MIPS architecture have a delay slot.  You have
                   12905: to fill it yourself (the simplest way is to use @code{nop,}), the
                   12906: assembler does not do it for you (unlike @command{as}).  Even
                   12907: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
                   12908: @code{else,} and @code{repeat,} need a delay slot.  Since @code{begin,}
                   12909: and @code{then,} just specify branch targets, they are not affected.
1.2       jwilke   12910: 
1.78      anton    12911: Note that you must not put branches, jumps, or @code{li,} into the delay
                   12912: slot: @code{li,} may expand to several instructions, and control flow
                   12913: instructions may not be put into the branch delay slot in any case.
1.2       jwilke   12914: 
1.78      anton    12915: For branches the argument specifying the target is a relative address;
                   12916: You have to add the address of the delay slot to get the absolute
                   12917: address.
1.1       anton    12918: 
1.78      anton    12919: The MIPS architecture also has load delay slots and restrictions on
                   12920: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
                   12921: yourself to satisfy these restrictions, the assembler does not do it for
                   12922: you.
1.1       anton    12923: 
1.78      anton    12924: You can specify the conditions for @code{if,} etc. by taking a
                   12925: conditional branch and leaving away the @code{b} at the start and the
                   12926: @code{,} at the end.  E.g.,
1.1       anton    12927: 
1.26      crook    12928: @example
1.78      anton    12929: 4 5 eq if,
                   12930:   ... \ do something if $4 equals $5
                   12931: then,
1.26      crook    12932: @end example
1.1       anton    12933: 
1.161     anton    12934: 
1.193     dvdkhlng 12935: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
1.161     anton    12936: @subsection PowerPC assembler
                   12937: 
1.162     anton    12938: The PowerPC assembler and disassembler were contributed by Michal
1.161     anton    12939: Revucky.
                   12940: 
1.162     anton    12941: This assembler does not follow the convention of ending mnemonic names
                   12942: with a ``,'', so some mnemonic names shadow regular Forth words (in
                   12943: particular: @code{and or xor fabs}); so if you want to use the Forth
                   12944: words, you have to make them visible first, e.g., with @code{also
                   12945: forth}.
                   12946: 
1.161     anton    12947: Registers are referred to by their number, e.g., @code{9} means the
                   12948: integer register 9 or the FP register 9 (depending on the
                   12949: instruction).
                   12950: 
                   12951: Because there is no way to distinguish registers from immediate values,
                   12952: you have to explicitly use the immediate forms of instructions, i.e.,
1.162     anton    12953: @code{addi,}, not just @code{add,}.
1.161     anton    12954: 
1.162     anton    12955: The assembler and disassembler usually support the most general form
1.161     anton    12956: of an instruction, but usually not the shorter forms (especially for
                   12957: branches).
                   12958: 
                   12959: 
1.193     dvdkhlng 12960: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
                   12961: @subsection ARM Assembler
1.161     anton    12962: 
1.193     dvdkhlng 12963: The ARM assembler included in Gforth was written from scratch by David
                   12964: Kuehling.
                   12965: 
                   12966: The assembler includes all instruction of ARM architecture version 4,
                   12967: but does not (yet) have support for Thumb instructions.  It also lacks
                   12968: support for any co-processors.
                   12969: 
                   12970: The assembler uses a postfix syntax with the target operand specified
                   12971: last.  For load/store instructions the last operand will be the
                   12972: register(s) to be loaded from/stored to.
                   12973: 
                   12974: Registers are specified by their names @code{r0} through @code{r15},
                   12975: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
                   12976: @code{fp} provided for convenience.  Note that @code{ip} means intra
                   12977: procedure call scratch register (@code{r12}) and does not refer to the
                   12978: instruction pointer.
                   12979: 
                   12980: Condition codes can be specified anywhere in the instruction, but will
                   12981: be most readable if specified just in front of the mnemonic.  The 'S'
                   12982: flag is not a separate word, but encoded into instruction mnemonics,
                   12983: ie. just use @code{adds,} instead of @code{add,} if you want the
                   12984: status register to be updated.
                   12985: 
                   12986: The following table lists the syntax of operands for general
                   12987: instructions:
                   12988: 
                   12989: @example
                   12990: Gforth          normal assembler      description
                   12991: 123 #           #123                  immediate
                   12992: r12             r12                   register
                   12993: r12 4 #LSL      r12, LSL #4           shift left by immediate
                   12994: r12 r1 #LSL     r12, LSL r1           shift left by register
                   12995: r12 4 #LSR      r12, LSR #4           shift right by immediate
                   12996: r12 r1 #LSR     r12, LSR r1           shift right by register
                   12997: r12 4 #ASR      r12, ASR #4           arithmetic shift right
                   12998: r12 r1 #ASR     r12, ASR r1           ... by register
                   12999: r12 4 #ROR      r12, ROR #4           rotate right by immediate
                   13000: r12 r1 #ROR     r12, ROR r1           ... by register
                   13001: r12 RRX         r12, RRX              rotate right with extend by 1
                   13002: @end example
                   13003: 
                   13004: Memory operand syntax is listed in this table:
                   13005: 
                   13006: @example
                   13007: Gforth            normal assembler      description
                   13008: r4 ]              [r4]                  register
                   13009: r4 4 #]           [r4, #+4]             register with immediate offset
                   13010: r4 -4 #]          [r4, #-4]             with negative offset
                   13011: r4 r1 +]          [r4, +r1]             register with register offset
                   13012: r4 r1 -]          [r4, -r1]             with negated register offset
                   13013: r4 r1 2 #LSL -]   [r4, -r1, LSL #2]     with negated and shifted offset
                   13014: r4 4 #]!          [r4, #+4]!            immediate preincrement
                   13015: r4 r1 +]!         [r4, +r1]!            register preincrement
                   13016: r4 r1 -]!         [r4, +r1]!            register predecrement
                   13017: r4 r1 2 #LSL +]!  [r4, +r1, LSL #2]!    shifted preincrement
                   13018: r4 -4 ]#          [r4], #-4             immediate postdecrement
                   13019: r4 r1 ]+          [r4], r1              register postincrement
                   13020: r4 r1 ]-          [r4], -r1             register postdecrement
                   13021: r4 r1 2 #LSL ]-   [r4], -r1, LSL #2     shifted postdecrement
                   13022: ' xyz >body [#]   xyz                   PC-relative addressing
                   13023: @end example
                   13024: 
                   13025: Register lists for load/store multiple instructions are started and
                   13026: terminated by using the words @code{@{} and @code{@}}
                   13027: respectivly.  Between braces, register names can be listed one by one,
                   13028: or register ranges can be formed by using the postfix operator
                   13029: @code{r-r}.  The @code{^} flag is not encoded in the register list
                   13030: operand, but instead directly encoded into the instruction mnemonic,
                   13031: ie. use @code{^ldm,} and @code{^stm,}.
                   13032: 
                   13033: Addressing modes for load/store multiple are not encoded as
                   13034: instruction suffixes, but instead specified after the register that
                   13035: supplies the address.  Use one of @code{DA}, @code{IA}, @code{DB},
                   13036: @code{IB}, @code{DA!}, @code{IA!}, @code{DB!} or @code{IB!}.
                   13037: 
                   13038: The following table gives some examples:
                   13039: 
                   13040: @example
                   13041: Gforth                           normal assembler
                   13042: @{ r0 r7 r8 @}  r4 ia  stm,        stmia    @{r0,r7,r8@}, r4
                   13043: @{ r0 r7 r8 @}  r4 db!  ldm,       ldmdb    @{r0,r7,r8@}, r4!
                   13044: @{ r0 r15 r-r @}  sp ia!  ^ldm,    ldmfd    @{r0-r15@}^, sp!
                   13045: @end example
                   13046: 
                   13047: Conditions for control structure words are specified in front of a
                   13048: word:
                   13049: 
                   13050: @example
                   13051: r1 r2 cmp,    \ compare r1 and r2
                   13052: eq if,        \ equal?
                   13053:    ...          \ code executed if r1 == r2
                   13054: then,
                   13055: @end example
                   13056: 
                   13057: Here is an example of a @code{code} word (assumes that the stack
                   13058: pointer is in @code{r9}, and that @code{r2} and @code{r3} can be
                   13059: clobbered):
                   13060: 
                   13061: @example
                   13062: code my+ ( n1 n2 --  n3 )
                   13063:    r9 IA!       @{ r2 r3 @} ldm,  \ pop r2 = n2, r3 = n1
                   13064:    r2   r3      r3        add,  \ r3 = n2+n1
                   13065:    r9 -4 #]!    r3        str,  \ push r3
                   13066:    next,
                   13067: end-code
                   13068: @end example
                   13069: 
                   13070: Look at @file{arch/arm/asm-example.fs} for more examples.
                   13071: 
                   13072: @node Other assemblers,  , ARM Assembler, Assembler and Code Words
1.78      anton    13073: @subsection Other assemblers
                   13074: 
                   13075: If you want to contribute another assembler/disassembler, please contact
1.103     anton    13076: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
                   13077: an assembler already.  If you are writing them from scratch, please use
                   13078: a similar syntax style as the one we use (i.e., postfix, commas at the
                   13079: end of the instruction names, @pxref{Common Assembler}); make the output
                   13080: of the disassembler be valid input for the assembler, and keep the style
1.78      anton    13081: similar to the style we used.
                   13082: 
                   13083: Hints on implementation: The most important part is to have a good test
                   13084: suite that contains all instructions.  Once you have that, the rest is
                   13085: easy.  For actual coding you can take a look at
                   13086: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
                   13087: the assembler and disassembler, avoiding redundancy and some potential
                   13088: bugs.  You can also look at that file (and @pxref{Advanced does> usage
                   13089: example}) to get ideas how to factor a disassembler.
                   13090: 
                   13091: Start with the disassembler, because it's easier to reuse data from the
                   13092: disassembler for the assembler than the other way round.
1.1       anton    13093: 
1.78      anton    13094: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
                   13095: how simple it can be.
1.1       anton    13096: 
1.161     anton    13097: 
                   13098: 
                   13099: 
1.78      anton    13100: @c -------------------------------------------------------------
                   13101: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
                   13102: @section Threading Words
                   13103: @cindex threading words
1.1       anton    13104: 
1.78      anton    13105: @cindex code address
                   13106: These words provide access to code addresses and other threading stuff
                   13107: in Gforth (and, possibly, other interpretive Forths). It more or less
                   13108: abstracts away the differences between direct and indirect threading
                   13109: (and, for direct threading, the machine dependences). However, at
                   13110: present this wordset is still incomplete. It is also pretty low-level;
                   13111: some day it will hopefully be made unnecessary by an internals wordset
                   13112: that abstracts implementation details away completely.
1.1       anton    13113: 
1.78      anton    13114: The terminology used here stems from indirect threaded Forth systems; in
                   13115: such a system, the XT of a word is represented by the CFA (code field
                   13116: address) of a word; the CFA points to a cell that contains the code
                   13117: address.  The code address is the address of some machine code that
                   13118: performs the run-time action of invoking the word (e.g., the
                   13119: @code{dovar:} routine pushes the address of the body of the word (a
                   13120: variable) on the stack
                   13121: ).
1.1       anton    13122: 
1.78      anton    13123: @cindex code address
                   13124: @cindex code field address
                   13125: In an indirect threaded Forth, you can get the code address of @i{name}
                   13126: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
                   13127: >code-address}, independent of the threading method.
1.1       anton    13128: 
1.78      anton    13129: doc-threading-method
                   13130: doc->code-address
                   13131: doc-code-address!
1.1       anton    13132: 
1.78      anton    13133: @cindex @code{does>}-handler
                   13134: @cindex @code{does>}-code
                   13135: For a word defined with @code{DOES>}, the code address usually points to
                   13136: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
                   13137: routine (in Gforth on some platforms, it can also point to the dodoes
                   13138: routine itself).  What you are typically interested in, though, is
                   13139: whether a word is a @code{DOES>}-defined word, and what Forth code it
                   13140: executes; @code{>does-code} tells you that.
1.1       anton    13141: 
1.78      anton    13142: doc->does-code
1.1       anton    13143: 
1.78      anton    13144: To create a @code{DOES>}-defined word with the following basic words,
                   13145: you have to set up a @code{DOES>}-handler with @code{does-handler!};
                   13146: @code{/does-handler} aus behind you have to place your executable Forth
                   13147: code.  Finally you have to create a word and modify its behaviour with
                   13148: @code{does-handler!}.
1.1       anton    13149: 
1.78      anton    13150: doc-does-code!
                   13151: doc-does-handler!
                   13152: doc-/does-handler
1.1       anton    13153: 
1.78      anton    13154: The code addresses produced by various defining words are produced by
                   13155: the following words:
1.1       anton    13156: 
1.78      anton    13157: doc-docol:
                   13158: doc-docon:
                   13159: doc-dovar:
                   13160: doc-douser:
                   13161: doc-dodefer:
                   13162: doc-dofield:
1.1       anton    13163: 
1.99      anton    13164: @cindex definer
                   13165: The following two words generalize @code{>code-address},
                   13166: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
                   13167: 
                   13168: doc->definer
                   13169: doc-definer!
                   13170: 
1.26      crook    13171: @c -------------------------------------------------------------
1.78      anton    13172: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21      crook    13173: @section Passing Commands to the Operating System
                   13174: @cindex operating system - passing commands
                   13175: @cindex shell commands
                   13176: 
                   13177: Gforth allows you to pass an arbitrary string to the host operating
                   13178: system shell (if such a thing exists) for execution.
                   13179: 
                   13180: doc-sh
                   13181: doc-system
                   13182: doc-$?
1.23      crook    13183: doc-getenv
1.44      crook    13184: 
1.26      crook    13185: @c -------------------------------------------------------------
1.47      crook    13186: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
                   13187: @section Keeping track of Time
                   13188: @cindex time-related words
                   13189: 
                   13190: doc-ms
                   13191: doc-time&date
1.79      anton    13192: doc-utime
                   13193: doc-cputime
1.47      crook    13194: 
                   13195: 
                   13196: @c -------------------------------------------------------------
                   13197: @node Miscellaneous Words,  , Keeping track of Time, Words
1.21      crook    13198: @section Miscellaneous Words
                   13199: @cindex miscellaneous words
                   13200: 
1.29      crook    13201: @comment TODO find homes for these
                   13202: 
1.26      crook    13203: These section lists the ANS Forth words that are not documented
1.21      crook    13204: elsewhere in this manual. Ultimately, they all need proper homes.
                   13205: 
1.68      anton    13206: doc-quit
1.44      crook    13207: 
1.26      crook    13208: The following ANS Forth words are not currently supported by Gforth 
1.27      crook    13209: (@pxref{ANS conformance}):
1.21      crook    13210: 
                   13211: @code{EDITOR} 
                   13212: @code{EMIT?} 
                   13213: @code{FORGET} 
                   13214: 
1.24      anton    13215: @c ******************************************************************
                   13216: @node Error messages, Tools, Words, Top
                   13217: @chapter Error messages
                   13218: @cindex error messages
                   13219: @cindex backtrace
                   13220: 
                   13221: A typical Gforth error message looks like this:
                   13222: 
                   13223: @example
1.86      anton    13224: in file included from \evaluated string/:-1
1.24      anton    13225: in file included from ./yyy.fs:1
                   13226: ./xxx.fs:4: Invalid memory address
1.134     anton    13227: >>>bar<<<
1.79      anton    13228: Backtrace:
1.25      anton    13229: $400E664C @@
                   13230: $400E6664 foo
1.24      anton    13231: @end example
                   13232: 
                   13233: The message identifying the error is @code{Invalid memory address}.  The
                   13234: error happened when text-interpreting line 4 of the file
                   13235: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
                   13236: word on the line where the error happened, is pointed out (with
1.134     anton    13237: @code{>>>} and @code{<<<}).
1.24      anton    13238: 
                   13239: The file containing the error was included in line 1 of @file{./yyy.fs},
                   13240: and @file{yyy.fs} was included from a non-file (in this case, by giving
                   13241: @file{yyy.fs} as command-line parameter to Gforth).
                   13242: 
                   13243: At the end of the error message you find a return stack dump that can be
                   13244: interpreted as a backtrace (possibly empty). On top you find the top of
                   13245: the return stack when the @code{throw} happened, and at the bottom you
                   13246: find the return stack entry just above the return stack of the topmost
                   13247: text interpreter.
                   13248: 
                   13249: To the right of most return stack entries you see a guess for the word
                   13250: that pushed that return stack entry as its return address. This gives a
                   13251: backtrace. In our case we see that @code{bar} called @code{foo}, and
                   13252: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
                   13253: address} exception).
                   13254: 
                   13255: Note that the backtrace is not perfect: We don't know which return stack
                   13256: entries are return addresses (so we may get false positives); and in
                   13257: some cases (e.g., for @code{abort"}) we cannot determine from the return
                   13258: address the word that pushed the return address, so for some return
                   13259: addresses you see no names in the return stack dump.
1.25      anton    13260: 
                   13261: @cindex @code{catch} and backtraces
                   13262: The return stack dump represents the return stack at the time when a
                   13263: specific @code{throw} was executed.  In programs that make use of
                   13264: @code{catch}, it is not necessarily clear which @code{throw} should be
                   13265: used for the return stack dump (e.g., consider one @code{throw} that
                   13266: indicates an error, which is caught, and during recovery another error
1.160     anton    13267: happens; which @code{throw} should be used for the stack dump?).
                   13268: Gforth presents the return stack dump for the first @code{throw} after
                   13269: the last executed (not returned-to) @code{catch} or @code{nothrow};
                   13270: this works well in the usual case. To get the right backtrace, you
                   13271: usually want to insert @code{nothrow} or @code{['] false catch drop}
                   13272: after a @code{catch} if the error is not rethrown.
1.25      anton    13273: 
                   13274: @cindex @code{gforth-fast} and backtraces
                   13275: @cindex @code{gforth-fast}, difference from @code{gforth}
                   13276: @cindex backtraces with @code{gforth-fast}
                   13277: @cindex return stack dump with @code{gforth-fast}
1.79      anton    13278: @code{Gforth} is able to do a return stack dump for throws generated
1.25      anton    13279: from primitives (e.g., invalid memory address, stack empty etc.);
                   13280: @code{gforth-fast} is only able to do a return stack dump from a
1.96      anton    13281: directly called @code{throw} (including @code{abort} etc.).  Given an
1.30      anton    13282: exception caused by a primitive in @code{gforth-fast}, you will
                   13283: typically see no return stack dump at all; however, if the exception is
                   13284: caught by @code{catch} (e.g., for restoring some state), and then
                   13285: @code{throw}n again, the return stack dump will be for the first such
                   13286: @code{throw}.
1.2       jwilke   13287: 
1.5       anton    13288: @c ******************************************************************
1.24      anton    13289: @node Tools, ANS conformance, Error messages, Top
1.1       anton    13290: @chapter Tools
                   13291: 
                   13292: @menu
                   13293: * ANS Report::                  Report the words used, sorted by wordset.
1.127     anton    13294: * Stack depth changes::         Where does this stack item come from?
1.1       anton    13295: @end menu
                   13296: 
                   13297: See also @ref{Emacs and Gforth}.
                   13298: 
1.126     pazsan   13299: @node ANS Report, Stack depth changes, Tools, Tools
1.1       anton    13300: @section @file{ans-report.fs}: Report the words used, sorted by wordset
                   13301: @cindex @file{ans-report.fs}
                   13302: @cindex report the words used in your program
                   13303: @cindex words used in your program
                   13304: 
                   13305: If you want to label a Forth program as ANS Forth Program, you must
                   13306: document which wordsets the program uses; for extension wordsets, it is
                   13307: helpful to list the words the program requires from these wordsets
                   13308: (because Forth systems are allowed to provide only some words of them).
                   13309: 
                   13310: The @file{ans-report.fs} tool makes it easy for you to determine which
                   13311: words from which wordset and which non-ANS words your application
                   13312: uses. You simply have to include @file{ans-report.fs} before loading the
                   13313: program you want to check. After loading your program, you can get the
                   13314: report with @code{print-ans-report}. A typical use is to run this as
                   13315: batch job like this:
                   13316: @example
                   13317: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
                   13318: @end example
                   13319: 
                   13320: The output looks like this (for @file{compat/control.fs}):
                   13321: @example
                   13322: The program uses the following words
                   13323: from CORE :
                   13324: : POSTPONE THEN ; immediate ?dup IF 0= 
                   13325: from BLOCK-EXT :
                   13326: \ 
                   13327: from FILE :
                   13328: ( 
                   13329: @end example
                   13330: 
                   13331: @subsection Caveats
                   13332: 
                   13333: Note that @file{ans-report.fs} just checks which words are used, not whether
                   13334: they are used in an ANS Forth conforming way!
                   13335: 
                   13336: Some words are defined in several wordsets in the
                   13337: standard. @file{ans-report.fs} reports them for only one of the
                   13338: wordsets, and not necessarily the one you expect. It depends on usage
                   13339: which wordset is the right one to specify. E.g., if you only use the
                   13340: compilation semantics of @code{S"}, it is a Core word; if you also use
                   13341: its interpretation semantics, it is a File word.
1.124     anton    13342: 
                   13343: 
1.127     anton    13344: @node Stack depth changes,  , ANS Report, Tools
1.124     anton    13345: @section Stack depth changes during interpretation
                   13346: @cindex @file{depth-changes.fs}
                   13347: @cindex depth changes during interpretation
                   13348: @cindex stack depth changes during interpretation
                   13349: @cindex items on the stack after interpretation
                   13350: 
                   13351: Sometimes you notice that, after loading a file, there are items left
                   13352: on the stack.  The tool @file{depth-changes.fs} helps you find out
                   13353: quickly where in the file these stack items are coming from.
                   13354: 
                   13355: The simplest way of using @file{depth-changes.fs} is to include it
                   13356: before the file(s) you want to check, e.g.:
                   13357: 
                   13358: @example
                   13359: gforth depth-changes.fs my-file.fs
                   13360: @end example
                   13361: 
                   13362: This will compare the stack depths of the data and FP stack at every
                   13363: empty line (in interpretation state) against these depths at the last
                   13364: empty line (in interpretation state).  If the depths are not equal,
                   13365: the position in the file and the stack contents are printed with
                   13366: @code{~~} (@pxref{Debugging}).  This indicates that a stack depth
                   13367: change has occured in the paragraph of non-empty lines before the
                   13368: indicated line.  It is a good idea to leave an empty line at the end
                   13369: of the file, so the last paragraph is checked, too.
                   13370: 
                   13371: Checking only at empty lines usually works well, but sometimes you
                   13372: have big blocks of non-empty lines (e.g., when building a big table),
                   13373: and you want to know where in this block the stack depth changed.  You
                   13374: can check all interpreted lines with
                   13375: 
                   13376: @example
                   13377: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
                   13378: @end example
                   13379: 
                   13380: This checks the stack depth at every end-of-line.  So the depth change
                   13381: occured in the line reported by the @code{~~} (not in the line
                   13382: before).
                   13383: 
                   13384: Note that, while this offers better accuracy in indicating where the
                   13385: stack depth changes, it will often report many intentional stack depth
                   13386: changes (e.g., when an interpreted computation stretches across
                   13387: several lines).  You can suppress the checking of some lines by
                   13388: putting backslashes at the end of these lines (not followed by white
                   13389: space), and using
                   13390: 
                   13391: @example
                   13392: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
                   13393: @end example
1.1       anton    13394: 
                   13395: @c ******************************************************************
1.65      anton    13396: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1       anton    13397: @chapter ANS conformance
                   13398: @cindex ANS conformance of Gforth
                   13399: 
                   13400: To the best of our knowledge, Gforth is an
                   13401: 
                   13402: ANS Forth System
                   13403: @itemize @bullet
                   13404: @item providing the Core Extensions word set
                   13405: @item providing the Block word set
                   13406: @item providing the Block Extensions word set
                   13407: @item providing the Double-Number word set
                   13408: @item providing the Double-Number Extensions word set
                   13409: @item providing the Exception word set
                   13410: @item providing the Exception Extensions word set
                   13411: @item providing the Facility word set
1.40      anton    13412: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1       anton    13413: @item providing the File Access word set
                   13414: @item providing the File Access Extensions word set
                   13415: @item providing the Floating-Point word set
                   13416: @item providing the Floating-Point Extensions word set
                   13417: @item providing the Locals word set
                   13418: @item providing the Locals Extensions word set
                   13419: @item providing the Memory-Allocation word set
                   13420: @item providing the Memory-Allocation Extensions word set (that one's easy)
                   13421: @item providing the Programming-Tools word set
                   13422: @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
                   13423: @item providing the Search-Order word set
                   13424: @item providing the Search-Order Extensions word set
                   13425: @item providing the String word set
                   13426: @item providing the String Extensions word set (another easy one)
                   13427: @end itemize
                   13428: 
1.118     anton    13429: Gforth has the following environmental restrictions:
                   13430: 
                   13431: @cindex environmental restrictions
                   13432: @itemize @bullet
                   13433: @item
                   13434: While processing the OS command line, if an exception is not caught,
                   13435: Gforth exits with a non-zero exit code instyead of performing QUIT.
                   13436: 
                   13437: @item
                   13438: When an @code{throw} is performed after a @code{query}, Gforth does not
                   13439: allways restore the input source specification in effect at the
                   13440: corresponding catch.
                   13441: 
                   13442: @end itemize
                   13443: 
                   13444: 
1.1       anton    13445: @cindex system documentation
                   13446: In addition, ANS Forth systems are required to document certain
                   13447: implementation choices. This chapter tries to meet these
                   13448: requirements. In many cases it gives a way to ask the system for the
                   13449: information instead of providing the information directly, in
                   13450: particular, if the information depends on the processor, the operating
                   13451: system or the installation options chosen, or if they are likely to
                   13452: change during the maintenance of Gforth.
                   13453: 
                   13454: @comment The framework for the rest has been taken from pfe.
                   13455: 
                   13456: @menu
                   13457: * The Core Words::              
                   13458: * The optional Block word set::  
                   13459: * The optional Double Number word set::  
                   13460: * The optional Exception word set::  
                   13461: * The optional Facility word set::  
                   13462: * The optional File-Access word set::  
                   13463: * The optional Floating-Point word set::  
                   13464: * The optional Locals word set::  
                   13465: * The optional Memory-Allocation word set::  
                   13466: * The optional Programming-Tools word set::  
                   13467: * The optional Search-Order word set::  
                   13468: @end menu
                   13469: 
                   13470: 
                   13471: @c =====================================================================
                   13472: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
                   13473: @comment  node-name,  next,  previous,  up
                   13474: @section The Core Words
                   13475: @c =====================================================================
                   13476: @cindex core words, system documentation
                   13477: @cindex system documentation, core words
                   13478: 
                   13479: @menu
                   13480: * core-idef::                   Implementation Defined Options                   
                   13481: * core-ambcond::                Ambiguous Conditions                
                   13482: * core-other::                  Other System Documentation                  
                   13483: @end menu
                   13484: 
                   13485: @c ---------------------------------------------------------------------
                   13486: @node core-idef, core-ambcond, The Core Words, The Core Words
                   13487: @subsection Implementation Defined Options
                   13488: @c ---------------------------------------------------------------------
                   13489: @cindex core words, implementation-defined options
                   13490: @cindex implementation-defined options, core words
                   13491: 
                   13492: 
                   13493: @table @i
                   13494: @item (Cell) aligned addresses:
                   13495: @cindex cell-aligned addresses
                   13496: @cindex aligned addresses
                   13497: processor-dependent. Gforth's alignment words perform natural alignment
                   13498: (e.g., an address aligned for a datum of size 8 is divisible by
                   13499: 8). Unaligned accesses usually result in a @code{-23 THROW}.
                   13500: 
                   13501: @item @code{EMIT} and non-graphic characters:
                   13502: @cindex @code{EMIT} and non-graphic characters
                   13503: @cindex non-graphic characters and @code{EMIT}
                   13504: The character is output using the C library function (actually, macro)
                   13505: @code{putc}.
                   13506: 
                   13507: @item character editing of @code{ACCEPT} and @code{EXPECT}:
                   13508: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
                   13509: @cindex editing in @code{ACCEPT} and @code{EXPECT}
                   13510: @cindex @code{ACCEPT}, editing
                   13511: @cindex @code{EXPECT}, editing
                   13512: This is modeled on the GNU readline library (@pxref{Readline
                   13513: Interaction, , Command Line Editing, readline, The GNU Readline
                   13514: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
                   13515: producing a full word completion every time you type it (instead of
1.28      crook    13516: producing the common prefix of all completions). @xref{Command-line editing}.
1.1       anton    13517: 
                   13518: @item character set:
                   13519: @cindex character set
                   13520: The character set of your computer and display device. Gforth is
                   13521: 8-bit-clean (but some other component in your system may make trouble).
                   13522: 
                   13523: @item Character-aligned address requirements:
                   13524: @cindex character-aligned address requirements
                   13525: installation-dependent. Currently a character is represented by a C
                   13526: @code{unsigned char}; in the future we might switch to @code{wchar_t}
                   13527: (Comments on that requested).
                   13528: 
                   13529: @item character-set extensions and matching of names:
                   13530: @cindex character-set extensions and matching of names
1.26      crook    13531: @cindex case-sensitivity for name lookup
                   13532: @cindex name lookup, case-sensitivity
                   13533: @cindex locale and case-sensitivity
1.21      crook    13534: Any character except the ASCII NUL character can be used in a
1.1       anton    13535: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47      crook    13536: matching is performed using the C library function @code{strncasecmp}, whose
1.1       anton    13537: function is probably influenced by the locale. E.g., the @code{C} locale
                   13538: does not know about accents and umlauts, so they are matched
                   13539: case-sensitively in that locale. For portability reasons it is best to
                   13540: write programs such that they work in the @code{C} locale. Then one can
                   13541: use libraries written by a Polish programmer (who might use words
                   13542: containing ISO Latin-2 encoded characters) and by a French programmer
                   13543: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
                   13544: funny results for some of the words (which ones, depends on the font you
                   13545: are using)). Also, the locale you prefer may not be available in other
                   13546: operating systems. Hopefully, Unicode will solve these problems one day.
                   13547: 
                   13548: @item conditions under which control characters match a space delimiter:
                   13549: @cindex space delimiters
                   13550: @cindex control characters as delimiters
1.117     anton    13551: If @code{word} is called with the space character as a delimiter, all
1.1       anton    13552: white-space characters (as identified by the C macro @code{isspace()})
1.117     anton    13553: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138     anton    13554: delimiters.  @code{Parse-name}, which is used by the outer
1.1       anton    13555: interpreter (aka text interpreter) by default, treats all white-space
                   13556: characters as delimiters.
                   13557: 
1.26      crook    13558: @item format of the control-flow stack:
                   13559: @cindex control-flow stack, format
                   13560: The data stack is used as control-flow stack. The size of a control-flow
1.1       anton    13561: stack item in cells is given by the constant @code{cs-item-size}. At the
                   13562: time of this writing, an item consists of a (pointer to a) locals list
                   13563: (third), an address in the code (second), and a tag for identifying the
                   13564: item (TOS). The following tags are used: @code{defstart},
                   13565: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
                   13566: @code{scopestart}.
                   13567: 
                   13568: @item conversion of digits > 35
                   13569: @cindex digits > 35
                   13570: The characters @code{[\]^_'} are the digits with the decimal value
                   13571: 36@minus{}41. There is no way to input many of the larger digits.
                   13572: 
                   13573: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
                   13574: @cindex @code{EXPECT}, display after end of input
                   13575: @cindex @code{ACCEPT}, display after end of input
                   13576: The cursor is moved to the end of the entered string. If the input is
                   13577: terminated using the @kbd{Return} key, a space is typed.
                   13578: 
                   13579: @item exception abort sequence of @code{ABORT"}:
                   13580: @cindex exception abort sequence of @code{ABORT"}
                   13581: @cindex @code{ABORT"}, exception abort sequence
                   13582: The error string is stored into the variable @code{"error} and a
                   13583: @code{-2 throw} is performed.
                   13584: 
                   13585: @item input line terminator:
                   13586: @cindex input line terminator
                   13587: @cindex line terminator on input
1.26      crook    13588: @cindex newline character on input
1.1       anton    13589: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
                   13590: lines. One of these characters is typically produced when you type the
                   13591: @kbd{Enter} or @kbd{Return} key.
                   13592: 
                   13593: @item maximum size of a counted string:
                   13594: @cindex maximum size of a counted string
                   13595: @cindex counted string, maximum size
                   13596: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79      anton    13597: on all platforms, but this may change.
1.1       anton    13598: 
                   13599: @item maximum size of a parsed string:
                   13600: @cindex maximum size of a parsed string
                   13601: @cindex parsed string, maximum size
                   13602: Given by the constant @code{/line}. Currently 255 characters.
                   13603: 
                   13604: @item maximum size of a definition name, in characters:
                   13605: @cindex maximum size of a definition name, in characters
                   13606: @cindex name, maximum length
1.113     anton    13607: MAXU/8
1.1       anton    13608: 
                   13609: @item maximum string length for @code{ENVIRONMENT?}, in characters:
                   13610: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
                   13611: @cindex @code{ENVIRONMENT?} string length, maximum
1.113     anton    13612: MAXU/8
1.1       anton    13613: 
                   13614: @item method of selecting the user input device:
                   13615: @cindex user input device, method of selecting
                   13616: The user input device is the standard input. There is currently no way to
                   13617: change it from within Gforth. However, the input can typically be
                   13618: redirected in the command line that starts Gforth.
                   13619: 
                   13620: @item method of selecting the user output device:
                   13621: @cindex user output device, method of selecting
                   13622: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10      anton    13623: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
                   13624: output when the user output device is a terminal, otherwise the output
                   13625: is buffered.
1.1       anton    13626: 
                   13627: @item methods of dictionary compilation:
                   13628: What are we expected to document here?
                   13629: 
                   13630: @item number of bits in one address unit:
                   13631: @cindex number of bits in one address unit
                   13632: @cindex address unit, size in bits
                   13633: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79      anton    13634: platforms.
1.1       anton    13635: 
                   13636: @item number representation and arithmetic:
                   13637: @cindex number representation and arithmetic
1.79      anton    13638: Processor-dependent. Binary two's complement on all current platforms.
1.1       anton    13639: 
                   13640: @item ranges for integer types:
                   13641: @cindex ranges for integer types
                   13642: @cindex integer types, ranges
                   13643: Installation-dependent. Make environmental queries for @code{MAX-N},
                   13644: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
                   13645: unsigned (and positive) types is 0. The lower bound for signed types on
                   13646: two's complement and one's complement machines machines can be computed
                   13647: by adding 1 to the upper bound.
                   13648: 
                   13649: @item read-only data space regions:
                   13650: @cindex read-only data space regions
                   13651: @cindex data-space, read-only regions
                   13652: The whole Forth data space is writable.
                   13653: 
                   13654: @item size of buffer at @code{WORD}:
                   13655: @cindex size of buffer at @code{WORD}
                   13656: @cindex @code{WORD} buffer size
                   13657: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   13658: shared with the pictured numeric output string. If overwriting
                   13659: @code{PAD} is acceptable, it is as large as the remaining dictionary
                   13660: space, although only as much can be sensibly used as fits in a counted
                   13661: string.
                   13662: 
                   13663: @item size of one cell in address units:
                   13664: @cindex cell size
                   13665: @code{1 cells .}.
                   13666: 
                   13667: @item size of one character in address units:
                   13668: @cindex char size
1.79      anton    13669: @code{1 chars .}. 1 on all current platforms.
1.1       anton    13670: 
                   13671: @item size of the keyboard terminal buffer:
                   13672: @cindex size of the keyboard terminal buffer
                   13673: @cindex terminal buffer, size
                   13674: Varies. You can determine the size at a specific time using @code{lp@@
                   13675: tib - .}. It is shared with the locals stack and TIBs of files that
                   13676: include the current file. You can change the amount of space for TIBs
                   13677: and locals stack at Gforth startup with the command line option
                   13678: @code{-l}.
                   13679: 
                   13680: @item size of the pictured numeric output buffer:
                   13681: @cindex size of the pictured numeric output buffer
                   13682: @cindex pictured numeric output buffer, size
                   13683: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
                   13684: shared with @code{WORD}.
                   13685: 
                   13686: @item size of the scratch area returned by @code{PAD}:
                   13687: @cindex size of the scratch area returned by @code{PAD}
                   13688: @cindex @code{PAD} size
                   13689: The remainder of dictionary space. @code{unused pad here - - .}.
                   13690: 
                   13691: @item system case-sensitivity characteristics:
                   13692: @cindex case-sensitivity characteristics
1.26      crook    13693: Dictionary searches are case-insensitive (except in
1.1       anton    13694: @code{TABLE}s). However, as explained above under @i{character-set
                   13695: extensions}, the matching for non-ASCII characters is determined by the
                   13696: locale you are using. In the default @code{C} locale all non-ASCII
                   13697: characters are matched case-sensitively.
                   13698: 
                   13699: @item system prompt:
                   13700: @cindex system prompt
                   13701: @cindex prompt
                   13702: @code{ ok} in interpret state, @code{ compiled} in compile state.
                   13703: 
                   13704: @item division rounding:
                   13705: @cindex division rounding
1.166     anton    13706: The ordinary division words @code{/ mod /mod */ */mod} perform floored
                   13707: division (with the default installation of Gforth).  You can check
                   13708: this with @code{s" floored" environment? drop .}.  If you write
                   13709: programs that need a specific division rounding, best use
                   13710: @code{fm/mod} or @code{sm/rem} for portability.
1.1       anton    13711: 
                   13712: @item values of @code{STATE} when true:
                   13713: @cindex @code{STATE} values
                   13714: -1.
                   13715: 
                   13716: @item values returned after arithmetic overflow:
                   13717: On two's complement machines, arithmetic is performed modulo
                   13718: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164     anton    13719: arithmetic (with appropriate mapping for signed types). Division by
                   13720: zero typically results in a @code{-55 throw} (Floating-point
                   13721: unidentified fault) or @code{-10 throw} (divide by zero).  Integer
1.166     anton    13722: division overflow can result in these throws, or in @code{-11 throw};
                   13723: in @code{gforth-fast} division overflow and divide by zero may also
                   13724: result in returning bogus results without producing an exception.
1.1       anton    13725: 
                   13726: @item whether the current definition can be found after @t{DOES>}:
                   13727: @cindex @t{DOES>}, visibility of current definition
                   13728: No.
                   13729: 
                   13730: @end table
                   13731: 
                   13732: @c ---------------------------------------------------------------------
                   13733: @node core-ambcond, core-other, core-idef, The Core Words
                   13734: @subsection Ambiguous conditions
                   13735: @c ---------------------------------------------------------------------
                   13736: @cindex core words, ambiguous conditions
                   13737: @cindex ambiguous conditions, core words
                   13738: 
                   13739: @table @i
                   13740: 
                   13741: @item a name is neither a word nor a number:
                   13742: @cindex name not found
1.26      crook    13743: @cindex undefined word
1.80      anton    13744: @code{-13 throw} (Undefined word).
1.1       anton    13745: 
                   13746: @item a definition name exceeds the maximum length allowed:
1.26      crook    13747: @cindex word name too long
1.1       anton    13748: @code{-19 throw} (Word name too long)
                   13749: 
                   13750: @item addressing a region not inside the various data spaces of the forth system:
                   13751: @cindex Invalid memory address
1.32      anton    13752: The stacks, code space and header space are accessible. Machine code space is
1.1       anton    13753: typically readable. Accessing other addresses gives results dependent on
                   13754: the operating system. On decent systems: @code{-9 throw} (Invalid memory
                   13755: address).
                   13756: 
                   13757: @item argument type incompatible with parameter:
1.26      crook    13758: @cindex argument type mismatch
1.1       anton    13759: This is usually not caught. Some words perform checks, e.g., the control
                   13760: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
                   13761: mismatch).
                   13762: 
                   13763: @item attempting to obtain the execution token of a word with undefined execution semantics:
                   13764: @cindex Interpreting a compile-only word, for @code{'} etc.
                   13765: @cindex execution token of words with undefined execution semantics
                   13766: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
                   13767: get an execution token for @code{compile-only-error} (which performs a
                   13768: @code{-14 throw} when executed).
                   13769: 
                   13770: @item dividing by zero:
                   13771: @cindex dividing by zero
                   13772: @cindex floating point unidentified fault, integer division
1.80      anton    13773: On some platforms, this produces a @code{-10 throw} (Division by
1.24      anton    13774: zero); on other systems, this typically results in a @code{-55 throw}
                   13775: (Floating-point unidentified fault).
1.1       anton    13776: 
                   13777: @item insufficient data stack or return stack space:
                   13778: @cindex insufficient data stack or return stack space
                   13779: @cindex stack overflow
1.26      crook    13780: @cindex address alignment exception, stack overflow
1.1       anton    13781: @cindex Invalid memory address, stack overflow
                   13782: Depending on the operating system, the installation, and the invocation
                   13783: of Gforth, this is either checked by the memory management hardware, or
1.24      anton    13784: it is not checked. If it is checked, you typically get a @code{-3 throw}
                   13785: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
                   13786: throw} (Invalid memory address) (depending on the platform and how you
                   13787: achieved the overflow) as soon as the overflow happens. If it is not
                   13788: checked, overflows typically result in mysterious illegal memory
                   13789: accesses, producing @code{-9 throw} (Invalid memory address) or
                   13790: @code{-23 throw} (Address alignment exception); they might also destroy
                   13791: the internal data structure of @code{ALLOCATE} and friends, resulting in
                   13792: various errors in these words.
1.1       anton    13793: 
                   13794: @item insufficient space for loop control parameters:
                   13795: @cindex insufficient space for loop control parameters
1.80      anton    13796: Like other return stack overflows.
1.1       anton    13797: 
                   13798: @item insufficient space in the dictionary:
                   13799: @cindex insufficient space in the dictionary
                   13800: @cindex dictionary overflow
1.12      anton    13801: If you try to allot (either directly with @code{allot}, or indirectly
                   13802: with @code{,}, @code{create} etc.) more memory than available in the
                   13803: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
                   13804: to access memory beyond the end of the dictionary, the results are
                   13805: similar to stack overflows.
1.1       anton    13806: 
                   13807: @item interpreting a word with undefined interpretation semantics:
                   13808: @cindex interpreting a word with undefined interpretation semantics
                   13809: @cindex Interpreting a compile-only word
                   13810: For some words, we have defined interpretation semantics. For the
                   13811: others: @code{-14 throw} (Interpreting a compile-only word).
                   13812: 
                   13813: @item modifying the contents of the input buffer or a string literal:
                   13814: @cindex modifying the contents of the input buffer or a string literal
                   13815: These are located in writable memory and can be modified.
                   13816: 
                   13817: @item overflow of the pictured numeric output string:
                   13818: @cindex overflow of the pictured numeric output string
                   13819: @cindex pictured numeric output string, overflow
1.24      anton    13820: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1       anton    13821: 
                   13822: @item parsed string overflow:
                   13823: @cindex parsed string overflow
                   13824: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
                   13825: 
                   13826: @item producing a result out of range:
                   13827: @cindex result out of range
                   13828: On two's complement machines, arithmetic is performed modulo
                   13829: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166     anton    13830: arithmetic (with appropriate mapping for signed types). Division by
                   13831: zero typically results in a @code{-10 throw} (divide by zero) or
                   13832: @code{-55 throw} (floating point unidentified fault). Overflow on
                   13833: division may result in these errors or in @code{-11 throw} (result out
                   13834: of range).  @code{Gforth-fast} may silently produce bogus results on
                   13835: division overflow or division by zero.  @code{Convert} and
1.24      anton    13836: @code{>number} currently overflow silently.
1.1       anton    13837: 
                   13838: @item reading from an empty data or return stack:
                   13839: @cindex stack empty
                   13840: @cindex stack underflow
1.24      anton    13841: @cindex return stack underflow
1.1       anton    13842: The data stack is checked by the outer (aka text) interpreter after
                   13843: every word executed. If it has underflowed, a @code{-4 throw} (Stack
                   13844: underflow) is performed. Apart from that, stacks may be checked or not,
1.24      anton    13845: depending on operating system, installation, and invocation. If they are
                   13846: caught by a check, they typically result in @code{-4 throw} (Stack
                   13847: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
                   13848: (Invalid memory address), depending on the platform and which stack
                   13849: underflows and by how much. Note that even if the system uses checking
                   13850: (through the MMU), your program may have to underflow by a significant
                   13851: number of stack items to trigger the reaction (the reason for this is
                   13852: that the MMU, and therefore the checking, works with a page-size
                   13853: granularity).  If there is no checking, the symptoms resulting from an
                   13854: underflow are similar to those from an overflow.  Unbalanced return
1.80      anton    13855: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24      anton    13856: (Invalid memory address) and Illegal Instruction (typically @code{-260
                   13857: throw}).
1.1       anton    13858: 
                   13859: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
                   13860: @cindex unexpected end of the input buffer
                   13861: @cindex zero-length string as a name
                   13862: @cindex Attempt to use zero-length string as a name
                   13863: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
                   13864: use zero-length string as a name). Words like @code{'} probably will not
                   13865: find what they search. Note that it is possible to create zero-length
                   13866: names with @code{nextname} (should it not?).
                   13867: 
                   13868: @item @code{>IN} greater than input buffer:
                   13869: @cindex @code{>IN} greater than input buffer
                   13870: The next invocation of a parsing word returns a string with length 0.
                   13871: 
                   13872: @item @code{RECURSE} appears after @code{DOES>}:
                   13873: @cindex @code{RECURSE} appears after @code{DOES>}
                   13874: Compiles a recursive call to the defining word, not to the defined word.
                   13875: 
                   13876: @item argument input source different than current input source for @code{RESTORE-INPUT}:
                   13877: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26      crook    13878: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1       anton    13879: @cindex @code{RESTORE-INPUT}, Argument type mismatch
                   13880: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
                   13881: the end of the file was reached), its source-id may be
                   13882: reused. Therefore, restoring an input source specification referencing a
                   13883: closed file may lead to unpredictable results instead of a @code{-12
                   13884: THROW}.
                   13885: 
                   13886: In the future, Gforth may be able to restore input source specifications
                   13887: from other than the current input source.
                   13888: 
                   13889: @item data space containing definitions gets de-allocated:
                   13890: @cindex data space containing definitions gets de-allocated
                   13891: Deallocation with @code{allot} is not checked. This typically results in
                   13892: memory access faults or execution of illegal instructions.
                   13893: 
                   13894: @item data space read/write with incorrect alignment:
                   13895: @cindex data space read/write with incorrect alignment
                   13896: @cindex alignment faults
1.26      crook    13897: @cindex address alignment exception
1.1       anton    13898: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12      anton    13899: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1       anton    13900: alignment turned on, incorrect alignment results in a @code{-9 throw}
                   13901: (Invalid memory address). There are reportedly some processors with
1.12      anton    13902: alignment restrictions that do not report violations.
1.1       anton    13903: 
                   13904: @item data space pointer not properly aligned, @code{,}, @code{C,}:
                   13905: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
                   13906: Like other alignment errors.
                   13907: 
                   13908: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
                   13909: Like other stack underflows.
                   13910: 
                   13911: @item loop control parameters not available:
                   13912: @cindex loop control parameters not available
                   13913: Not checked. The counted loop words simply assume that the top of return
                   13914: stack items are loop control parameters and behave accordingly.
                   13915: 
                   13916: @item most recent definition does not have a name (@code{IMMEDIATE}):
                   13917: @cindex most recent definition does not have a name (@code{IMMEDIATE})
                   13918: @cindex last word was headerless
                   13919: @code{abort" last word was headerless"}.
                   13920: 
                   13921: @item name not defined by @code{VALUE} used by @code{TO}:
                   13922: @cindex name not defined by @code{VALUE} used by @code{TO}
                   13923: @cindex @code{TO} on non-@code{VALUE}s
                   13924: @cindex Invalid name argument, @code{TO}
                   13925: @code{-32 throw} (Invalid name argument) (unless name is a local or was
                   13926: defined by @code{CONSTANT}; in the latter case it just changes the constant).
                   13927: 
                   13928: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
                   13929: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26      crook    13930: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1       anton    13931: @code{-13 throw} (Undefined word)
                   13932: 
                   13933: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
                   13934: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
                   13935: Gforth behaves as if they were of the same type. I.e., you can predict
                   13936: the behaviour by interpreting all parameters as, e.g., signed.
                   13937: 
                   13938: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
                   13939: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
                   13940: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
                   13941: compilation semantics of @code{TO}.
                   13942: 
                   13943: @item String longer than a counted string returned by @code{WORD}:
1.26      crook    13944: @cindex string longer than a counted string returned by @code{WORD}
1.1       anton    13945: @cindex @code{WORD}, string overflow
                   13946: Not checked. The string will be ok, but the count will, of course,
                   13947: contain only the least significant bits of the length.
                   13948: 
                   13949: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
                   13950: @cindex @code{LSHIFT}, large shift counts
                   13951: @cindex @code{RSHIFT}, large shift counts
                   13952: Processor-dependent. Typical behaviours are returning 0 and using only
                   13953: the low bits of the shift count.
                   13954: 
                   13955: @item word not defined via @code{CREATE}:
                   13956: @cindex @code{>BODY} of non-@code{CREATE}d words
                   13957: @code{>BODY} produces the PFA of the word no matter how it was defined.
                   13958: 
                   13959: @cindex @code{DOES>} of non-@code{CREATE}d words
                   13960: @code{DOES>} changes the execution semantics of the last defined word no
                   13961: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
                   13962: @code{CREATE , DOES>}.
                   13963: 
                   13964: @item words improperly used outside @code{<#} and @code{#>}:
                   13965: Not checked. As usual, you can expect memory faults.
                   13966: 
                   13967: @end table
                   13968: 
                   13969: 
                   13970: @c ---------------------------------------------------------------------
                   13971: @node core-other,  , core-ambcond, The Core Words
                   13972: @subsection Other system documentation
                   13973: @c ---------------------------------------------------------------------
                   13974: @cindex other system documentation, core words
                   13975: @cindex core words, other system documentation
                   13976: 
                   13977: @table @i
                   13978: @item nonstandard words using @code{PAD}:
                   13979: @cindex @code{PAD} use by nonstandard words
                   13980: None.
                   13981: 
                   13982: @item operator's terminal facilities available:
                   13983: @cindex operator's terminal facilities available
1.80      anton    13984: After processing the OS's command line, Gforth goes into interactive mode,
1.1       anton    13985: and you can give commands to Gforth interactively. The actual facilities
                   13986: available depend on how you invoke Gforth.
                   13987: 
                   13988: @item program data space available:
                   13989: @cindex program data space available
                   13990: @cindex data space available
                   13991: @code{UNUSED .} gives the remaining dictionary space. The total
                   13992: dictionary space can be specified with the @code{-m} switch
                   13993: (@pxref{Invoking Gforth}) when Gforth starts up.
                   13994: 
                   13995: @item return stack space available:
                   13996: @cindex return stack space available
                   13997: You can compute the total return stack space in cells with
                   13998: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
                   13999: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
                   14000: 
                   14001: @item stack space available:
                   14002: @cindex stack space available
                   14003: You can compute the total data stack space in cells with
                   14004: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
                   14005: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
                   14006: 
                   14007: @item system dictionary space required, in address units:
                   14008: @cindex system dictionary space required, in address units
                   14009: Type @code{here forthstart - .} after startup. At the time of this
                   14010: writing, this gives 80080 (bytes) on a 32-bit system.
                   14011: @end table
                   14012: 
                   14013: 
                   14014: @c =====================================================================
                   14015: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
                   14016: @section The optional Block word set
                   14017: @c =====================================================================
                   14018: @cindex system documentation, block words
                   14019: @cindex block words, system documentation
                   14020: 
                   14021: @menu
                   14022: * block-idef::                  Implementation Defined Options
                   14023: * block-ambcond::               Ambiguous Conditions               
                   14024: * block-other::                 Other System Documentation                 
                   14025: @end menu
                   14026: 
                   14027: 
                   14028: @c ---------------------------------------------------------------------
                   14029: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
                   14030: @subsection Implementation Defined Options
                   14031: @c ---------------------------------------------------------------------
                   14032: @cindex implementation-defined options, block words
                   14033: @cindex block words, implementation-defined options
                   14034: 
                   14035: @table @i
                   14036: @item the format for display by @code{LIST}:
                   14037: @cindex @code{LIST} display format
                   14038: First the screen number is displayed, then 16 lines of 64 characters,
                   14039: each line preceded by the line number.
                   14040: 
                   14041: @item the length of a line affected by @code{\}:
                   14042: @cindex length of a line affected by @code{\}
                   14043: @cindex @code{\}, line length in blocks
                   14044: 64 characters.
                   14045: @end table
                   14046: 
                   14047: 
                   14048: @c ---------------------------------------------------------------------
                   14049: @node block-ambcond, block-other, block-idef, The optional Block word set
                   14050: @subsection Ambiguous conditions
                   14051: @c ---------------------------------------------------------------------
                   14052: @cindex block words, ambiguous conditions
                   14053: @cindex ambiguous conditions, block words
                   14054: 
                   14055: @table @i
                   14056: @item correct block read was not possible:
                   14057: @cindex block read not possible
                   14058: Typically results in a @code{throw} of some OS-derived value (between
                   14059: -512 and -2048). If the blocks file was just not long enough, blanks are
                   14060: supplied for the missing portion.
                   14061: 
                   14062: @item I/O exception in block transfer:
                   14063: @cindex I/O exception in block transfer
                   14064: @cindex block transfer, I/O exception
                   14065: Typically results in a @code{throw} of some OS-derived value (between
                   14066: -512 and -2048).
                   14067: 
                   14068: @item invalid block number:
                   14069: @cindex invalid block number
                   14070: @cindex block number invalid
                   14071: @code{-35 throw} (Invalid block number)
                   14072: 
                   14073: @item a program directly alters the contents of @code{BLK}:
                   14074: @cindex @code{BLK}, altering @code{BLK}
                   14075: The input stream is switched to that other block, at the same
                   14076: position. If the storing to @code{BLK} happens when interpreting
                   14077: non-block input, the system will get quite confused when the block ends.
                   14078: 
                   14079: @item no current block buffer for @code{UPDATE}:
                   14080: @cindex @code{UPDATE}, no current block buffer
                   14081: @code{UPDATE} has no effect.
                   14082: 
                   14083: @end table
                   14084: 
                   14085: @c ---------------------------------------------------------------------
                   14086: @node block-other,  , block-ambcond, The optional Block word set
                   14087: @subsection Other system documentation
                   14088: @c ---------------------------------------------------------------------
                   14089: @cindex other system documentation, block words
                   14090: @cindex block words, other system documentation
                   14091: 
                   14092: @table @i
                   14093: @item any restrictions a multiprogramming system places on the use of buffer addresses:
                   14094: No restrictions (yet).
                   14095: 
                   14096: @item the number of blocks available for source and data:
                   14097: depends on your disk space.
                   14098: 
                   14099: @end table
                   14100: 
                   14101: 
                   14102: @c =====================================================================
                   14103: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
                   14104: @section The optional Double Number word set
                   14105: @c =====================================================================
                   14106: @cindex system documentation, double words
                   14107: @cindex double words, system documentation
                   14108: 
                   14109: @menu
                   14110: * double-ambcond::              Ambiguous Conditions              
                   14111: @end menu
                   14112: 
                   14113: 
                   14114: @c ---------------------------------------------------------------------
                   14115: @node double-ambcond,  , The optional Double Number word set, The optional Double Number word set
                   14116: @subsection Ambiguous conditions
                   14117: @c ---------------------------------------------------------------------
                   14118: @cindex double words, ambiguous conditions
                   14119: @cindex ambiguous conditions, double words
                   14120: 
                   14121: @table @i
1.29      crook    14122: @item @i{d} outside of range of @i{n} in @code{D>S}:
                   14123: @cindex @code{D>S}, @i{d} out of range of @i{n} 
                   14124: The least significant cell of @i{d} is produced.
1.1       anton    14125: 
                   14126: @end table
                   14127: 
                   14128: 
                   14129: @c =====================================================================
                   14130: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
                   14131: @section The optional Exception word set
                   14132: @c =====================================================================
                   14133: @cindex system documentation, exception words
                   14134: @cindex exception words, system documentation
                   14135: 
                   14136: @menu
                   14137: * exception-idef::              Implementation Defined Options              
                   14138: @end menu
                   14139: 
                   14140: 
                   14141: @c ---------------------------------------------------------------------
                   14142: @node exception-idef,  , The optional Exception word set, The optional Exception word set
                   14143: @subsection Implementation Defined Options
                   14144: @c ---------------------------------------------------------------------
                   14145: @cindex implementation-defined options, exception words
                   14146: @cindex exception words, implementation-defined options
                   14147: 
                   14148: @table @i
                   14149: @item @code{THROW}-codes used in the system:
                   14150: @cindex @code{THROW}-codes used in the system
                   14151: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29      crook    14152: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1       anton    14153: codes -512@minus{}-2047 are used for OS errors (for file and memory
                   14154: allocation operations). The mapping from OS error numbers to throw codes
                   14155: is -512@minus{}@code{errno}. One side effect of this mapping is that
                   14156: undefined OS errors produce a message with a strange number; e.g.,
                   14157: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
                   14158: @end table
                   14159: 
                   14160: @c =====================================================================
                   14161: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
                   14162: @section The optional Facility word set
                   14163: @c =====================================================================
                   14164: @cindex system documentation, facility words
                   14165: @cindex facility words, system documentation
                   14166: 
                   14167: @menu
                   14168: * facility-idef::               Implementation Defined Options               
                   14169: * facility-ambcond::            Ambiguous Conditions            
                   14170: @end menu
                   14171: 
                   14172: 
                   14173: @c ---------------------------------------------------------------------
                   14174: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
                   14175: @subsection Implementation Defined Options
                   14176: @c ---------------------------------------------------------------------
                   14177: @cindex implementation-defined options, facility words
                   14178: @cindex facility words, implementation-defined options
                   14179: 
                   14180: @table @i
                   14181: @item encoding of keyboard events (@code{EKEY}):
                   14182: @cindex keyboard events, encoding in @code{EKEY}
                   14183: @cindex @code{EKEY}, encoding of keyboard events
1.40      anton    14184: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41      anton    14185: Other keys are encoded with the constants @code{k-left}, @code{k-right},
                   14186: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
                   14187: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
                   14188: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40      anton    14189: 
1.1       anton    14190: 
                   14191: @item duration of a system clock tick:
                   14192: @cindex duration of a system clock tick
                   14193: @cindex clock tick duration
                   14194: System dependent. With respect to @code{MS}, the time is specified in
                   14195: microseconds. How well the OS and the hardware implement this, is
                   14196: another question.
                   14197: 
                   14198: @item repeatability to be expected from the execution of @code{MS}:
                   14199: @cindex repeatability to be expected from the execution of @code{MS}
                   14200: @cindex @code{MS}, repeatability to be expected
                   14201: System dependent. On Unix, a lot depends on load. If the system is
                   14202: lightly loaded, and the delay is short enough that Gforth does not get
                   14203: swapped out, the performance should be acceptable. Under MS-DOS and
                   14204: other single-tasking systems, it should be good.
                   14205: 
                   14206: @end table
                   14207: 
                   14208: 
                   14209: @c ---------------------------------------------------------------------
                   14210: @node facility-ambcond,  , facility-idef, The optional Facility word set
                   14211: @subsection Ambiguous conditions
                   14212: @c ---------------------------------------------------------------------
                   14213: @cindex facility words, ambiguous conditions
                   14214: @cindex ambiguous conditions, facility words
                   14215: 
                   14216: @table @i
                   14217: @item @code{AT-XY} can't be performed on user output device:
                   14218: @cindex @code{AT-XY} can't be performed on user output device
                   14219: Largely terminal dependent. No range checks are done on the arguments.
                   14220: No errors are reported. You may see some garbage appearing, you may see
                   14221: simply nothing happen.
                   14222: 
                   14223: @end table
                   14224: 
                   14225: 
                   14226: @c =====================================================================
                   14227: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
                   14228: @section The optional File-Access word set
                   14229: @c =====================================================================
                   14230: @cindex system documentation, file words
                   14231: @cindex file words, system documentation
                   14232: 
                   14233: @menu
                   14234: * file-idef::                   Implementation Defined Options
                   14235: * file-ambcond::                Ambiguous Conditions                
                   14236: @end menu
                   14237: 
                   14238: @c ---------------------------------------------------------------------
                   14239: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
                   14240: @subsection Implementation Defined Options
                   14241: @c ---------------------------------------------------------------------
                   14242: @cindex implementation-defined options, file words
                   14243: @cindex file words, implementation-defined options
                   14244: 
                   14245: @table @i
                   14246: @item file access methods used:
                   14247: @cindex file access methods used
                   14248: @code{R/O}, @code{R/W} and @code{BIN} work as you would
                   14249: expect. @code{W/O} translates into the C file opening mode @code{w} (or
                   14250: @code{wb}): The file is cleared, if it exists, and created, if it does
                   14251: not (with both @code{open-file} and @code{create-file}).  Under Unix
                   14252: @code{create-file} creates a file with 666 permissions modified by your
                   14253: umask.
                   14254: 
                   14255: @item file exceptions:
                   14256: @cindex file exceptions
                   14257: The file words do not raise exceptions (except, perhaps, memory access
                   14258: faults when you pass illegal addresses or file-ids).
                   14259: 
                   14260: @item file line terminator:
                   14261: @cindex file line terminator
                   14262: System-dependent. Gforth uses C's newline character as line
                   14263: terminator. What the actual character code(s) of this are is
                   14264: system-dependent.
                   14265: 
                   14266: @item file name format:
                   14267: @cindex file name format
                   14268: System dependent. Gforth just uses the file name format of your OS.
                   14269: 
                   14270: @item information returned by @code{FILE-STATUS}:
                   14271: @cindex @code{FILE-STATUS}, returned information
                   14272: @code{FILE-STATUS} returns the most powerful file access mode allowed
                   14273: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
                   14274: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
                   14275: along with the returned mode.
                   14276: 
                   14277: @item input file state after an exception when including source:
                   14278: @cindex exception when including source
                   14279: All files that are left via the exception are closed.
                   14280: 
1.29      crook    14281: @item @i{ior} values and meaning:
                   14282: @cindex @i{ior} values and meaning
1.68      anton    14283: @cindex @i{wior} values and meaning
1.29      crook    14284: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    14285: intended as throw codes. They typically are in the range
                   14286: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    14287: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    14288: 
                   14289: @item maximum depth of file input nesting:
                   14290: @cindex maximum depth of file input nesting
                   14291: @cindex file input nesting, maximum depth
                   14292: limited by the amount of return stack, locals/TIB stack, and the number
                   14293: of open files available. This should not give you troubles.
                   14294: 
                   14295: @item maximum size of input line:
                   14296: @cindex maximum size of input line
                   14297: @cindex input line size, maximum
                   14298: @code{/line}. Currently 255.
                   14299: 
                   14300: @item methods of mapping block ranges to files:
                   14301: @cindex mapping block ranges to files
                   14302: @cindex files containing blocks
                   14303: @cindex blocks in files
                   14304: By default, blocks are accessed in the file @file{blocks.fb} in the
                   14305: current working directory. The file can be switched with @code{USE}.
                   14306: 
                   14307: @item number of string buffers provided by @code{S"}:
                   14308: @cindex @code{S"}, number of string buffers
                   14309: 1
                   14310: 
                   14311: @item size of string buffer used by @code{S"}:
                   14312: @cindex @code{S"}, size of string buffer
                   14313: @code{/line}. currently 255.
                   14314: 
                   14315: @end table
                   14316: 
                   14317: @c ---------------------------------------------------------------------
                   14318: @node file-ambcond,  , file-idef, The optional File-Access word set
                   14319: @subsection Ambiguous conditions
                   14320: @c ---------------------------------------------------------------------
                   14321: @cindex file words, ambiguous conditions
                   14322: @cindex ambiguous conditions, file words
                   14323: 
                   14324: @table @i
                   14325: @item attempting to position a file outside its boundaries:
                   14326: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
                   14327: @code{REPOSITION-FILE} is performed as usual: Afterwards,
                   14328: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
                   14329: 
                   14330: @item attempting to read from file positions not yet written:
                   14331: @cindex reading from file positions not yet written
                   14332: End-of-file, i.e., zero characters are read and no error is reported.
                   14333: 
1.29      crook    14334: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
                   14335: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid 
1.1       anton    14336: An appropriate exception may be thrown, but a memory fault or other
                   14337: problem is more probable.
                   14338: 
1.29      crook    14339: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
                   14340: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
                   14341: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
                   14342: The @i{ior} produced by the operation, that discovered the problem, is
1.1       anton    14343: thrown.
                   14344: 
                   14345: @item named file cannot be opened (@code{INCLUDED}):
                   14346: @cindex @code{INCLUDED}, named file cannot be opened
1.29      crook    14347: The @i{ior} produced by @code{open-file} is thrown.
1.1       anton    14348: 
                   14349: @item requesting an unmapped block number:
                   14350: @cindex unmapped block numbers
                   14351: There are no unmapped legal block numbers. On some operating systems,
                   14352: writing a block with a large number may overflow the file system and
                   14353: have an error message as consequence.
                   14354: 
                   14355: @item using @code{source-id} when @code{blk} is non-zero:
                   14356: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
                   14357: @code{source-id} performs its function. Typically it will give the id of
                   14358: the source which loaded the block. (Better ideas?)
                   14359: 
                   14360: @end table
                   14361: 
                   14362: 
                   14363: @c =====================================================================
                   14364: @node  The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
                   14365: @section The optional Floating-Point word set
                   14366: @c =====================================================================
                   14367: @cindex system documentation, floating-point words
                   14368: @cindex floating-point words, system documentation
                   14369: 
                   14370: @menu
                   14371: * floating-idef::               Implementation Defined Options
                   14372: * floating-ambcond::            Ambiguous Conditions            
                   14373: @end menu
                   14374: 
                   14375: 
                   14376: @c ---------------------------------------------------------------------
                   14377: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
                   14378: @subsection Implementation Defined Options
                   14379: @c ---------------------------------------------------------------------
                   14380: @cindex implementation-defined options, floating-point words
                   14381: @cindex floating-point words, implementation-defined options
                   14382: 
                   14383: @table @i
                   14384: @item format and range of floating point numbers:
                   14385: @cindex format and range of floating point numbers
                   14386: @cindex floating point numbers, format and range
                   14387: System-dependent; the @code{double} type of C.
                   14388: 
1.29      crook    14389: @item results of @code{REPRESENT} when @i{float} is out of range:
                   14390: @cindex  @code{REPRESENT}, results when @i{float} is out of range
1.1       anton    14391: System dependent; @code{REPRESENT} is implemented using the C library
                   14392: function @code{ecvt()} and inherits its behaviour in this respect.
                   14393: 
                   14394: @item rounding or truncation of floating-point numbers:
                   14395: @cindex rounding of floating-point numbers
                   14396: @cindex truncation of floating-point numbers
                   14397: @cindex floating-point numbers, rounding or truncation
                   14398: System dependent; the rounding behaviour is inherited from the hosting C
                   14399: compiler. IEEE-FP-based (i.e., most) systems by default round to
                   14400: nearest, and break ties by rounding to even (i.e., such that the last
                   14401: bit of the mantissa is 0).
                   14402: 
                   14403: @item size of floating-point stack:
                   14404: @cindex floating-point stack size
                   14405: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
                   14406: the floating-point stack (in floats). You can specify this on startup
                   14407: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
                   14408: 
                   14409: @item width of floating-point stack:
                   14410: @cindex floating-point stack width 
                   14411: @code{1 floats}.
                   14412: 
                   14413: @end table
                   14414: 
                   14415: 
                   14416: @c ---------------------------------------------------------------------
                   14417: @node floating-ambcond,  , floating-idef, The optional Floating-Point word set
                   14418: @subsection Ambiguous conditions
                   14419: @c ---------------------------------------------------------------------
                   14420: @cindex floating-point words, ambiguous conditions
                   14421: @cindex ambiguous conditions, floating-point words
                   14422: 
                   14423: @table @i
                   14424: @item @code{df@@} or @code{df!} used with an address that is not double-float  aligned:
                   14425: @cindex @code{df@@} or @code{df!} used with an address that is not double-float  aligned
                   14426: System-dependent. Typically results in a @code{-23 THROW} like other
                   14427: alignment violations.
                   14428: 
                   14429: @item @code{f@@} or @code{f!} used with an address that is not float  aligned:
                   14430: @cindex @code{f@@} used with an address that is not float aligned
                   14431: @cindex @code{f!} used with an address that is not float aligned
                   14432: System-dependent. Typically results in a @code{-23 THROW} like other
                   14433: alignment violations.
                   14434: 
                   14435: @item floating-point result out of range:
                   14436: @cindex floating-point result out of range
1.80      anton    14437: System-dependent. Can result in a @code{-43 throw} (floating point
                   14438: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
                   14439: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1       anton    14440: unidentified fault), or can produce a special value representing, e.g.,
                   14441: Infinity.
                   14442: 
                   14443: @item @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned:
                   14444: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float  aligned
                   14445: System-dependent. Typically results in an alignment fault like other
                   14446: alignment violations.
                   14447: 
1.35      anton    14448: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
                   14449: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1       anton    14450: The floating-point number is converted into decimal nonetheless.
                   14451: 
                   14452: @item Both arguments are equal to zero (@code{FATAN2}):
                   14453: @cindex @code{FATAN2}, both arguments are equal to zero
                   14454: System-dependent. @code{FATAN2} is implemented using the C library
                   14455: function @code{atan2()}.
                   14456: 
1.29      crook    14457: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
                   14458: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
                   14459: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1       anton    14460: because of small errors and the tan will be a very large (or very small)
                   14461: but finite number.
                   14462: 
1.29      crook    14463: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
                   14464: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1       anton    14465: The result is rounded to the nearest float.
                   14466: 
                   14467: @item dividing by zero:
                   14468: @cindex dividing by zero, floating-point
                   14469: @cindex floating-point dividing by zero
                   14470: @cindex floating-point unidentified fault, FP divide-by-zero
1.80      anton    14471: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
                   14472: (floating point divide by zero) or @code{-55 throw} (Floating-point
                   14473: unidentified fault).
1.1       anton    14474: 
                   14475: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
                   14476: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
                   14477: System dependent. On IEEE-FP based systems the number is converted into
                   14478: an infinity.
                   14479: 
1.29      crook    14480: @item @i{float}<1 (@code{FACOSH}):
                   14481: @cindex @code{FACOSH}, @i{float}<1
1.1       anton    14482: @cindex floating-point unidentified fault, @code{FACOSH}
1.80      anton    14483: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1       anton    14484: 
1.29      crook    14485: @item @i{float}=<-1 (@code{FLNP1}):
                   14486: @cindex @code{FLNP1}, @i{float}=<-1
1.1       anton    14487: @cindex floating-point unidentified fault, @code{FLNP1}
1.80      anton    14488: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   14489: negative infinity for @i{float}=-1).
1.1       anton    14490: 
1.29      crook    14491: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
                   14492: @cindex @code{FLN}, @i{float}=<0
                   14493: @cindex @code{FLOG}, @i{float}=<0
1.1       anton    14494: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80      anton    14495: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
                   14496: negative infinity for @i{float}=0).
1.1       anton    14497: 
1.29      crook    14498: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
                   14499: @cindex @code{FASINH}, @i{float}<0
                   14500: @cindex @code{FSQRT}, @i{float}<0
1.1       anton    14501: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80      anton    14502: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
                   14503: @code{fasinh} some platforms produce a NaN, others a number (bug in the
                   14504: C library?).
1.1       anton    14505: 
1.29      crook    14506: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
                   14507: @cindex @code{FACOS}, |@i{float}|>1
                   14508: @cindex @code{FASIN}, |@i{float}|>1
                   14509: @cindex @code{FATANH}, |@i{float}|>1
1.1       anton    14510: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80      anton    14511: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1       anton    14512: 
1.29      crook    14513: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
                   14514: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1       anton    14515: @cindex floating-point unidentified fault, @code{F>D}
1.80      anton    14516: Platform-dependent; typically, some double number is produced and no
                   14517: error is reported.
1.1       anton    14518: 
                   14519: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
                   14520: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80      anton    14521: @code{Precision} characters of the numeric output area are used.  If
                   14522: @code{precision} is too high, these words will smash the data or code
                   14523: close to @code{here}.
1.1       anton    14524: @end table
                   14525: 
                   14526: @c =====================================================================
                   14527: @node  The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
                   14528: @section The optional Locals word set
                   14529: @c =====================================================================
                   14530: @cindex system documentation, locals words
                   14531: @cindex locals words, system documentation
                   14532: 
                   14533: @menu
                   14534: * locals-idef::                 Implementation Defined Options                 
                   14535: * locals-ambcond::              Ambiguous Conditions              
                   14536: @end menu
                   14537: 
                   14538: 
                   14539: @c ---------------------------------------------------------------------
                   14540: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
                   14541: @subsection Implementation Defined Options
                   14542: @c ---------------------------------------------------------------------
                   14543: @cindex implementation-defined options, locals words
                   14544: @cindex locals words, implementation-defined options
                   14545: 
                   14546: @table @i
                   14547: @item maximum number of locals in a definition:
                   14548: @cindex maximum number of locals in a definition
                   14549: @cindex locals, maximum number in a definition
                   14550: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
                   14551: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
                   14552: characters. The number of locals in a definition is bounded by the size
                   14553: of locals-buffer, which contains the names of the locals.
                   14554: 
                   14555: @end table
                   14556: 
                   14557: 
                   14558: @c ---------------------------------------------------------------------
                   14559: @node locals-ambcond,  , locals-idef, The optional Locals word set
                   14560: @subsection Ambiguous conditions
                   14561: @c ---------------------------------------------------------------------
                   14562: @cindex locals words, ambiguous conditions
                   14563: @cindex ambiguous conditions, locals words
                   14564: 
                   14565: @table @i
                   14566: @item executing a named local in interpretation state:
                   14567: @cindex local in interpretation state
                   14568: @cindex Interpreting a compile-only word, for a local
                   14569: Locals have no interpretation semantics. If you try to perform the
                   14570: interpretation semantics, you will get a @code{-14 throw} somewhere
                   14571: (Interpreting a compile-only word). If you perform the compilation
                   14572: semantics, the locals access will be compiled (irrespective of state).
                   14573: 
1.29      crook    14574: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1       anton    14575: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
                   14576: @cindex @code{TO} on non-@code{VALUE}s and non-locals
                   14577: @cindex Invalid name argument, @code{TO}
                   14578: @code{-32 throw} (Invalid name argument)
                   14579: 
                   14580: @end table
                   14581: 
                   14582: 
                   14583: @c =====================================================================
                   14584: @node  The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
                   14585: @section The optional Memory-Allocation word set
                   14586: @c =====================================================================
                   14587: @cindex system documentation, memory-allocation words
                   14588: @cindex memory-allocation words, system documentation
                   14589: 
                   14590: @menu
                   14591: * memory-idef::                 Implementation Defined Options                 
                   14592: @end menu
                   14593: 
                   14594: 
                   14595: @c ---------------------------------------------------------------------
                   14596: @node memory-idef,  , The optional Memory-Allocation word set, The optional Memory-Allocation word set
                   14597: @subsection Implementation Defined Options
                   14598: @c ---------------------------------------------------------------------
                   14599: @cindex implementation-defined options, memory-allocation words
                   14600: @cindex memory-allocation words, implementation-defined options
                   14601: 
                   14602: @table @i
1.29      crook    14603: @item values and meaning of @i{ior}:
                   14604: @cindex  @i{ior} values and meaning
                   14605: The @i{ior}s returned by the file and memory allocation words are
1.1       anton    14606: intended as throw codes. They typically are in the range
                   14607: -512@minus{}-2047 of OS errors.  The mapping from OS error numbers to
1.29      crook    14608: @i{ior}s is -512@minus{}@i{errno}.
1.1       anton    14609: 
                   14610: @end table
                   14611: 
                   14612: @c =====================================================================
                   14613: @node  The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
                   14614: @section The optional Programming-Tools word set
                   14615: @c =====================================================================
                   14616: @cindex system documentation, programming-tools words
                   14617: @cindex programming-tools words, system documentation
                   14618: 
                   14619: @menu
                   14620: * programming-idef::            Implementation Defined Options            
                   14621: * programming-ambcond::         Ambiguous Conditions         
                   14622: @end menu
                   14623: 
                   14624: 
                   14625: @c ---------------------------------------------------------------------
                   14626: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
                   14627: @subsection Implementation Defined Options
                   14628: @c ---------------------------------------------------------------------
                   14629: @cindex implementation-defined options, programming-tools words
                   14630: @cindex programming-tools words, implementation-defined options
                   14631: 
                   14632: @table @i
                   14633: @item ending sequence for input following @code{;CODE} and @code{CODE}:
                   14634: @cindex @code{;CODE} ending sequence
                   14635: @cindex @code{CODE} ending sequence
                   14636: @code{END-CODE}
                   14637: 
                   14638: @item manner of processing input following @code{;CODE} and @code{CODE}:
                   14639: @cindex @code{;CODE}, processing input
                   14640: @cindex @code{CODE}, processing input
                   14641: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
                   14642: the input is processed by the text interpreter, (starting) in interpret
                   14643: state.
                   14644: 
                   14645: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
                   14646: @cindex @code{ASSEMBLER}, search order capability
                   14647: The ANS Forth search order word set.
                   14648: 
                   14649: @item source and format of display by @code{SEE}:
                   14650: @cindex @code{SEE}, source and format of output
1.80      anton    14651: The source for @code{see} is the executable code used by the inner
1.1       anton    14652: interpreter.  The current @code{see} tries to output Forth source code
1.80      anton    14653: (and on some platforms, assembly code for primitives) as well as
                   14654: possible.
1.1       anton    14655: 
                   14656: @end table
                   14657: 
                   14658: @c ---------------------------------------------------------------------
                   14659: @node programming-ambcond,  , programming-idef, The optional Programming-Tools word set
                   14660: @subsection Ambiguous conditions
                   14661: @c ---------------------------------------------------------------------
                   14662: @cindex programming-tools words, ambiguous conditions
                   14663: @cindex ambiguous conditions, programming-tools words
                   14664: 
                   14665: @table @i
                   14666: 
1.21      crook    14667: @item deleting the compilation word list (@code{FORGET}):
                   14668: @cindex @code{FORGET}, deleting the compilation word list
1.1       anton    14669: Not implemented (yet).
                   14670: 
1.29      crook    14671: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
                   14672: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
                   14673: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1       anton    14674: @cindex control-flow stack underflow
                   14675: This typically results in an @code{abort"} with a descriptive error
                   14676: message (may change into a @code{-22 throw} (Control structure mismatch)
                   14677: in the future). You may also get a memory access error. If you are
                   14678: unlucky, this ambiguous condition is not caught.
                   14679: 
1.29      crook    14680: @item @i{name} can't be found (@code{FORGET}):
                   14681: @cindex @code{FORGET}, @i{name} can't be found
1.1       anton    14682: Not implemented (yet).
                   14683: 
1.29      crook    14684: @item @i{name} not defined via @code{CREATE}:
                   14685: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1       anton    14686: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
                   14687: the execution semantics of the last defined word no matter how it was
                   14688: defined.
                   14689: 
                   14690: @item @code{POSTPONE} applied to @code{[IF]}:
                   14691: @cindex @code{POSTPONE} applied to @code{[IF]}
                   14692: @cindex @code{[IF]} and @code{POSTPONE}
                   14693: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
                   14694: equivalent to @code{[IF]}.
                   14695: 
                   14696: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
                   14697: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
                   14698: Continue in the same state of conditional compilation in the next outer
                   14699: input source. Currently there is no warning to the user about this.
                   14700: 
                   14701: @item removing a needed definition (@code{FORGET}):
                   14702: @cindex @code{FORGET}, removing a needed definition
                   14703: Not implemented (yet).
                   14704: 
                   14705: @end table
                   14706: 
                   14707: 
                   14708: @c =====================================================================
                   14709: @node  The optional Search-Order word set,  , The optional Programming-Tools word set, ANS conformance
                   14710: @section The optional Search-Order word set
                   14711: @c =====================================================================
                   14712: @cindex system documentation, search-order words
                   14713: @cindex search-order words, system documentation
                   14714: 
                   14715: @menu
                   14716: * search-idef::                 Implementation Defined Options                 
                   14717: * search-ambcond::              Ambiguous Conditions              
                   14718: @end menu
                   14719: 
                   14720: 
                   14721: @c ---------------------------------------------------------------------
                   14722: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
                   14723: @subsection Implementation Defined Options
                   14724: @c ---------------------------------------------------------------------
                   14725: @cindex implementation-defined options, search-order words
                   14726: @cindex search-order words, implementation-defined options
                   14727: 
                   14728: @table @i
                   14729: @item maximum number of word lists in search order:
                   14730: @cindex maximum number of word lists in search order
                   14731: @cindex search order, maximum depth
                   14732: @code{s" wordlists" environment? drop .}. Currently 16.
                   14733: 
                   14734: @item minimum search order:
                   14735: @cindex minimum search order
                   14736: @cindex search order, minimum
                   14737: @code{root root}.
                   14738: 
                   14739: @end table
                   14740: 
                   14741: @c ---------------------------------------------------------------------
                   14742: @node search-ambcond,  , search-idef, The optional Search-Order word set
                   14743: @subsection Ambiguous conditions
                   14744: @c ---------------------------------------------------------------------
                   14745: @cindex search-order words, ambiguous conditions
                   14746: @cindex ambiguous conditions, search-order words
                   14747: 
                   14748: @table @i
1.21      crook    14749: @item changing the compilation word list (during compilation):
                   14750: @cindex changing the compilation word list (during compilation)
                   14751: @cindex compilation word list, change before definition ends
                   14752: The word is entered into the word list that was the compilation word list
1.1       anton    14753: at the start of the definition. Any changes to the name field (e.g.,
                   14754: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116     anton    14755: are applied to the latest defined word (as reported by @code{latest} or
                   14756: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1       anton    14757: 
                   14758: @item search order empty (@code{previous}):
                   14759: @cindex @code{previous}, search order empty
1.26      crook    14760: @cindex vocstack empty, @code{previous}
1.1       anton    14761: @code{abort" Vocstack empty"}.
                   14762: 
                   14763: @item too many word lists in search order (@code{also}):
                   14764: @cindex @code{also}, too many word lists in search order
1.26      crook    14765: @cindex vocstack full, @code{also}
1.1       anton    14766: @code{abort" Vocstack full"}.
                   14767: 
                   14768: @end table
                   14769: 
                   14770: @c ***************************************************************
1.65      anton    14771: @node Standard vs Extensions, Model, ANS conformance, Top
                   14772: @chapter Should I use Gforth extensions?
                   14773: @cindex Gforth extensions
                   14774: 
                   14775: As you read through the rest of this manual, you will see documentation
                   14776: for @i{Standard} words, and documentation for some appealing Gforth
                   14777: @i{extensions}. You might ask yourself the question: @i{``Should I
                   14778: restrict myself to the standard, or should I use the extensions?''}
                   14779: 
                   14780: The answer depends on the goals you have for the program you are working
                   14781: on:
                   14782: 
                   14783: @itemize @bullet
                   14784: 
                   14785: @item Is it just for yourself or do you want to share it with others?
                   14786: 
                   14787: @item
                   14788: If you want to share it, do the others all use Gforth?
                   14789: 
                   14790: @item
                   14791: If it is just for yourself, do you want to restrict yourself to Gforth?
                   14792: 
                   14793: @end itemize
                   14794: 
                   14795: If restricting the program to Gforth is ok, then there is no reason not
                   14796: to use extensions.  It is still a good idea to keep to the standard
                   14797: where it is easy, in case you want to reuse these parts in another
                   14798: program that you want to be portable.
                   14799: 
                   14800: If you want to be able to port the program to other Forth systems, there
                   14801: are the following points to consider:
                   14802: 
                   14803: @itemize @bullet
                   14804: 
                   14805: @item
                   14806: Most Forth systems that are being maintained support the ANS Forth
                   14807: standard.  So if your program complies with the standard, it will be
                   14808: portable among many systems.
                   14809: 
                   14810: @item
                   14811: A number of the Gforth extensions can be implemented in ANS Forth using
                   14812: public-domain files provided in the @file{compat/} directory. These are
                   14813: mentioned in the text in passing.  There is no reason not to use these
                   14814: extensions, your program will still be ANS Forth compliant; just include
                   14815: the appropriate compat files with your program.
                   14816: 
                   14817: @item
                   14818: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
                   14819: analyse your program and determine what non-Standard words it relies
                   14820: upon.  However, it does not check whether you use standard words in a
                   14821: non-standard way.
                   14822: 
                   14823: @item
                   14824: Some techniques are not standardized by ANS Forth, and are hard or
                   14825: impossible to implement in a standard way, but can be implemented in
                   14826: most Forth systems easily, and usually in similar ways (e.g., accessing
                   14827: word headers).  Forth has a rich historical precedent for programmers
                   14828: taking advantage of implementation-dependent features of their tools
                   14829: (for example, relying on a knowledge of the dictionary
                   14830: structure). Sometimes these techniques are necessary to extract every
                   14831: last bit of performance from the hardware, sometimes they are just a
                   14832: programming shorthand.
                   14833: 
                   14834: @item
                   14835: Does using a Gforth extension save more work than the porting this part
                   14836: to other Forth systems (if any) will cost?
                   14837: 
                   14838: @item
                   14839: Is the additional functionality worth the reduction in portability and
                   14840: the additional porting problems?
                   14841: 
                   14842: @end itemize
                   14843: 
                   14844: In order to perform these consideratios, you need to know what's
                   14845: standard and what's not.  This manual generally states if something is
1.81      anton    14846: non-standard, but the authoritative source is the
                   14847: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65      anton    14848: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
                   14849: into the thought processes of the technical committee.
                   14850: 
                   14851: Note also that portability between Forth systems is not the only
                   14852: portability issue; there is also the issue of portability between
                   14853: different platforms (processor/OS combinations).
                   14854: 
                   14855: @c ***************************************************************
                   14856: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1       anton    14857: @chapter Model
                   14858: 
                   14859: This chapter has yet to be written. It will contain information, on
                   14860: which internal structures you can rely.
                   14861: 
                   14862: @c ***************************************************************
                   14863: @node Integrating Gforth, Emacs and Gforth, Model, Top
                   14864: @chapter Integrating Gforth into C programs
                   14865: 
                   14866: This is not yet implemented.
                   14867: 
                   14868: Several people like to use Forth as scripting language for applications
                   14869: that are otherwise written in C, C++, or some other language.
                   14870: 
                   14871: The Forth system ATLAST provides facilities for embedding it into
                   14872: applications; unfortunately it has several disadvantages: most
                   14873: importantly, it is not based on ANS Forth, and it is apparently dead
                   14874: (i.e., not developed further and not supported). The facilities
1.21      crook    14875: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1       anton    14876: making the switch should not be hard.
                   14877: 
                   14878: We also tried to design the interface such that it can easily be
                   14879: implemented by other Forth systems, so that we may one day arrive at a
                   14880: standardized interface. Such a standard interface would allow you to
                   14881: replace the Forth system without having to rewrite C code.
                   14882: 
                   14883: You embed the Gforth interpreter by linking with the library
                   14884: @code{libgforth.a} (give the compiler the option @code{-lgforth}).  All
                   14885: global symbols in this library that belong to the interface, have the
                   14886: prefix @code{forth_}. (Global symbols that are used internally have the
                   14887: prefix @code{gforth_}).
                   14888: 
                   14889: You can include the declarations of Forth types and the functions and
                   14890: variables of the interface with @code{#include <forth.h>}.
                   14891: 
                   14892: Types.
                   14893: 
                   14894: Variables.
                   14895: 
                   14896: Data and FP Stack pointer. Area sizes.
                   14897: 
                   14898: functions.
                   14899: 
                   14900: forth_init(imagefile)
                   14901: forth_evaluate(string) exceptions?
                   14902: forth_goto(address) (or forth_execute(xt)?)
                   14903: forth_continue() (a corountining mechanism)
                   14904: 
                   14905: Adding primitives.
                   14906: 
                   14907: No checking.
                   14908: 
                   14909: Signals?
                   14910: 
                   14911: Accessing the Stacks
                   14912: 
1.26      crook    14913: @c ******************************************************************
1.1       anton    14914: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
                   14915: @chapter Emacs and Gforth
                   14916: @cindex Emacs and Gforth
                   14917: 
                   14918: @cindex @file{gforth.el}
                   14919: @cindex @file{forth.el}
                   14920: @cindex Rydqvist, Goran
1.107     dvdkhlng 14921: @cindex Kuehling, David
1.1       anton    14922: @cindex comment editing commands
                   14923: @cindex @code{\}, editing with Emacs
                   14924: @cindex debug tracer editing commands
                   14925: @cindex @code{~~}, removal with Emacs
                   14926: @cindex Forth mode in Emacs
1.107     dvdkhlng 14927: 
1.1       anton    14928: Gforth comes with @file{gforth.el}, an improved version of
                   14929: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26      crook    14930: improvements are:
                   14931: 
                   14932: @itemize @bullet
                   14933: @item
1.107     dvdkhlng 14934: A better handling of indentation.
                   14935: @item
                   14936: A custom hilighting engine for Forth-code.
1.26      crook    14937: @item
                   14938: Comment paragraph filling (@kbd{M-q})
                   14939: @item
                   14940: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
                   14941: @item
                   14942: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41      anton    14943: @item
                   14944: Support of the @code{info-lookup} feature for looking up the
                   14945: documentation of a word.
1.107     dvdkhlng 14946: @item
                   14947: Support for reading and writing blocks files.
1.26      crook    14948: @end itemize
                   14949: 
1.107     dvdkhlng 14950: To get a basic description of these features, enter Forth mode and
                   14951: type @kbd{C-h m}.
1.1       anton    14952: 
                   14953: @cindex source location of error or debugging output in Emacs
                   14954: @cindex error output, finding the source location in Emacs
                   14955: @cindex debugging output, finding the source location in Emacs
                   14956: In addition, Gforth supports Emacs quite well: The source code locations
                   14957: given in error messages, debugging output (from @code{~~}) and failed
                   14958: assertion messages are in the right format for Emacs' compilation mode
                   14959: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
                   14960: Manual}) so the source location corresponding to an error or other
                   14961: message is only a few keystrokes away (@kbd{C-x `} for the next error,
                   14962: @kbd{C-c C-c} for the error under the cursor).
                   14963: 
1.107     dvdkhlng 14964: @cindex viewing the documentation of a word in Emacs
                   14965: @cindex context-sensitive help
                   14966: Moreover, for words documented in this manual, you can look up the
                   14967: glossary entry quickly by using @kbd{C-h TAB}
                   14968: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
                   14969: Commands, emacs, Emacs Manual}).  This feature requires Emacs 20.3 or
                   14970: later and does not work for words containing @code{:}.
                   14971: 
                   14972: @menu
                   14973: * Installing gforth.el::        Making Emacs aware of Forth.
                   14974: * Emacs Tags::                  Viewing the source of a word in Emacs.
                   14975: * Hilighting::                  Making Forth code look prettier.
                   14976: * Auto-Indentation::            Customizing auto-indentation.
                   14977: * Blocks Files::                Reading and writing blocks files.
                   14978: @end menu
                   14979: 
                   14980: @c ----------------------------------
1.109     anton    14981: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107     dvdkhlng 14982: @section Installing gforth.el
                   14983: @cindex @file{.emacs}
                   14984: @cindex @file{gforth.el}, installation
                   14985: To make the features from @file{gforth.el} available in Emacs, add
                   14986: the following lines to your @file{.emacs} file:
                   14987: 
                   14988: @example
                   14989: (autoload 'forth-mode "gforth.el")
                   14990: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode) 
                   14991:                            auto-mode-alist))
                   14992: (autoload 'forth-block-mode "gforth.el")
                   14993: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode) 
                   14994:                            auto-mode-alist))
                   14995: (add-hook 'forth-mode-hook (function (lambda ()
                   14996:    ;; customize variables here:
                   14997:    (setq forth-indent-level 4)
                   14998:    (setq forth-minor-indent-level 2)
                   14999:    (setq forth-hilight-level 3)
                   15000:    ;;; ...
                   15001: )))
                   15002: @end example
                   15003: 
                   15004: @c ----------------------------------
                   15005: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
                   15006: @section Emacs Tags
1.1       anton    15007: @cindex @file{TAGS} file
                   15008: @cindex @file{etags.fs}
                   15009: @cindex viewing the source of a word in Emacs
1.43      anton    15010: @cindex @code{require}, placement in files
                   15011: @cindex @code{include}, placement in files
1.107     dvdkhlng 15012: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
                   15013: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1       anton    15014: contains the definitions of all words defined afterwards. You can then
1.107     dvdkhlng 15015: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1       anton    15016: several tags files at the same time (e.g., one for the Gforth sources
                   15017: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
                   15018: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
                   15019: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43      anton    15020: @file{/usr/local/share/gforth/0.2.0/TAGS}).  To get the best behaviour
                   15021: with @file{etags.fs}, you should avoid putting definitions both before
                   15022: and after @code{require} etc., otherwise you will see the same file
                   15023: visited several times by commands like @code{tags-search}.
1.1       anton    15024: 
1.107     dvdkhlng 15025: @c ----------------------------------
                   15026: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
                   15027: @section Hilighting
                   15028: @cindex hilighting Forth code in Emacs
                   15029: @cindex highlighting Forth code in Emacs
                   15030: @file{gforth.el} comes with a custom source hilighting engine.  When
                   15031: you open a file in @code{forth-mode}, it will be completely parsed,
                   15032: assigning faces to keywords, comments, strings etc.  While you edit
                   15033: the file, modified regions get parsed and updated on-the-fly. 
                   15034: 
                   15035: Use the variable `forth-hilight-level' to change the level of
                   15036: decoration from 0 (no hilighting at all) to 3 (the default).  Even if
                   15037: you set the hilighting level to 0, the parser will still work in the
                   15038: background, collecting information about whether regions of text are
                   15039: ``compiled'' or ``interpreted''.  Those information are required for
                   15040: auto-indentation to work properly.  Set `forth-disable-parser' to
                   15041: non-nil if your computer is too slow to handle parsing.  This will
                   15042: have an impact on the smartness of the auto-indentation engine,
                   15043: though.
                   15044: 
                   15045: Sometimes Forth sources define new features that should be hilighted,
                   15046: new control structures, defining-words etc.  You can use the variable
                   15047: `forth-custom-words' to make @code{forth-mode} hilight additional
                   15048: words and constructs.  See the docstring of `forth-words' for details
                   15049: (in Emacs, type @kbd{C-h v forth-words}).
                   15050: 
                   15051: `forth-custom-words' is meant to be customized in your
                   15052: @file{.emacs} file.  To customize hilighing in a file-specific manner,
                   15053: set `forth-local-words' in a local-variables section at the end of
                   15054: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
                   15055: 
                   15056: Example:
                   15057: @example
                   15058: 0 [IF]
                   15059:    Local Variables:
                   15060:    forth-local-words:
                   15061:       ((("t:") definition-starter (font-lock-keyword-face . 1)
                   15062:         "[ \t\n]" t name (font-lock-function-name-face . 3))
                   15063:        ((";t") definition-ender (font-lock-keyword-face . 1)))
                   15064:    End:
                   15065: [THEN]
                   15066: @end example
                   15067: 
                   15068: @c ----------------------------------
                   15069: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
                   15070: @section Auto-Indentation
                   15071: @cindex auto-indentation of Forth code in Emacs
                   15072: @cindex indentation of Forth code in Emacs
                   15073: @code{forth-mode} automatically tries to indent lines in a smart way,
                   15074: whenever you type @key{TAB} or break a line with @kbd{C-m}.
                   15075: 
                   15076: Simple customization can be achieved by setting
                   15077: `forth-indent-level' and `forth-minor-indent-level' in your
                   15078: @file{.emacs} file. For historical reasons @file{gforth.el} indents
                   15079: per default by multiples of 4 columns.  To use the more traditional
                   15080: 3-column indentation, add the following lines to your @file{.emacs}:
                   15081: 
                   15082: @example
                   15083: (add-hook 'forth-mode-hook (function (lambda ()
                   15084:    ;; customize variables here:
                   15085:    (setq forth-indent-level 3)
                   15086:    (setq forth-minor-indent-level 1)
                   15087: )))
                   15088: @end example
                   15089: 
                   15090: If you want indentation to recognize non-default words, customize it
                   15091: by setting `forth-custom-indent-words' in your @file{.emacs}.  See the
                   15092: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
                   15093: v forth-indent-words}).
                   15094: 
                   15095: To customize indentation in a file-specific manner, set
                   15096: `forth-local-indent-words' in a local-variables section at the end of
                   15097: your source file (@pxref{Local Variables in Files, Variables,,emacs,
                   15098: Emacs Manual}).
                   15099: 
                   15100: Example:
                   15101: @example
                   15102: 0 [IF]
                   15103:    Local Variables:
                   15104:    forth-local-indent-words:
                   15105:       ((("t:") (0 . 2) (0 . 2))
                   15106:        ((";t") (-2 . 0) (0 . -2)))
                   15107:    End:
                   15108: [THEN]
                   15109: @end example
                   15110: 
                   15111: @c ----------------------------------
1.109     anton    15112: @node Blocks Files,  , Auto-Indentation, Emacs and Gforth
1.107     dvdkhlng 15113: @section Blocks Files
                   15114: @cindex blocks files, use with Emacs
                   15115: @code{forth-mode} Autodetects blocks files by checking whether the
                   15116: length of the first line exceeds 1023 characters.  It then tries to
                   15117: convert the file into normal text format.  When you save the file, it
                   15118: will be written to disk as normal stream-source file.
                   15119: 
                   15120: If you want to write blocks files, use @code{forth-blocks-mode}.  It
                   15121: inherits all the features from @code{forth-mode}, plus some additions:
1.41      anton    15122: 
1.107     dvdkhlng 15123: @itemize @bullet
                   15124: @item
                   15125: Files are written to disk in blocks file format.
                   15126: @item
                   15127: Screen numbers are displayed in the mode line (enumerated beginning
                   15128: with the value of `forth-block-base')
                   15129: @item
                   15130: Warnings are displayed when lines exceed 64 characters.
                   15131: @item
                   15132: The beginning of the currently edited block is marked with an
                   15133: overlay-arrow. 
                   15134: @end itemize
1.41      anton    15135: 
1.107     dvdkhlng 15136: There are some restrictions you should be aware of.  When you open a
                   15137: blocks file that contains tabulator or newline characters, these
                   15138: characters will be translated into spaces when the file is written
                   15139: back to disk.  If tabs or newlines are encountered during blocks file
                   15140: reading, an error is output to the echo area. So have a look at the
                   15141: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1       anton    15142: 
1.107     dvdkhlng 15143: Please consult the docstring of @code{forth-blocks-mode} for more
                   15144: information by typing @kbd{C-h v forth-blocks-mode}).
1.1       anton    15145: 
1.26      crook    15146: @c ******************************************************************
1.1       anton    15147: @node Image Files, Engine, Emacs and Gforth, Top
                   15148: @chapter Image Files
1.26      crook    15149: @cindex image file
                   15150: @cindex @file{.fi} files
1.1       anton    15151: @cindex precompiled Forth code
                   15152: @cindex dictionary in persistent form
                   15153: @cindex persistent form of dictionary
                   15154: 
                   15155: An image file is a file containing an image of the Forth dictionary,
                   15156: i.e., compiled Forth code and data residing in the dictionary.  By
                   15157: convention, we use the extension @code{.fi} for image files.
                   15158: 
                   15159: @menu
1.18      anton    15160: * Image Licensing Issues::      Distribution terms for images.
                   15161: * Image File Background::       Why have image files?
1.67      anton    15162: * Non-Relocatable Image Files::  don't always work.
1.18      anton    15163: * Data-Relocatable Image Files::  are better.
1.67      anton    15164: * Fully Relocatable Image Files::  better yet.
1.18      anton    15165: * Stack and Dictionary Sizes::  Setting the default sizes for an image.
1.29      crook    15166: * Running Image Files::         @code{gforth -i @i{file}} or @i{file}.
1.18      anton    15167: * Modifying the Startup Sequence::  and turnkey applications.
1.1       anton    15168: @end menu
                   15169: 
1.18      anton    15170: @node Image Licensing Issues, Image File Background, Image Files, Image Files
                   15171: @section Image Licensing Issues
                   15172: @cindex license for images
                   15173: @cindex image license
                   15174: 
                   15175: An image created with @code{gforthmi} (@pxref{gforthmi}) or
                   15176: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
                   15177: original image; i.e., according to copyright law it is a derived work of
                   15178: the original image.
                   15179: 
                   15180: Since Gforth is distributed under the GNU GPL, the newly created image
                   15181: falls under the GNU GPL, too. In particular, this means that if you
                   15182: distribute the image, you have to make all of the sources for the image
1.113     anton    15183: available, including those you wrote.  For details see @ref{Copying, ,
1.18      anton    15184: GNU General Public License (Section 3)}.
                   15185: 
                   15186: If you create an image with @code{cross} (@pxref{cross.fs}), the image
                   15187: contains only code compiled from the sources you gave it; if none of
                   15188: these sources is under the GPL, the terms discussed above do not apply
                   15189: to the image. However, if your image needs an engine (a gforth binary)
                   15190: that is under the GPL, you should make sure that you distribute both in
                   15191: a way that is at most a @emph{mere aggregation}, if you don't want the
                   15192: terms of the GPL to apply to the image.
                   15193: 
                   15194: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1       anton    15195: @section Image File Background
                   15196: @cindex image file background
                   15197: 
1.80      anton    15198: Gforth consists not only of primitives (in the engine), but also of
1.1       anton    15199: definitions written in Forth. Since the Forth compiler itself belongs to
                   15200: those definitions, it is not possible to start the system with the
1.80      anton    15201: engine and the Forth source alone. Therefore we provide the Forth
1.26      crook    15202: code as an image file in nearly executable form. When Gforth starts up,
                   15203: a C routine loads the image file into memory, optionally relocates the
                   15204: addresses, then sets up the memory (stacks etc.) according to
                   15205: information in the image file, and (finally) starts executing Forth
                   15206: code.
1.1       anton    15207: 
1.204     anton    15208: The default image file is @file{gforth.fi} (in the @code{GFORTHPATH}).
                   15209: You can use a different image by using the @code{-i},
                   15210: @code{--image-file} or @code{--appl-image} options (@pxref{Invoking
                   15211: Gforth}), e.g.:
                   15212: 
                   15213: @example
                   15214: gforth-fast -i myimage.fi
                   15215: @end example
                   15216: 
                   15217: There are different variants of image files, and they represent
                   15218: different compromises between the goals of making it easy to generate
                   15219: image files and making them portable.
1.1       anton    15220: 
                   15221: @cindex relocation at run-time
1.26      crook    15222: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1       anton    15223: run-time. This avoids many of the complications discussed below (image
                   15224: files are data relocatable without further ado), but costs performance
1.204     anton    15225: (one addition per memory access) and makes it difficult to pass
                   15226: addresses between Forth and library calls or other programs.
1.1       anton    15227: 
                   15228: @cindex relocation at load-time
1.26      crook    15229: By contrast, the Gforth loader performs relocation at image load time. The
                   15230: loader also has to replace tokens that represent primitive calls with the
1.1       anton    15231: appropriate code-field addresses (or code addresses in the case of
                   15232: direct threading).
                   15233: 
                   15234: There are three kinds of image files, with different degrees of
                   15235: relocatability: non-relocatable, data-relocatable, and fully relocatable
                   15236: image files.
                   15237: 
                   15238: @cindex image file loader
                   15239: @cindex relocating loader
                   15240: @cindex loader for image files
                   15241: These image file variants have several restrictions in common; they are
                   15242: caused by the design of the image file loader:
                   15243: 
                   15244: @itemize @bullet
                   15245: @item
                   15246: There is only one segment; in particular, this means, that an image file
                   15247: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26      crook    15248: them). The contents of the stacks are not represented, either.
1.1       anton    15249: 
                   15250: @item
                   15251: The only kinds of relocation supported are: adding the same offset to
                   15252: all cells that represent data addresses; and replacing special tokens
                   15253: with code addresses or with pieces of machine code.
                   15254: 
                   15255: If any complex computations involving addresses are performed, the
                   15256: results cannot be represented in the image file. Several applications that
                   15257: use such computations come to mind:
1.204     anton    15258: 
1.1       anton    15259: @itemize @minus
                   15260: @item
                   15261: Hashing addresses (or data structures which contain addresses) for table
                   15262: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
                   15263: purpose, you will have no problem, because the hash tables are
                   15264: recomputed automatically when the system is started. If you use your own
                   15265: hash tables, you will have to do something similar.
                   15266: 
                   15267: @item
                   15268: There's a cute implementation of doubly-linked lists that uses
                   15269: @code{XOR}ed addresses. You could represent such lists as singly-linked
                   15270: in the image file, and restore the doubly-linked representation on
                   15271: startup.@footnote{In my opinion, though, you should think thrice before
                   15272: using a doubly-linked list (whatever implementation).}
                   15273: 
                   15274: @item
                   15275: The code addresses of run-time routines like @code{docol:} cannot be
                   15276: represented in the image file (because their tokens would be replaced by
                   15277: machine code in direct threaded implementations). As a workaround,
                   15278: compute these addresses at run-time with @code{>code-address} from the
                   15279: executions tokens of appropriate words (see the definitions of
1.80      anton    15280: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1       anton    15281: 
                   15282: @item
                   15283: On many architectures addresses are represented in machine code in some
                   15284: shifted or mangled form. You cannot put @code{CODE} words that contain
                   15285: absolute addresses in this form in a relocatable image file. Workarounds
                   15286: are representing the address in some relative form (e.g., relative to
                   15287: the CFA, which is present in some register), or loading the address from
                   15288: a place where it is stored in a non-mangled form.
                   15289: @end itemize
                   15290: @end itemize
                   15291: 
                   15292: @node  Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
                   15293: @section Non-Relocatable Image Files
                   15294: @cindex non-relocatable image files
1.26      crook    15295: @cindex image file, non-relocatable
1.1       anton    15296: 
1.204     anton    15297: These files are simple memory dumps of the dictionary. They are
                   15298: specific to the executable (i.e., @file{gforth} file) they were
                   15299: created with. What's worse, they are specific to the place on which
                   15300: the dictionary resided when the image was created. Now, there is no
1.1       anton    15301: guarantee that the dictionary will reside at the same place the next
                   15302: time you start Gforth, so there's no guarantee that a non-relocatable
1.204     anton    15303: image will work the next time (Gforth will complain instead of
                   15304: crashing, though).  Indeed, on OSs with (enabled) address-space
                   15305: randomization non-relocatable images are unlikely to work.
1.1       anton    15306: 
1.204     anton    15307: You can create a non-relocatable image file with @code{savesystem}, e.g.:
1.1       anton    15308: 
1.204     anton    15309: @example
                   15310: gforth app.fs -e "savesystem app.fi bye"
                   15311: @end example
1.44      crook    15312: 
1.1       anton    15313: doc-savesystem
                   15314: 
1.44      crook    15315: 
1.1       anton    15316: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
                   15317: @section Data-Relocatable Image Files
                   15318: @cindex data-relocatable image files
1.26      crook    15319: @cindex image file, data-relocatable
1.1       anton    15320: 
1.204     anton    15321: These files contain relocatable data addresses, but fixed code
                   15322: addresses (instead of tokens). They are specific to the executable
                   15323: (i.e., @file{gforth} file) they were created with.  Also, they disable
                   15324: dynamic native code generation (typically a factor of 2 in speed).
                   15325: You get a data-relocatable image, if you pass the engine you want to
                   15326: use through the @code{GFORTHD} environment variable to @file{gforthmi}
                   15327: (@pxref{gforthmi}), e.g.
                   15328: 
                   15329: @example
                   15330: GFORTHD="/usr/bin/gforth-fast --no-dynamic" gforthmi myimage.fi source.fs
                   15331: @end example
                   15332: 
                   15333: Note that the @code{--no-dynamic} is required here for the image to
                   15334: work (otherwise it will contain references to dynamically generated
                   15335: code that is not saved in the image).
                   15336: 
1.1       anton    15337: 
                   15338: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
                   15339: @section Fully Relocatable Image Files
                   15340: @cindex fully relocatable image files
1.26      crook    15341: @cindex image file, fully relocatable
1.1       anton    15342: 
                   15343: @cindex @file{kern*.fi}, relocatability
                   15344: @cindex @file{gforth.fi}, relocatability
                   15345: These image files have relocatable data addresses, and tokens for code
                   15346: addresses. They can be used with different binaries (e.g., with and
                   15347: without debugging) on the same machine, and even across machines with
1.204     anton    15348: the same data formats (byte order, cell size, floating point format),
                   15349: and they work with dynamic native code generation.  However, they are
                   15350: usually specific to the version of Gforth they were created with. The
                   15351: files @file{gforth.fi} and @file{kernl*.fi} are fully relocatable.
1.1       anton    15352: 
                   15353: There are two ways to create a fully relocatable image file:
                   15354: 
                   15355: @menu
1.29      crook    15356: * gforthmi::                    The normal way
1.1       anton    15357: * cross.fs::                    The hard way
                   15358: @end menu
                   15359: 
                   15360: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
                   15361: @subsection @file{gforthmi}
                   15362: @cindex @file{comp-i.fs}
                   15363: @cindex @file{gforthmi}
                   15364: 
                   15365: You will usually use @file{gforthmi}. If you want to create an
1.29      crook    15366: image @i{file} that contains everything you would load by invoking
                   15367: Gforth with @code{gforth @i{options}}, you simply say:
1.1       anton    15368: @example
1.29      crook    15369: gforthmi @i{file} @i{options}
1.1       anton    15370: @end example
                   15371: 
                   15372: E.g., if you want to create an image @file{asm.fi} that has the file
                   15373: @file{asm.fs} loaded in addition to the usual stuff, you could do it
                   15374: like this:
                   15375: 
                   15376: @example
                   15377: gforthmi asm.fi asm.fs
                   15378: @end example
                   15379: 
1.27      crook    15380: @file{gforthmi} is implemented as a sh script and works like this: It
                   15381: produces two non-relocatable images for different addresses and then
                   15382: compares them. Its output reflects this: first you see the output (if
1.62      crook    15383: any) of the two Gforth invocations that produce the non-relocatable image
1.27      crook    15384: files, then you see the output of the comparing program: It displays the
                   15385: offset used for data addresses and the offset used for code addresses;
1.1       anton    15386: moreover, for each cell that cannot be represented correctly in the
1.44      crook    15387: image files, it displays a line like this:
1.1       anton    15388: 
                   15389: @example
                   15390:      78DC         BFFFFA50         BFFFFA40
                   15391: @end example
                   15392: 
                   15393: This means that at offset $78dc from @code{forthstart}, one input image
                   15394: contains $bffffa50, and the other contains $bffffa40. Since these cells
                   15395: cannot be represented correctly in the output image, you should examine
                   15396: these places in the dictionary and verify that these cells are dead
                   15397: (i.e., not read before they are written).
1.39      anton    15398: 
                   15399: @cindex --application, @code{gforthmi} option
                   15400: If you insert the option @code{--application} in front of the image file
                   15401: name, you will get an image that uses the @code{--appl-image} option
                   15402: instead of the @code{--image-file} option (@pxref{Invoking
                   15403: Gforth}). When you execute such an image on Unix (by typing the image
                   15404: name as command), the Gforth engine will pass all options to the image
                   15405: instead of trying to interpret them as engine options.
1.1       anton    15406: 
1.27      crook    15407: If you type @file{gforthmi} with no arguments, it prints some usage
                   15408: instructions.
                   15409: 
1.1       anton    15410: @cindex @code{savesystem} during @file{gforthmi}
                   15411: @cindex @code{bye} during @file{gforthmi}
                   15412: @cindex doubly indirect threaded code
1.44      crook    15413: @cindex environment variables
                   15414: @cindex @code{GFORTHD} -- environment variable
                   15415: @cindex @code{GFORTH} -- environment variable
1.1       anton    15416: @cindex @code{gforth-ditc}
1.29      crook    15417: There are a few wrinkles: After processing the passed @i{options}, the
1.204     anton    15418: words @code{savesystem} and @code{bye} must be visible. A special
                   15419: doubly indirect threaded version of the @file{gforth} executable is
                   15420: used for creating the non-relocatable images; you can pass the exact
                   15421: filename of this executable through the environment variable
                   15422: @code{GFORTHD} (default: @file{gforth-ditc}); if you pass a version
                   15423: that is not doubly indirect threaded, you will not get a fully
                   15424: relocatable image, but a data-relocatable image
                   15425: (@pxref{Data-Relocatable Image Files}), because there is no code
                   15426: address offset). The normal @file{gforth} executable is used for
                   15427: creating the relocatable image; you can pass the exact filename of
                   15428: this executable through the environment variable @code{GFORTH}.
1.1       anton    15429: 
                   15430: @node cross.fs,  , gforthmi, Fully Relocatable Image Files
                   15431: @subsection @file{cross.fs}
                   15432: @cindex @file{cross.fs}
                   15433: @cindex cross-compiler
                   15434: @cindex metacompiler
1.47      crook    15435: @cindex target compiler
1.1       anton    15436: 
                   15437: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47      crook    15438: programming language (@pxref{Cross Compiler}).
1.1       anton    15439: 
1.47      crook    15440: @code{cross} allows you to create image files for machines with
1.1       anton    15441: different data sizes and data formats than the one used for generating
                   15442: the image file. You can also use it to create an application image that
                   15443: does not contain a Forth compiler. These features are bought with
                   15444: restrictions and inconveniences in programming. E.g., addresses have to
                   15445: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
                   15446: order to make the code relocatable.
                   15447: 
                   15448: 
                   15449: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
                   15450: @section Stack and Dictionary Sizes
                   15451: @cindex image file, stack and dictionary sizes
                   15452: @cindex dictionary size default
                   15453: @cindex stack size default
                   15454: 
                   15455: If you invoke Gforth with a command line flag for the size
                   15456: (@pxref{Invoking Gforth}), the size you specify is stored in the
                   15457: dictionary. If you save the dictionary with @code{savesystem} or create
                   15458: an image with @file{gforthmi}, this size will become the default
                   15459: for the resulting image file. E.g., the following will create a
1.21      crook    15460: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1       anton    15461: 
                   15462: @example
                   15463: gforthmi gforth.fi -m 1M
                   15464: @end example
                   15465: 
                   15466: In other words, if you want to set the default size for the dictionary
                   15467: and the stacks of an image, just invoke @file{gforthmi} with the
                   15468: appropriate options when creating the image.
                   15469: 
                   15470: @cindex stack size, cache-friendly
                   15471: Note: For cache-friendly behaviour (i.e., good performance), you should
                   15472: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
                   15473: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
                   15474: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
                   15475: 
                   15476: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
                   15477: @section Running Image Files
                   15478: @cindex running image files
                   15479: @cindex invoking image files
                   15480: @cindex image file invocation
                   15481: 
                   15482: @cindex -i, invoke image file
                   15483: @cindex --image file, invoke image file
1.29      crook    15484: You can invoke Gforth with an image file @i{image} instead of the
1.1       anton    15485: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
                   15486: @example
1.29      crook    15487: gforth -i @i{image}
1.1       anton    15488: @end example
                   15489: 
                   15490: @cindex executable image file
1.26      crook    15491: @cindex image file, executable
1.1       anton    15492: If your operating system supports starting scripts with a line of the
                   15493: form @code{#! ...}, you just have to type the image file name to start
                   15494: Gforth with this image file (note that the file extension @code{.fi} is
1.29      crook    15495: just a convention). I.e., to run Gforth with the image file @i{image},
                   15496: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27      crook    15497: This works because every @code{.fi} file starts with a line of this
                   15498: format:
                   15499: 
                   15500: @example
                   15501: #! /usr/local/bin/gforth-0.4.0 -i
                   15502: @end example
                   15503: 
                   15504: The file and pathname for the Gforth engine specified on this line is
                   15505: the specific Gforth executable that it was built against; i.e. the value
                   15506: of the environment variable @code{GFORTH} at the time that
                   15507: @file{gforthmi} was executed.
1.1       anton    15508: 
1.27      crook    15509: You can make use of the same shell capability to make a Forth source
                   15510: file into an executable. For example, if you place this text in a file:
1.26      crook    15511: 
                   15512: @example
                   15513: #! /usr/local/bin/gforth
                   15514: 
                   15515: ." Hello, world" CR
                   15516: bye
                   15517: @end example
                   15518: 
                   15519: @noindent
1.27      crook    15520: and then make the file executable (chmod +x in Unix), you can run it
1.26      crook    15521: directly from the command line. The sequence @code{#!} is used in two
                   15522: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29      crook    15523: system@footnote{The Unix kernel actually recognises two types of files:
                   15524: executable files and files of data, where the data is processed by an
                   15525: interpreter that is specified on the ``interpreter line'' -- the first
                   15526: line of the file, starting with the sequence #!. There may be a small
                   15527: limit (e.g., 32) on the number of characters that may be specified on
                   15528: the interpreter line.} secondly it is treated as a comment character by
                   15529: Gforth. Because of the second usage, a space is required between
1.80      anton    15530: @code{#!} and the path to the executable (moreover, some Unixes
                   15531: require the sequence @code{#! /}).
1.27      crook    15532: 
                   15533: The disadvantage of this latter technique, compared with using
1.80      anton    15534: @file{gforthmi}, is that it is slightly slower; the Forth source code is
                   15535: compiled on-the-fly, each time the program is invoked.
1.26      crook    15536: 
1.1       anton    15537: doc-#!
                   15538: 
1.44      crook    15539: 
1.1       anton    15540: @node Modifying the Startup Sequence,  , Running Image Files, Image Files
                   15541: @section Modifying the Startup Sequence
                   15542: @cindex startup sequence for image file
                   15543: @cindex image file initialization sequence
                   15544: @cindex initialization sequence of image file
                   15545: 
1.120     anton    15546: You can add your own initialization to the startup sequence of an image
                   15547: through the deferred word @code{'cold}. @code{'cold} is invoked just
                   15548: before the image-specific command line processing (i.e., loading files
                   15549: and evaluating (@code{-e}) strings) starts.
1.1       anton    15550: 
                   15551: A sequence for adding your initialization usually looks like this:
                   15552: 
                   15553: @example
                   15554: :noname
                   15555:     Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
                   15556:     ... \ your stuff
                   15557: ; IS 'cold
                   15558: @end example
                   15559: 
1.157     anton    15560: After @code{'cold}, Gforth processes the image options
                   15561: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
                   15562: another deferred word.  This normally prints Gforth's startup message
                   15563: and does nothing else.
                   15564: 
1.1       anton    15565: @cindex turnkey image files
1.26      crook    15566: @cindex image file, turnkey applications
1.157     anton    15567: So, if you want to make a turnkey image (i.e., an image for an
                   15568: application instead of an extended Forth system), you can do this in
                   15569: two ways:
                   15570: 
                   15571: @itemize @bullet
                   15572: 
                   15573: @item
                   15574: If you want to do your interpretation of the OS command-line
                   15575: arguments, hook into @code{'cold}.  In that case you probably also
                   15576: want to build the image with @code{gforthmi --application}
                   15577: (@pxref{gforthmi}) to keep the engine from processing OS command line
                   15578: options.  You can then do your own command-line processing with
                   15579: @code{next-arg} 
                   15580: 
                   15581: @item
                   15582: If you want to have the normal Gforth processing of OS command-line
                   15583: arguments, hook into @code{bootmessage}.
                   15584: 
                   15585: @end itemize
                   15586: 
                   15587: In either case, you probably do not want the word that you execute in
                   15588: these hooks to exit normally, but use @code{bye} or @code{throw}.
                   15589: Otherwise the Gforth startup process would continue and eventually
                   15590: present the Forth command line to the user.
1.26      crook    15591: 
                   15592: doc-'cold
1.157     anton    15593: doc-bootmessage
1.44      crook    15594: 
1.1       anton    15595: @c ******************************************************************
1.113     anton    15596: @node Engine, Cross Compiler, Image Files, Top
1.1       anton    15597: @chapter Engine
                   15598: @cindex engine
                   15599: @cindex virtual machine
                   15600: 
1.26      crook    15601: Reading this chapter is not necessary for programming with Gforth. It
1.1       anton    15602: may be helpful for finding your way in the Gforth sources.
                   15603: 
1.109     anton    15604: The ideas in this section have also been published in the following
                   15605: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
                   15606: Forth-Tagung '93; M. Anton Ertl,
                   15607: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
                   15608: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
                   15609: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
                   15610: Threaded code variations and optimizations (extended version)}},
                   15611: Forth-Tagung '02.
1.1       anton    15612: 
                   15613: @menu
                   15614: * Portability::                 
                   15615: * Threading::                   
                   15616: * Primitives::                  
                   15617: * Performance::                 
                   15618: @end menu
                   15619: 
                   15620: @node Portability, Threading, Engine, Engine
                   15621: @section Portability
                   15622: @cindex engine portability
                   15623: 
1.26      crook    15624: An important goal of the Gforth Project is availability across a wide
                   15625: range of personal machines. fig-Forth, and, to a lesser extent, F83,
                   15626: achieved this goal by manually coding the engine in assembly language
                   15627: for several then-popular processors. This approach is very
                   15628: labor-intensive and the results are short-lived due to progress in
                   15629: computer architecture.
1.1       anton    15630: 
                   15631: @cindex C, using C for the engine
                   15632: Others have avoided this problem by coding in C, e.g., Mitch Bradley
                   15633: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
                   15634: particularly popular for UNIX-based Forths due to the large variety of
                   15635: architectures of UNIX machines. Unfortunately an implementation in C
                   15636: does not mix well with the goals of efficiency and with using
                   15637: traditional techniques: Indirect or direct threading cannot be expressed
                   15638: in C, and switch threading, the fastest technique available in C, is
                   15639: significantly slower. Another problem with C is that it is very
                   15640: cumbersome to express double integer arithmetic.
                   15641: 
                   15642: @cindex GNU C for the engine
                   15643: @cindex long long
                   15644: Fortunately, there is a portable language that does not have these
                   15645: limitations: GNU C, the version of C processed by the GNU C compiler
                   15646: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
                   15647: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
                   15648: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
                   15649: threading possible, its @code{long long} type (@pxref{Long Long, ,
                   15650: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109     anton    15651: double numbers on many systems.  GNU C is freely available on all
1.1       anton    15652: important (and many unimportant) UNIX machines, VMS, 80386s running
                   15653: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
                   15654: on all these machines.
                   15655: 
                   15656: Writing in a portable language has the reputation of producing code that
                   15657: is slower than assembly. For our Forth engine we repeatedly looked at
                   15658: the code produced by the compiler and eliminated most compiler-induced
                   15659: inefficiencies by appropriate changes in the source code.
                   15660: 
                   15661: @cindex explicit register declarations
                   15662: @cindex --enable-force-reg, configuration flag
                   15663: @cindex -DFORCE_REG
                   15664: However, register allocation cannot be portably influenced by the
                   15665: programmer, leading to some inefficiencies on register-starved
                   15666: machines. We use explicit register declarations (@pxref{Explicit Reg
                   15667: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
                   15668: improve the speed on some machines. They are turned on by using the
                   15669: configuration flag @code{--enable-force-reg} (@code{gcc} switch
                   15670: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
                   15671: machine, but also on the compiler version: On some machines some
                   15672: compiler versions produce incorrect code when certain explicit register
                   15673: declarations are used. So by default @code{-DFORCE_REG} is not used.
                   15674: 
                   15675: @node Threading, Primitives, Portability, Engine
                   15676: @section Threading
                   15677: @cindex inner interpreter implementation
                   15678: @cindex threaded code implementation
                   15679: 
                   15680: @cindex labels as values
                   15681: GNU C's labels as values extension (available since @code{gcc-2.0},
                   15682: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29      crook    15683: makes it possible to take the address of @i{label} by writing
                   15684: @code{&&@i{label}}.  This address can then be used in a statement like
                   15685: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1       anton    15686: @code{goto x}.
                   15687: 
1.26      crook    15688: @cindex @code{NEXT}, indirect threaded
1.1       anton    15689: @cindex indirect threaded inner interpreter
                   15690: @cindex inner interpreter, indirect threaded
1.26      crook    15691: With this feature an indirect threaded @code{NEXT} looks like:
1.1       anton    15692: @example
                   15693: cfa = *ip++;
                   15694: ca = *cfa;
                   15695: goto *ca;
                   15696: @end example
                   15697: @cindex instruction pointer
                   15698: For those unfamiliar with the names: @code{ip} is the Forth instruction
                   15699: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
                   15700: execution token and points to the code field of the next word to be
                   15701: executed; The @code{ca} (code address) fetched from there points to some
                   15702: executable code, e.g., a primitive or the colon definition handler
                   15703: @code{docol}.
                   15704: 
1.26      crook    15705: @cindex @code{NEXT}, direct threaded
1.1       anton    15706: @cindex direct threaded inner interpreter
                   15707: @cindex inner interpreter, direct threaded
                   15708: Direct threading is even simpler:
                   15709: @example
                   15710: ca = *ip++;
                   15711: goto *ca;
                   15712: @end example
                   15713: 
                   15714: Of course we have packaged the whole thing neatly in macros called
1.26      crook    15715: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1       anton    15716: 
                   15717: @menu
                   15718: * Scheduling::                  
                   15719: * Direct or Indirect Threaded?::  
1.109     anton    15720: * Dynamic Superinstructions::   
1.1       anton    15721: * DOES>::                       
                   15722: @end menu
                   15723: 
                   15724: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
                   15725: @subsection Scheduling
                   15726: @cindex inner interpreter optimization
                   15727: 
                   15728: There is a little complication: Pipelined and superscalar processors,
                   15729: i.e., RISC and some modern CISC machines can process independent
                   15730: instructions while waiting for the results of an instruction. The
                   15731: compiler usually reorders (schedules) the instructions in a way that
                   15732: achieves good usage of these delay slots. However, on our first tries
                   15733: the compiler did not do well on scheduling primitives. E.g., for
                   15734: @code{+} implemented as
                   15735: @example
                   15736: n=sp[0]+sp[1];
                   15737: sp++;
                   15738: sp[0]=n;
                   15739: NEXT;
                   15740: @end example
1.81      anton    15741: the @code{NEXT} comes strictly after the other code, i.e., there is
                   15742: nearly no scheduling. After a little thought the problem becomes clear:
                   15743: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21      crook    15744: addresses (and the version of @code{gcc} we used would not know it even
                   15745: if it was possible), so it could not move the load of the cfa above the
                   15746: store to the TOS. Indeed the pointers could be the same, if code on or
                   15747: very near the top of stack were executed. In the interest of speed we
                   15748: chose to forbid this probably unused ``feature'' and helped the compiler
1.81      anton    15749: in scheduling: @code{NEXT} is divided into several parts:
                   15750: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
                   15751: like:
1.1       anton    15752: @example
1.81      anton    15753: NEXT_P0;
1.1       anton    15754: n=sp[0]+sp[1];
                   15755: sp++;
                   15756: NEXT_P1;
                   15757: sp[0]=n;
                   15758: NEXT_P2;
                   15759: @end example
                   15760: 
1.81      anton    15761: There are various schemes that distribute the different operations of
                   15762: NEXT between these parts in several ways; in general, different schemes
                   15763: perform best on different processors.  We use a scheme for most
                   15764: architectures that performs well for most processors of this
1.109     anton    15765: architecture; in the future we may switch to benchmarking and chosing
1.81      anton    15766: the scheme on installation time.
                   15767: 
1.1       anton    15768: 
1.109     anton    15769: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1       anton    15770: @subsection Direct or Indirect Threaded?
                   15771: @cindex threading, direct or indirect?
                   15772: 
1.109     anton    15773: Threaded forth code consists of references to primitives (simple machine
                   15774: code routines like @code{+}) and to non-primitives (e.g., colon
                   15775: definitions, variables, constants); for a specific class of
                   15776: non-primitives (e.g., variables) there is one code routine (e.g.,
                   15777: @code{dovar}), but each variable needs a separate reference to its data.
                   15778: 
                   15779: Traditionally Forth has been implemented as indirect threaded code,
                   15780: because this allows to use only one cell to reference a non-primitive
                   15781: (basically you point to the data, and find the code address there).
                   15782: 
                   15783: @cindex primitive-centric threaded code
                   15784: However, threaded code in Gforth (since 0.6.0) uses two cells for
                   15785: non-primitives, one for the code address, and one for the data address;
                   15786: the data pointer is an immediate argument for the virtual machine
                   15787: instruction represented by the code address.  We call this
                   15788: @emph{primitive-centric} threaded code, because all code addresses point
                   15789: to simple primitives.  E.g., for a variable, the code address is for
                   15790: @code{lit} (also used for integer literals like @code{99}).
                   15791: 
                   15792: Primitive-centric threaded code allows us to use (faster) direct
                   15793: threading as dispatch method, completely portably (direct threaded code
                   15794: in Gforth before 0.6.0 required architecture-specific code).  It also
                   15795: eliminates the performance problems related to I-cache consistency that
                   15796: 386 implementations have with direct threaded code, and allows
                   15797: additional optimizations.
                   15798: 
                   15799: @cindex hybrid direct/indirect threaded code
                   15800: There is a catch, however: the @var{xt} parameter of @code{execute} can
                   15801: occupy only one cell, so how do we pass non-primitives with their code
                   15802: @emph{and} data addresses to them?  Our answer is to use indirect
                   15803: threaded dispatch for @code{execute} and other words that use a
                   15804: single-cell xt.  So, normal threaded code in colon definitions uses
                   15805: direct threading, and @code{execute} and similar words, which dispatch
                   15806: to xts on the data stack, use indirect threaded code.  We call this
                   15807: @emph{hybrid direct/indirect} threaded code.
                   15808: 
                   15809: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
                   15810: @cindex gforth engine
                   15811: @cindex gforth-fast engine
                   15812: The engines @command{gforth} and @command{gforth-fast} use hybrid
                   15813: direct/indirect threaded code.  This means that with these engines you
                   15814: cannot use @code{,} to compile an xt.  Instead, you have to use
                   15815: @code{compile,}.
                   15816: 
                   15817: @cindex gforth-itc engine
1.115     anton    15818: If you want to compile xts with @code{,}, use @command{gforth-itc}.
                   15819: This engine uses plain old indirect threaded code.  It still compiles in
                   15820: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109     anton    15821: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115     anton    15822: ... [}).  If you want to do that, you have to use @command{gforth-itc}
1.109     anton    15823: and execute @code{' , is compile,}.  Your program can check if it is
                   15824: running on a hybrid direct/indirect threaded engine or a pure indirect
                   15825: threaded engine with @code{threading-method} (@pxref{Threading Words}).
                   15826: 
                   15827: 
                   15828: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
                   15829: @subsection Dynamic Superinstructions
                   15830: @cindex Dynamic superinstructions with replication
                   15831: @cindex Superinstructions
                   15832: @cindex Replication
                   15833: 
                   15834: The engines @command{gforth} and @command{gforth-fast} use another
                   15835: optimization: Dynamic superinstructions with replication.  As an
                   15836: example, consider the following colon definition:
                   15837: 
                   15838: @example
                   15839: : squared ( n1 -- n2 )
                   15840:   dup * ;
                   15841: @end example
                   15842: 
                   15843: Gforth compiles this into the threaded code sequence
                   15844: 
                   15845: @example
                   15846: dup
                   15847: *
                   15848: ;s
                   15849: @end example
                   15850: 
                   15851: In normal direct threaded code there is a code address occupying one
                   15852: cell for each of these primitives.  Each code address points to a
                   15853: machine code routine, and the interpreter jumps to this machine code in
                   15854: order to execute the primitive.  The routines for these three
                   15855: primitives are (in @command{gforth-fast} on the 386):
                   15856: 
                   15857: @example
                   15858: Code dup  
                   15859: ( $804B950 )  add     esi , # -4  \ $83 $C6 $FC 
                   15860: ( $804B953 )  add     ebx , # 4  \ $83 $C3 $4 
                   15861: ( $804B956 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
                   15862: ( $804B959 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15863: end-code
                   15864: Code *  
                   15865: ( $804ACC4 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
                   15866: ( $804ACC7 )  add     esi , # 4  \ $83 $C6 $4 
                   15867: ( $804ACCA )  add     ebx , # 4  \ $83 $C3 $4 
                   15868: ( $804ACCD )  imul    ecx , eax  \ $F $AF $C8 
                   15869: ( $804ACD0 )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15870: end-code
                   15871: Code ;s  
                   15872: ( $804A693 )  mov     eax , dword ptr [edi]  \ $8B $7 
                   15873: ( $804A695 )  add     edi , # 4  \ $83 $C7 $4 
                   15874: ( $804A698 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
                   15875: ( $804A69B )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15876: end-code
                   15877: @end example
                   15878: 
                   15879: With dynamic superinstructions and replication the compiler does not
                   15880: just lay down the threaded code, but also copies the machine code
                   15881: fragments, usually without the jump at the end.
                   15882: 
                   15883: @example
                   15884: ( $4057D27D )  add     esi , # -4  \ $83 $C6 $FC 
                   15885: ( $4057D280 )  add     ebx , # 4  \ $83 $C3 $4 
                   15886: ( $4057D283 )  mov     dword ptr 4 [esi] , ecx  \ $89 $4E $4 
                   15887: ( $4057D286 )  mov     eax , dword ptr 4 [esi]  \ $8B $46 $4 
                   15888: ( $4057D289 )  add     esi , # 4  \ $83 $C6 $4 
                   15889: ( $4057D28C )  add     ebx , # 4  \ $83 $C3 $4 
                   15890: ( $4057D28F )  imul    ecx , eax  \ $F $AF $C8 
                   15891: ( $4057D292 )  mov     eax , dword ptr [edi]  \ $8B $7 
                   15892: ( $4057D294 )  add     edi , # 4  \ $83 $C7 $4 
                   15893: ( $4057D297 )  lea     ebx , dword ptr 4 [eax]  \ $8D $58 $4 
                   15894: ( $4057D29A )  jmp     dword ptr FC [ebx]  \ $FF $63 $FC 
                   15895: @end example
                   15896: 
                   15897: Only when a threaded-code control-flow change happens (e.g., in
                   15898: @code{;s}), the jump is appended.  This optimization eliminates many of
                   15899: these jumps and makes the rest much more predictable.  The speedup
                   15900: depends on the processor and the application; on the Athlon and Pentium
                   15901: III this optimization typically produces a speedup by a factor of 2.
                   15902: 
                   15903: The code addresses in the direct-threaded code are set to point to the
                   15904: appropriate points in the copied machine code, in this example like
                   15905: this:
1.1       anton    15906: 
1.109     anton    15907: @example
                   15908: primitive  code address
                   15909:    dup       $4057D27D
                   15910:    *         $4057D286
                   15911:    ;s        $4057D292
                   15912: @end example
                   15913: 
                   15914: Thus there can be threaded-code jumps to any place in this piece of
                   15915: code.  This also simplifies decompilation quite a bit.
                   15916: 
                   15917: @cindex --no-dynamic command-line option
                   15918: @cindex --no-super command-line option
                   15919: You can disable this optimization with @option{--no-dynamic}.  You can
                   15920: use the copying without eliminating the jumps (i.e., dynamic
                   15921: replication, but without superinstructions) with @option{--no-super};
                   15922: this gives the branch prediction benefit alone; the effect on
1.110     anton    15923: performance depends on the CPU; on the Athlon and Pentium III the
                   15924: speedup is a little less than for dynamic superinstructions with
                   15925: replication.
                   15926: 
                   15927: @cindex patching threaded code
                   15928: One use of these options is if you want to patch the threaded code.
                   15929: With superinstructions, many of the dispatch jumps are eliminated, so
                   15930: patching often has no effect.  These options preserve all the dispatch
                   15931: jumps.
1.109     anton    15932: 
                   15933: @cindex --dynamic command-line option
1.110     anton    15934: On some machines dynamic superinstructions are disabled by default,
                   15935: because it is unsafe on these machines.  However, if you feel
                   15936: adventurous, you can enable it with @option{--dynamic}.
1.109     anton    15937: 
                   15938: @node DOES>,  , Dynamic Superinstructions, Threading
1.1       anton    15939: @subsection DOES>
                   15940: @cindex @code{DOES>} implementation
                   15941: 
1.26      crook    15942: @cindex @code{dodoes} routine
                   15943: @cindex @code{DOES>}-code
1.1       anton    15944: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
                   15945: the chunk of code executed by every word defined by a
1.109     anton    15946: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
                   15947: this is only needed if the xt of the word is @code{execute}d. The main
                   15948: problem here is: How to find the Forth code to be executed, i.e. the
                   15949: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
                   15950: solutions:
1.1       anton    15951: 
1.21      crook    15952: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109     anton    15953: @code{DOES>}-code address is stored in the cell after the code address
                   15954: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
                   15955: illegal in the Forth-79 and all later standards, because in fig-Forth
                   15956: this address lies in the body (which is illegal in these
                   15957: standards). However, by making the code field larger for all words this
                   15958: solution becomes legal again.  We use this approach.  Leaving a cell
                   15959: unused in most words is a bit wasteful, but on the machines we are
                   15960: targeting this is hardly a problem.
                   15961: 
1.1       anton    15962: 
                   15963: @node Primitives, Performance, Threading, Engine
                   15964: @section Primitives
                   15965: @cindex primitives, implementation
                   15966: @cindex virtual machine instructions, implementation
                   15967: 
                   15968: @menu
                   15969: * Automatic Generation::        
                   15970: * TOS Optimization::            
                   15971: * Produced code::               
                   15972: @end menu
                   15973: 
                   15974: @node Automatic Generation, TOS Optimization, Primitives, Primitives
                   15975: @subsection Automatic Generation
                   15976: @cindex primitives, automatic generation
                   15977: 
                   15978: @cindex @file{prims2x.fs}
1.109     anton    15979: 
1.1       anton    15980: Since the primitives are implemented in a portable language, there is no
                   15981: longer any need to minimize the number of primitives. On the contrary,
                   15982: having many primitives has an advantage: speed. In order to reduce the
                   15983: number of errors in primitives and to make programming them easier, we
1.109     anton    15984: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
                   15985: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
                   15986: generates most (and sometimes all) of the C code for a primitive from
                   15987: the stack effect notation.  The source for a primitive has the following
                   15988: form:
1.1       anton    15989: 
                   15990: @cindex primitive source format
                   15991: @format
1.58      anton    15992: @i{Forth-name}  ( @i{stack-effect} )        @i{category}    [@i{pronounc.}]
1.29      crook    15993: [@code{""}@i{glossary entry}@code{""}]
                   15994: @i{C code}
1.1       anton    15995: [@code{:}
1.29      crook    15996: @i{Forth code}]
1.1       anton    15997: @end format
                   15998: 
                   15999: The items in brackets are optional. The category and glossary fields
                   16000: are there for generating the documentation, the Forth code is there
                   16001: for manual implementations on machines without GNU C. E.g., the source
                   16002: for the primitive @code{+} is:
                   16003: @example
1.58      anton    16004: +    ( n1 n2 -- n )   core    plus
1.1       anton    16005: n = n1+n2;
                   16006: @end example
                   16007: 
                   16008: This looks like a specification, but in fact @code{n = n1+n2} is C
                   16009: code. Our primitive generation tool extracts a lot of information from
                   16010: the stack effect notations@footnote{We use a one-stack notation, even
                   16011: though we have separate data and floating-point stacks; The separate
                   16012: notation can be generated easily from the unified notation.}: The number
                   16013: of items popped from and pushed on the stack, their type, and by what
                   16014: name they are referred to in the C code. It then generates a C code
                   16015: prelude and postlude for each primitive. The final C code for @code{+}
                   16016: looks like this:
                   16017: 
                   16018: @example
1.46      pazsan   16019: I_plus: /* + ( n1 n2 -- n ) */  /* label, stack effect */
1.1       anton    16020: /*  */                          /* documentation */
1.81      anton    16021: NAME("+")                       /* debugging output (with -DDEBUG) */
1.1       anton    16022: @{
                   16023: DEF_CA                          /* definition of variable ca (indirect threading) */
                   16024: Cell n1;                        /* definitions of variables */
                   16025: Cell n2;
                   16026: Cell n;
1.81      anton    16027: NEXT_P0;                        /* NEXT part 0 */
1.1       anton    16028: n1 = (Cell) sp[1];              /* input */
                   16029: n2 = (Cell) TOS;
                   16030: sp += 1;                        /* stack adjustment */
                   16031: @{
                   16032: n = n1+n2;                      /* C code taken from the source */
                   16033: @}
                   16034: NEXT_P1;                        /* NEXT part 1 */
                   16035: TOS = (Cell)n;                  /* output */
                   16036: NEXT_P2;                        /* NEXT part 2 */
                   16037: @}
                   16038: @end example
                   16039: 
                   16040: This looks long and inefficient, but the GNU C compiler optimizes quite
                   16041: well and produces optimal code for @code{+} on, e.g., the R3000 and the
                   16042: HP RISC machines: Defining the @code{n}s does not produce any code, and
                   16043: using them as intermediate storage also adds no cost.
                   16044: 
1.26      crook    16045: There are also other optimizations that are not illustrated by this
                   16046: example: assignments between simple variables are usually for free (copy
1.1       anton    16047: propagation). If one of the stack items is not used by the primitive
                   16048: (e.g.  in @code{drop}), the compiler eliminates the load from the stack
                   16049: (dead code elimination). On the other hand, there are some things that
                   16050: the compiler does not do, therefore they are performed by
                   16051: @file{prims2x.fs}: The compiler does not optimize code away that stores
                   16052: a stack item to the place where it just came from (e.g., @code{over}).
                   16053: 
                   16054: While programming a primitive is usually easy, there are a few cases
                   16055: where the programmer has to take the actions of the generator into
                   16056: account, most notably @code{?dup}, but also words that do not (always)
1.26      crook    16057: fall through to @code{NEXT}.
1.109     anton    16058: 
                   16059: For more information
1.1       anton    16060: 
                   16061: @node TOS Optimization, Produced code, Automatic Generation, Primitives
                   16062: @subsection TOS Optimization
                   16063: @cindex TOS optimization for primitives
                   16064: @cindex primitives, keeping the TOS in a register
                   16065: 
                   16066: An important optimization for stack machine emulators, e.g., Forth
                   16067: engines, is keeping  one or more of the top stack items in
1.29      crook    16068: registers.  If a word has the stack effect @i{in1}...@i{inx} @code{--}
                   16069: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1       anton    16070: @itemize @bullet
                   16071: @item
1.29      crook    16072: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1       anton    16073: due to fewer loads from and stores to the stack.
1.29      crook    16074: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
                   16075: @i{y<n}, due to additional moves between registers.
1.1       anton    16076: @end itemize
                   16077: 
                   16078: @cindex -DUSE_TOS
                   16079: @cindex -DUSE_NO_TOS
                   16080: In particular, keeping one item in a register is never a disadvantage,
                   16081: if there are enough registers. Keeping two items in registers is a
                   16082: disadvantage for frequent words like @code{?branch}, constants,
                   16083: variables, literals and @code{i}. Therefore our generator only produces
                   16084: code that keeps zero or one items in registers. The generated C code
                   16085: covers both cases; the selection between these alternatives is made at
                   16086: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
                   16087: code for @code{+} is just a simple variable name in the one-item case,
                   16088: otherwise it is a macro that expands into @code{sp[0]}. Note that the
                   16089: GNU C compiler tries to keep simple variables like @code{TOS} in
                   16090: registers, and it usually succeeds, if there are enough registers.
                   16091: 
                   16092: @cindex -DUSE_FTOS
                   16093: @cindex -DUSE_NO_FTOS
                   16094: The primitive generator performs the TOS optimization for the
                   16095: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
                   16096: operations the benefit of this optimization is even larger:
                   16097: floating-point operations take quite long on most processors, but can be
                   16098: performed in parallel with other operations as long as their results are
                   16099: not used. If the FP-TOS is kept in a register, this works. If
                   16100: it is kept on the stack, i.e., in memory, the store into memory has to
                   16101: wait for the result of the floating-point operation, lengthening the
                   16102: execution time of the primitive considerably.
                   16103: 
                   16104: The TOS optimization makes the automatic generation of primitives a
                   16105: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
                   16106: @code{TOS} is not sufficient. There are some special cases to
                   16107: consider:
                   16108: @itemize @bullet
                   16109: @item In the case of @code{dup ( w -- w w )} the generator must not
                   16110: eliminate the store to the original location of the item on the stack,
                   16111: if the TOS optimization is turned on.
                   16112: @item Primitives with stack effects of the form @code{--}
1.29      crook    16113: @i{out1}...@i{outy} must store the TOS to the stack at the start.
                   16114: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1       anton    16115: must load the TOS from the stack at the end. But for the null stack
                   16116: effect @code{--} no stores or loads should be generated.
                   16117: @end itemize
                   16118: 
                   16119: @node Produced code,  , TOS Optimization, Primitives
                   16120: @subsection Produced code
                   16121: @cindex primitives, assembly code listing
                   16122: 
                   16123: @cindex @file{engine.s}
                   16124: To see what assembly code is produced for the primitives on your machine
                   16125: with your compiler and your flag settings, type @code{make engine.s} and
1.81      anton    16126: look at the resulting file @file{engine.s}.  Alternatively, you can also
                   16127: disassemble the code of primitives with @code{see} on some architectures.
1.1       anton    16128: 
                   16129: @node  Performance,  , Primitives, Engine
                   16130: @section Performance
                   16131: @cindex performance of some Forth interpreters
                   16132: @cindex engine performance
                   16133: @cindex benchmarking Forth systems
                   16134: @cindex Gforth performance
                   16135: 
                   16136: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112     anton    16137: impossible to write a significantly faster threaded-code engine.
1.1       anton    16138: 
                   16139: On register-starved machines like the 386 architecture processors
                   16140: improvements are possible, because @code{gcc} does not utilize the
                   16141: registers as well as a human, even with explicit register declarations;
                   16142: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
                   16143: and hand-tuned it for the 486; this system is 1.19 times faster on the
                   16144: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40      anton    16145: @code{gcc-2.6.3} with @code{-DFORCE_REG}.  The situation has improved
                   16146: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
                   16147: registers fit in real registers (and we can even afford to use the TOS
                   16148: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112     anton    16149: earlier results.  And dynamic superinstructions provide another speedup
                   16150: (but only around a factor 1.2 on the 486).
1.1       anton    16151: 
                   16152: @cindex Win32Forth performance
                   16153: @cindex NT Forth performance
                   16154: @cindex eforth performance
                   16155: @cindex ThisForth performance
                   16156: @cindex PFE performance
                   16157: @cindex TILE performance
1.81      anton    16158: The potential advantage of assembly language implementations is not
1.112     anton    16159: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81      anton    16160: (direct threaded, compiled with @code{gcc-2.95.1} and
                   16161: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
                   16162: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
                   16163: (with and without peephole (aka pinhole) optimization of the threaded
                   16164: code); all these systems were written in assembly language. We also
                   16165: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
                   16166: with @code{gcc-2.6.3} with the default configuration for Linux:
                   16167: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
                   16168: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
                   16169: employs peephole optimization of the threaded code) and TILE (compiled
                   16170: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
                   16171: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
                   16172: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
                   16173: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
                   16174: then extended it to run the benchmarks, added the peephole optimizer,
                   16175: ran the benchmarks and reported the results.
1.40      anton    16176: 
1.1       anton    16177: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
                   16178: matrix multiplication come from the Stanford integer benchmarks and have
                   16179: been translated into Forth by Martin Fraeman; we used the versions
                   16180: included in the TILE Forth package, but with bigger data set sizes; and
                   16181: a recursive Fibonacci number computation for benchmarking calling
                   16182: performance. The following table shows the time taken for the benchmarks
                   16183: scaled by the time taken by Gforth (in other words, it shows the speedup
                   16184: factor that Gforth achieved over the other systems).
                   16185: 
                   16186: @example
1.112     anton    16187: relative       Win32-    NT       eforth       This-      
                   16188: time     Gforth Forth Forth eforth  +opt   PFE Forth  TILE
                   16189: sieve      1.00  2.16  1.78   2.16  1.32  2.46  4.96 13.37
                   16190: bubble     1.00  1.93  2.07   2.18  1.29  2.21        5.70
                   16191: matmul     1.00  1.92  1.76   1.90  0.96  2.06        5.32
                   16192: fib        1.00  2.32  2.03   1.86  1.31  2.64  4.55  6.54
1.1       anton    16193: @end example
                   16194: 
1.26      crook    16195: You may be quite surprised by the good performance of Gforth when
                   16196: compared with systems written in assembly language. One important reason
                   16197: for the disappointing performance of these other systems is probably
                   16198: that they are not written optimally for the 486 (e.g., they use the
                   16199: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
                   16200: but costly method for relocating the Forth image: like @code{cforth}, it
                   16201: computes the actual addresses at run time, resulting in two address
                   16202: computations per @code{NEXT} (@pxref{Image File Background}).
                   16203: 
1.1       anton    16204: The speedup of Gforth over PFE, ThisForth and TILE can be easily
                   16205: explained with the self-imposed restriction of the latter systems to
                   16206: standard C, which makes efficient threading impossible (however, the
1.4       anton    16207: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1       anton    16208: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
                   16209: Moreover, current C compilers have a hard time optimizing other aspects
                   16210: of the ThisForth and the TILE source.
                   16211: 
1.26      crook    16212: The performance of Gforth on 386 architecture processors varies widely
                   16213: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
                   16214: allocate any of the virtual machine registers into real machine
                   16215: registers by itself and would not work correctly with explicit register
1.112     anton    16216: declarations, giving a significantly slower engine (on a 486DX2/66
                   16217: running the Sieve) than the one measured above.
1.1       anton    16218: 
1.26      crook    16219: Note that there have been several releases of Win32Forth since the
                   16220: release presented here, so the results presented above may have little
1.40      anton    16221: predictive value for the performance of Win32Forth today (results for
                   16222: the current release on an i486DX2/66 are welcome).
1.1       anton    16223: 
                   16224: @cindex @file{Benchres}
1.66      anton    16225: In
                   16226: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
                   16227: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1       anton    16228: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66      anton    16229: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
                   16230: several native code systems; that version of Gforth is slower on a 486
1.112     anton    16231: than the version used here. You can find a newer version of these
                   16232: measurements at
1.47      crook    16233: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1       anton    16234: find numbers for Gforth on various machines in @file{Benchres}.
                   16235: 
1.26      crook    16236: @c ******************************************************************
1.113     anton    16237: @c @node Binding to System Library, Cross Compiler, Engine, Top
                   16238: @c @chapter Binding to System Library
1.13      pazsan   16239: 
1.113     anton    16240: @c ****************************************************************
                   16241: @node Cross Compiler, Bugs, Engine, Top
1.14      pazsan   16242: @chapter Cross Compiler
1.47      crook    16243: @cindex @file{cross.fs}
                   16244: @cindex cross-compiler
                   16245: @cindex metacompiler
                   16246: @cindex target compiler
1.13      pazsan   16247: 
1.46      pazsan   16248: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
                   16249: mostly written in Forth, including crucial parts like the outer
                   16250: interpreter and compiler, it needs compiled Forth code to get
                   16251: started. The cross compiler allows to create new images for other
                   16252: architectures, even running under another Forth system.
1.13      pazsan   16253: 
                   16254: @menu
1.67      anton    16255: * Using the Cross Compiler::    
                   16256: * How the Cross Compiler Works::  
1.13      pazsan   16257: @end menu
                   16258: 
1.21      crook    16259: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14      pazsan   16260: @section Using the Cross Compiler
1.46      pazsan   16261: 
                   16262: The cross compiler uses a language that resembles Forth, but isn't. The
                   16263: main difference is that you can execute Forth code after definition,
                   16264: while you usually can't execute the code compiled by cross, because the
                   16265: code you are compiling is typically for a different computer than the
                   16266: one you are compiling on.
                   16267: 
1.81      anton    16268: @c anton: This chapter is somewhat different from waht I would expect: I
                   16269: @c would expect an explanation of the cross language and how to create an
                   16270: @c application image with it.  The section explains some aspects of
                   16271: @c creating a Gforth kernel.
                   16272: 
1.46      pazsan   16273: The Makefile is already set up to allow you to create kernels for new
                   16274: architectures with a simple make command. The generic kernels using the
                   16275: GCC compiled virtual machine are created in the normal build process
                   16276: with @code{make}. To create a embedded Gforth executable for e.g. the
                   16277: 8086 processor (running on a DOS machine), type
                   16278: 
                   16279: @example
                   16280: make kernl-8086.fi
                   16281: @end example
                   16282: 
                   16283: This will use the machine description from the @file{arch/8086}
                   16284: directory to create a new kernel. A machine file may look like that:
                   16285: 
                   16286: @example
                   16287: \ Parameter for target systems                         06oct92py
                   16288: 
                   16289:     4 Constant cell             \ cell size in bytes
                   16290:     2 Constant cell<<           \ cell shift to bytes
                   16291:     5 Constant cell>bit         \ cell shift to bits
                   16292:     8 Constant bits/char        \ bits per character
                   16293:     8 Constant bits/byte        \ bits per byte [default: 8]
                   16294:     8 Constant float            \ bytes per float
                   16295:     8 Constant /maxalign        \ maximum alignment in bytes
                   16296: false Constant bigendian        \ byte order
                   16297: ( true=big, false=little )
                   16298: 
                   16299: include machpc.fs               \ feature list
                   16300: @end example
                   16301: 
                   16302: This part is obligatory for the cross compiler itself, the feature list
                   16303: is used by the kernel to conditionally compile some features in and out,
                   16304: depending on whether the target supports these features.
                   16305: 
                   16306: There are some optional features, if you define your own primitives,
                   16307: have an assembler, or need special, nonstandard preparation to make the
1.81      anton    16308: boot process work. @code{asm-include} includes an assembler,
1.46      pazsan   16309: @code{prims-include} includes primitives, and @code{>boot} prepares for
                   16310: booting.
                   16311: 
                   16312: @example
                   16313: : asm-include    ." Include assembler" cr
                   16314:   s" arch/8086/asm.fs" included ;
                   16315: 
                   16316: : prims-include  ." Include primitives" cr
                   16317:   s" arch/8086/prim.fs" included ;
                   16318: 
                   16319: : >boot          ." Prepare booting" cr
                   16320:   s" ' boot >body into-forth 1+ !" evaluate ;
                   16321: @end example
                   16322: 
                   16323: These words are used as sort of macro during the cross compilation in
1.81      anton    16324: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46      pazsan   16325: be possible --- but more complicated --- to write a new kernel project
                   16326: file, too.
                   16327: 
                   16328: @file{kernel/main.fs} expects the machine description file name on the
                   16329: stack; the cross compiler itself (@file{cross.fs}) assumes that either
                   16330: @code{mach-file} leaves a counted string on the stack, or
                   16331: @code{machine-file} leaves an address, count pair of the filename on the
                   16332: stack.
                   16333: 
                   16334: The feature list is typically controlled using @code{SetValue}, generic
                   16335: files that are used by several projects can use @code{DefaultValue}
                   16336: instead. Both functions work like @code{Value}, when the value isn't
                   16337: defined, but @code{SetValue} works like @code{to} if the value is
                   16338: defined, and @code{DefaultValue} doesn't set anything, if the value is
                   16339: defined.
                   16340: 
                   16341: @example
                   16342: \ generic mach file for pc gforth                       03sep97jaw
                   16343: 
                   16344: true DefaultValue NIL  \ relocating
                   16345: 
                   16346: >ENVIRON
                   16347: 
                   16348: true DefaultValue file          \ controls the presence of the
                   16349:                                 \ file access wordset
                   16350: true DefaultValue OS            \ flag to indicate a operating system
                   16351: 
                   16352: true DefaultValue prims         \ true: primitives are c-code
                   16353: 
                   16354: true DefaultValue floating      \ floating point wordset is present
                   16355: 
                   16356: true DefaultValue glocals       \ gforth locals are present
                   16357:                                 \ will be loaded
                   16358: true DefaultValue dcomps        \ double number comparisons
                   16359: 
                   16360: true DefaultValue hash          \ hashing primitives are loaded/present
                   16361: 
                   16362: true DefaultValue xconds        \ used together with glocals,
                   16363:                                 \ special conditionals supporting gforths'
                   16364:                                 \ local variables
                   16365: true DefaultValue header        \ save a header information
                   16366: 
                   16367: true DefaultValue backtrace     \ enables backtrace code
                   16368: 
                   16369: false DefaultValue ec
                   16370: false DefaultValue crlf
                   16371: 
                   16372: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
                   16373: 
                   16374: &16 KB          DefaultValue stack-size
                   16375: &15 KB &512 +   DefaultValue fstack-size
                   16376: &15 KB          DefaultValue rstack-size
                   16377: &14 KB &512 +   DefaultValue lstack-size
                   16378: @end example
1.13      pazsan   16379: 
1.48      anton    16380: @node How the Cross Compiler Works,  , Using the Cross Compiler, Cross Compiler
1.14      pazsan   16381: @section How the Cross Compiler Works
1.13      pazsan   16382: 
                   16383: @node Bugs, Origin, Cross Compiler, Top
1.21      crook    16384: @appendix Bugs
1.1       anton    16385: @cindex bug reporting
                   16386: 
1.21      crook    16387: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1       anton    16388: 
1.103     anton    16389: If you find a bug, please submit a bug report through
                   16390: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21      crook    16391: 
                   16392: @itemize @bullet
                   16393: @item
1.81      anton    16394: A program (or a sequence of keyboard commands) that reproduces the bug.
                   16395: @item
                   16396: A description of what you think constitutes the buggy behaviour.
                   16397: @item
1.21      crook    16398: The Gforth version used (it is announced at the start of an
                   16399: interactive Gforth session).
                   16400: @item
                   16401: The machine and operating system (on Unix
                   16402: systems @code{uname -a} will report this information).
                   16403: @item
1.81      anton    16404: The installation options (you can find the configure options at the
                   16405: start of @file{config.status}) and configuration (@code{configure}
                   16406: output or @file{config.cache}).
1.21      crook    16407: @item
                   16408: A complete list of changes (if any) you (or your installer) have made to the
                   16409: Gforth sources.
                   16410: @end itemize
1.1       anton    16411: 
                   16412: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
                   16413: to Report Bugs, gcc.info, GNU C Manual}.
                   16414: 
                   16415: 
1.21      crook    16416: @node Origin, Forth-related information, Bugs, Top
                   16417: @appendix Authors and Ancestors of Gforth
1.1       anton    16418: 
                   16419: @section Authors and Contributors
                   16420: @cindex authors of Gforth
                   16421: @cindex contributors to Gforth
                   16422: 
                   16423: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81      anton    16424: Ertl. The third major author was Jens Wilke.  Neal Crook contributed a
                   16425: lot to the manual.  Assemblers and disassemblers were contributed by
1.161     anton    16426: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
                   16427: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
                   16428: and Stuart Ramsden inspired us with their continuous feedback. Lennart
                   16429: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
                   16430: working on automatic support for calling C libraries. Helpful comments
                   16431: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
                   16432: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
                   16433: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
                   16434: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
                   16435: comments from many others; thank you all, sorry for not listing you
                   16436: here (but digging through my mailbox to extract your names is on my
                   16437: to-do list).
1.1       anton    16438: 
                   16439: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
                   16440: and autoconf, among others), and to the creators of the Internet: Gforth
1.21      crook    16441: was developed across the Internet, and its authors did not meet
1.20      pazsan   16442: physically for the first 4 years of development.
1.1       anton    16443: 
                   16444: @section Pedigree
1.26      crook    16445: @cindex pedigree of Gforth
1.1       anton    16446: 
1.81      anton    16447: Gforth descends from bigFORTH (1993) and fig-Forth.  Of course, a
                   16448: significant part of the design of Gforth was prescribed by ANS Forth.
1.1       anton    16449: 
1.20      pazsan   16450: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1       anton    16451: 32 bit native code version of VolksForth for the Atari ST, written
                   16452: mostly by Dietrich Weineck.
                   16453: 
1.81      anton    16454: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
                   16455: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147     anton    16456: the mid-80s and ported to the Atari ST in 1986.  It descends from fig-Forth.
1.1       anton    16457: 
1.147     anton    16458: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
                   16459: @c Forth-83 standard. !! Pedigree? When?
1.1       anton    16460: 
                   16461: A team led by Bill Ragsdale implemented fig-Forth on many processors in
                   16462: 1979. Robert Selzer and Bill Ragsdale developed the original
                   16463: implementation of fig-Forth for the 6502 based on microForth.
                   16464: 
                   16465: The principal architect of microForth was Dean Sanderson. microForth was
                   16466: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
                   16467: the 1802, and subsequently implemented on the 8080, the 6800 and the
                   16468: Z80.
                   16469: 
                   16470: All earlier Forth systems were custom-made, usually by Charles Moore,
                   16471: who discovered (as he puts it) Forth during the late 60s. The first full
                   16472: Forth existed in 1971.
                   16473: 
1.81      anton    16474: A part of the information in this section comes from
                   16475: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
                   16476: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147     anton    16477: Charles H. Moore, presented at the HOPL-II conference and preprinted
                   16478: in SIGPLAN Notices 28(3), 1993.  You can find more historical and
                   16479: genealogical information about Forth there.  For a more general (and
                   16480: graphical) Forth family tree look see
                   16481: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
                   16482: Forth Family Tree and Timeline}.
1.1       anton    16483: 
1.81      anton    16484: @c ------------------------------------------------------------------
1.113     anton    16485: @node Forth-related information, Licenses, Origin, Top
1.21      crook    16486: @appendix Other Forth-related information
                   16487: @cindex Forth-related information
                   16488: 
1.81      anton    16489: @c anton: I threw most of this stuff out, because it can be found through
                   16490: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21      crook    16491: 
                   16492: @cindex comp.lang.forth
                   16493: @cindex frequently asked questions
1.81      anton    16494: There is an active news group (comp.lang.forth) discussing Forth
                   16495: (including Gforth) and Forth-related issues. Its
                   16496: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
                   16497: (frequently asked questions and their answers) contains a lot of
                   16498: information on Forth.  You should read it before posting to
                   16499: comp.lang.forth.
1.21      crook    16500: 
1.81      anton    16501: The ANS Forth standard is most usable in its
                   16502: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21      crook    16503: 
1.113     anton    16504: @c ---------------------------------------------------
                   16505: @node  Licenses, Word Index, Forth-related information, Top
                   16506: @appendix Licenses
                   16507: 
                   16508: @menu
                   16509: * GNU Free Documentation License::  License for copying this manual.
1.192     anton    16510: * Copying::                     GPL (for copying this software).
1.113     anton    16511: @end menu
                   16512: 
1.192     anton    16513: @node GNU Free Documentation License, Copying, Licenses, Licenses
                   16514: @appendixsec GNU Free Documentation License
1.113     anton    16515: @include fdl.texi
                   16516: 
1.192     anton    16517: @node Copying,  , GNU Free Documentation License, Licenses
                   16518: @appendixsec GNU GENERAL PUBLIC LICENSE
1.113     anton    16519: @include gpl.texi
                   16520: 
                   16521: 
                   16522: 
1.81      anton    16523: @c ------------------------------------------------------------------
1.113     anton    16524: @node Word Index, Concept Index, Licenses, Top
1.1       anton    16525: @unnumbered Word Index
                   16526: 
1.26      crook    16527: This index is a list of Forth words that have ``glossary'' entries
                   16528: within this manual. Each word is listed with its stack effect and
                   16529: wordset.
1.1       anton    16530: 
                   16531: @printindex fn
                   16532: 
1.81      anton    16533: @c anton: the name index seems superfluous given the word and concept indices.
                   16534: 
                   16535: @c @node Name Index, Concept Index, Word Index, Top
                   16536: @c @unnumbered Name Index
1.41      anton    16537: 
1.81      anton    16538: @c This index is a list of Forth words that have ``glossary'' entries
                   16539: @c within this manual.
1.41      anton    16540: 
1.81      anton    16541: @c @printindex ky
1.41      anton    16542: 
1.113     anton    16543: @c -------------------------------------------------------
1.81      anton    16544: @node Concept Index,  , Word Index, Top
1.1       anton    16545: @unnumbered Concept and Word Index
                   16546: 
1.26      crook    16547: Not all entries listed in this index are present verbatim in the
                   16548: text. This index also duplicates, in abbreviated form, all of the words
                   16549: listed in the Word Index (only the names are listed for the words here).
1.1       anton    16550: 
                   16551: @printindex cp
                   16552: 
                   16553: @bye
1.81      anton    16554: 
                   16555: 
1.1       anton    16556: 

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