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

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.197     anton      64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008 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.48      anton     148: * Startup speed::               When 35ms is not fast enough ...
                    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.48      anton     634: * Startup speed::               When 35ms 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
                   1142: speed may become a problem.  On a 300MHz 21064a under Linux-2.2.13 with
                   1143: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
                   1144: system time.
                   1145: 
                   1146: If startup speed is a problem, you may consider the following ways to
                   1147: improve it; or you may consider ways to reduce the number of startups
1.62      crook    1148: (for example, by using Fast-CGI).
1.48      anton    1149: 
1.112     anton    1150: An easy step that influences Gforth startup speed is the use of the
                   1151: @option{--no-dynamic} option; this decreases image loading speed, but
                   1152: increases compile-time and run-time.
                   1153: 
                   1154: Another step to improve startup speed is to statically link Gforth, by
1.48      anton    1155: building it with @code{XLDFLAGS=-static}.  This requires more memory for
                   1156: the code and will therefore slow down the first invocation, but
                   1157: subsequent invocations avoid the dynamic linking overhead.  Another
                   1158: disadvantage is that Gforth won't profit from library upgrades.  As a
                   1159: result, @code{gforth-static -e bye} takes about 17.1ms user and
                   1160: 8.2ms system time.
                   1161: 
                   1162: The next step to improve startup speed is to use a non-relocatable image
1.65      anton    1163: (@pxref{Non-Relocatable Image Files}).  You can create this image with
1.48      anton    1164: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
                   1165: @code{gforth -i gforthnr.fi ...}.  This avoids the relocation overhead
                   1166: and a part of the copy-on-write overhead.  The disadvantage is that the
1.62      crook    1167: non-relocatable image does not work if the OS gives Gforth a different
1.48      anton    1168: address for the dictionary, for whatever reason; so you better provide a
                   1169: fallback on a relocatable image.  @code{gforth-static -i gforthnr.fi -e
                   1170: bye} takes about 15.3ms user and 7.5ms system time.
                   1171: 
                   1172: The final step is to disable dictionary hashing in Gforth.  Gforth
                   1173: builds the hash table on startup, which takes much of the startup
                   1174: overhead. You can do this by commenting out the @code{include hash.fs}
                   1175: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
                   1176: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
                   1177: The disadvantages are that functionality like @code{table} and
                   1178: @code{ekey} is missing and that text interpretation (e.g., compiling)
                   1179: now takes much longer. So, you should only use this method if there is
                   1180: no significant text interpretation to perform (the script should be
1.62      crook    1181: compiled into the image, amongst other things).  @code{gforth-static -i
1.48      anton    1182: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
                   1183: 
                   1184: @c ******************************************************************
                   1185: @node Tutorial, Introduction, Gforth Environment, Top
                   1186: @chapter Forth Tutorial
                   1187: @cindex Tutorial
                   1188: @cindex Forth Tutorial
                   1189: 
1.67      anton    1190: @c Topics from nac's Introduction that could be mentioned:
                   1191: @c press <ret> after each line
                   1192: @c Prompt
                   1193: @c numbers vs. words in dictionary on text interpretation
                   1194: @c what happens on redefinition
                   1195: @c parsing words (in particular, defining words)
                   1196: 
1.83      anton    1197: The difference of this chapter from the Introduction
                   1198: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
                   1199: be used while sitting in front of a computer, and covers much more
                   1200: material, but does not explain how the Forth system works.
                   1201: 
1.62      crook    1202: This tutorial can be used with any ANS-compliant Forth; any
                   1203: Gforth-specific features are marked as such and you can skip them if you
                   1204: work with another Forth.  This tutorial does not explain all features of
                   1205: Forth, just enough to get you started and give you some ideas about the
                   1206: facilities available in Forth.  Read the rest of the manual and the
                   1207: standard when you are through this.
1.48      anton    1208: 
                   1209: The intended way to use this tutorial is that you work through it while
                   1210: sitting in front of the console, take a look at the examples and predict
                   1211: what they will do, then try them out; if the outcome is not as expected,
                   1212: find out why (e.g., by trying out variations of the example), so you
                   1213: understand what's going on.  There are also some assignments that you
                   1214: should solve.
                   1215: 
                   1216: This tutorial assumes that you have programmed before and know what,
                   1217: e.g., a loop is.
                   1218: 
                   1219: @c !! explain compat library
                   1220: 
                   1221: @menu
                   1222: * Starting Gforth Tutorial::    
                   1223: * Syntax Tutorial::             
                   1224: * Crash Course Tutorial::       
                   1225: * Stack Tutorial::              
                   1226: * Arithmetics Tutorial::        
                   1227: * Stack Manipulation Tutorial::  
                   1228: * Using files for Forth code Tutorial::  
                   1229: * Comments Tutorial::           
                   1230: * Colon Definitions Tutorial::  
                   1231: * Decompilation Tutorial::      
                   1232: * Stack-Effect Comments Tutorial::  
                   1233: * Types Tutorial::              
                   1234: * Factoring Tutorial::          
                   1235: * Designing the stack effect Tutorial::  
                   1236: * Local Variables Tutorial::    
                   1237: * Conditional execution Tutorial::  
                   1238: * Flags and Comparisons Tutorial::  
                   1239: * General Loops Tutorial::      
                   1240: * Counted loops Tutorial::      
                   1241: * Recursion Tutorial::          
                   1242: * Leaving definitions or loops Tutorial::  
                   1243: * Return Stack Tutorial::       
                   1244: * Memory Tutorial::             
                   1245: * Characters and Strings Tutorial::  
                   1246: * Alignment Tutorial::          
1.190     anton    1247: * Floating Point Tutorial::     
1.87      anton    1248: * Files Tutorial::              
1.48      anton    1249: * Interpretation and Compilation Semantics and Immediacy Tutorial::  
                   1250: * Execution Tokens Tutorial::   
                   1251: * Exceptions Tutorial::         
                   1252: * Defining Words Tutorial::     
                   1253: * Arrays and Records Tutorial::  
                   1254: * POSTPONE Tutorial::           
                   1255: * Literal Tutorial::            
                   1256: * Advanced macros Tutorial::    
                   1257: * Compilation Tokens Tutorial::  
                   1258: * Wordlists and Search Order Tutorial::  
                   1259: @end menu
                   1260: 
                   1261: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
                   1262: @section Starting Gforth
1.66      anton    1263: @cindex starting Gforth tutorial
1.48      anton    1264: You can start Gforth by typing its name:
                   1265: 
                   1266: @example
                   1267: gforth
                   1268: @end example
                   1269: 
                   1270: That puts you into interactive mode; you can leave Gforth by typing
                   1271: @code{bye}.  While in Gforth, you can edit the command line and access
                   1272: the command line history with cursor keys, similar to bash.
                   1273: 
                   1274: 
                   1275: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
                   1276: @section Syntax
1.66      anton    1277: @cindex syntax tutorial
1.48      anton    1278: 
1.171     anton    1279: A @dfn{word} is a sequence of arbitrary characters (except white
1.48      anton    1280: space).  Words are separated by white space.  E.g., each of the
                   1281: following lines contains exactly one word:
                   1282: 
                   1283: @example
                   1284: word
                   1285: !@@#$%^&*()
                   1286: 1234567890
                   1287: 5!a
                   1288: @end example
                   1289: 
                   1290: A frequent beginner's error is to leave away necessary white space,
                   1291: resulting in an error like @samp{Undefined word}; so if you see such an
                   1292: error, check if you have put spaces wherever necessary.
                   1293: 
                   1294: @example
                   1295: ." hello, world" \ correct
                   1296: ."hello, world"  \ gives an "Undefined word" error
                   1297: @end example
                   1298: 
1.65      anton    1299: Gforth and most other Forth systems ignore differences in case (they are
1.48      anton    1300: case-insensitive), i.e., @samp{word} is the same as @samp{Word}.  If
                   1301: your system is case-sensitive, you may have to type all the examples
                   1302: given here in upper case.
                   1303: 
                   1304: 
                   1305: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
                   1306: @section Crash Course
                   1307: 
                   1308: Type
                   1309: 
                   1310: @example
                   1311: 0 0 !
                   1312: here execute
                   1313: ' catch >body 20 erase abort
                   1314: ' (quit) >body 20 erase
                   1315: @end example
                   1316: 
                   1317: The last two examples are guaranteed to destroy parts of Gforth (and
                   1318: most other systems), so you better leave Gforth afterwards (if it has
                   1319: not finished by itself).  On some systems you may have to kill gforth
                   1320: from outside (e.g., in Unix with @code{kill}).
                   1321: 
                   1322: Now that you know how to produce crashes (and that there's not much to
                   1323: them), let's learn how to produce meaningful programs.
                   1324: 
                   1325: 
                   1326: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
                   1327: @section Stack
1.66      anton    1328: @cindex stack tutorial
1.48      anton    1329: 
                   1330: The most obvious feature of Forth is the stack.  When you type in a
                   1331: number, it is pushed on the stack.  You can display the content of the
                   1332: stack with @code{.s}.
                   1333: 
                   1334: @example
                   1335: 1 2 .s
                   1336: 3 .s
                   1337: @end example
                   1338: 
                   1339: @code{.s} displays the top-of-stack to the right, i.e., the numbers
                   1340: appear in @code{.s} output as they appeared in the input.
                   1341: 
                   1342: You can print the top of stack element with @code{.}.
                   1343: 
                   1344: @example
                   1345: 1 2 3 . . .
                   1346: @end example
                   1347: 
                   1348: In general, words consume their stack arguments (@code{.s} is an
                   1349: exception).
                   1350: 
1.141     anton    1351: @quotation Assignment
1.48      anton    1352: What does the stack contain after @code{5 6 7 .}?
1.141     anton    1353: @end quotation
1.48      anton    1354: 
                   1355: 
                   1356: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
                   1357: @section Arithmetics
1.66      anton    1358: @cindex arithmetics tutorial
1.48      anton    1359: 
                   1360: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
                   1361: operate on the top two stack items:
                   1362: 
                   1363: @example
1.67      anton    1364: 2 2 .s
                   1365: + .s
                   1366: .
1.48      anton    1367: 2 1 - .
                   1368: 7 3 mod .
                   1369: @end example
                   1370: 
                   1371: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
                   1372: as in the corresponding infix expression (this is generally the case in
                   1373: Forth).
                   1374: 
                   1375: Parentheses are superfluous (and not available), because the order of
                   1376: the words unambiguously determines the order of evaluation and the
                   1377: operands:
                   1378: 
                   1379: @example
                   1380: 3 4 + 5 * .
                   1381: 3 4 5 * + .
                   1382: @end example
                   1383: 
1.141     anton    1384: @quotation Assignment
1.48      anton    1385: What are the infix expressions corresponding to the Forth code above?
                   1386: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
                   1387: known as Postfix or RPN (Reverse Polish Notation).}.
1.141     anton    1388: @end quotation
1.48      anton    1389: 
                   1390: To change the sign, use @code{negate}:
                   1391: 
                   1392: @example
                   1393: 2 negate .
                   1394: @end example
                   1395: 
1.141     anton    1396: @quotation Assignment
1.48      anton    1397: Convert -(-3)*4-5 to Forth.
1.141     anton    1398: @end quotation
1.48      anton    1399: 
                   1400: @code{/mod} performs both @code{/} and @code{mod}.
                   1401: 
                   1402: @example
                   1403: 7 3 /mod . .
                   1404: @end example
                   1405: 
1.66      anton    1406: Reference: @ref{Arithmetic}.
                   1407: 
                   1408: 
1.48      anton    1409: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
                   1410: @section Stack Manipulation
1.66      anton    1411: @cindex stack manipulation tutorial
1.48      anton    1412: 
                   1413: Stack manipulation words rearrange the data on the stack.
                   1414: 
                   1415: @example
                   1416: 1 .s drop .s
                   1417: 1 .s dup .s drop drop .s
                   1418: 1 2 .s over .s drop drop drop
                   1419: 1 2 .s swap .s drop drop
                   1420: 1 2 3 .s rot .s drop drop drop
                   1421: @end example
                   1422: 
                   1423: These are the most important stack manipulation words.  There are also
                   1424: variants that manipulate twice as many stack items:
                   1425: 
                   1426: @example
                   1427: 1 2 3 4 .s 2swap .s 2drop 2drop
                   1428: @end example
                   1429: 
                   1430: Two more stack manipulation words are:
                   1431: 
                   1432: @example
                   1433: 1 2 .s nip .s drop
                   1434: 1 2 .s tuck .s 2drop drop
                   1435: @end example
                   1436: 
1.141     anton    1437: @quotation Assignment
1.48      anton    1438: Replace @code{nip} and @code{tuck} with combinations of other stack
                   1439: manipulation words.
                   1440: 
                   1441: @example
                   1442: Given:          How do you get:
                   1443: 1 2 3           3 2 1           
                   1444: 1 2 3           1 2 3 2                 
                   1445: 1 2 3           1 2 3 3                 
                   1446: 1 2 3           1 3 3           
                   1447: 1 2 3           2 1 3           
                   1448: 1 2 3 4         4 3 2 1         
                   1449: 1 2 3           1 2 3 1 2 3             
                   1450: 1 2 3 4         1 2 3 4 1 2             
                   1451: 1 2 3
                   1452: 1 2 3           1 2 3 4                 
                   1453: 1 2 3           1 3             
                   1454: @end example
1.141     anton    1455: @end quotation
1.48      anton    1456: 
                   1457: @example
                   1458: 5 dup * .
                   1459: @end example
                   1460: 
1.141     anton    1461: @quotation Assignment
1.48      anton    1462: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
                   1463: Write a piece of Forth code that expects two numbers on the stack
                   1464: (@var{a} and @var{b}, with @var{b} on top) and computes
                   1465: @code{(a-b)(a+1)}.
1.141     anton    1466: @end quotation
1.48      anton    1467: 
1.66      anton    1468: Reference: @ref{Stack Manipulation}.
                   1469: 
                   1470: 
1.48      anton    1471: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
                   1472: @section Using files for Forth code
1.66      anton    1473: @cindex loading Forth code, tutorial
                   1474: @cindex files containing Forth code, tutorial
1.48      anton    1475: 
                   1476: While working at the Forth command line is convenient for one-line
                   1477: examples and short one-off code, you probably want to store your source
                   1478: code in files for convenient editing and persistence.  You can use your
                   1479: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102     anton    1480: Gforth}) to create @var{file.fs} and use
1.48      anton    1481: 
                   1482: @example
1.102     anton    1483: s" @var{file.fs}" included
1.48      anton    1484: @end example
                   1485: 
                   1486: to load it into your Forth system.  The file name extension I use for
                   1487: Forth files is @samp{.fs}.
                   1488: 
                   1489: You can easily start Gforth with some files loaded like this:
                   1490: 
                   1491: @example
1.102     anton    1492: gforth @var{file1.fs} @var{file2.fs}
1.48      anton    1493: @end example
                   1494: 
                   1495: If an error occurs during loading these files, Gforth terminates,
                   1496: whereas an error during @code{INCLUDED} within Gforth usually gives you
                   1497: a Gforth command line.  Starting the Forth system every time gives you a
                   1498: clean start every time, without interference from the results of earlier
                   1499: tries.
                   1500: 
                   1501: I often put all the tests in a file, then load the code and run the
                   1502: tests with
                   1503: 
                   1504: @example
1.102     anton    1505: gforth @var{code.fs} @var{tests.fs} -e bye
1.48      anton    1506: @end example
                   1507: 
                   1508: (often by performing this command with @kbd{C-x C-e} in Emacs).  The
                   1509: @code{-e bye} ensures that Gforth terminates afterwards so that I can
                   1510: restart this command without ado.
                   1511: 
                   1512: The advantage of this approach is that the tests can be repeated easily
                   1513: every time the program ist changed, making it easy to catch bugs
                   1514: introduced by the change.
                   1515: 
1.66      anton    1516: Reference: @ref{Forth source files}.
                   1517: 
1.48      anton    1518: 
                   1519: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
                   1520: @section Comments
1.66      anton    1521: @cindex comments tutorial
1.48      anton    1522: 
                   1523: @example
                   1524: \ That's a comment; it ends at the end of the line
                   1525: ( Another comment; it ends here: )  .s
                   1526: @end example
                   1527: 
                   1528: @code{\} and @code{(} are ordinary Forth words and therefore have to be
                   1529: separated with white space from the following text.
                   1530: 
                   1531: @example
                   1532: \This gives an "Undefined word" error
                   1533: @end example
                   1534: 
                   1535: The first @code{)} ends a comment started with @code{(}, so you cannot
                   1536: nest @code{(}-comments; and you cannot comment out text containing a
                   1537: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
                   1538: avoid @code{)} in word names.}.
                   1539: 
                   1540: I use @code{\}-comments for descriptive text and for commenting out code
                   1541: of one or more line; I use @code{(}-comments for describing the stack
                   1542: effect, the stack contents, or for commenting out sub-line pieces of
                   1543: code.
                   1544: 
                   1545: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
                   1546: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
                   1547: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
                   1548: with @kbd{M-q}.
                   1549: 
1.66      anton    1550: Reference: @ref{Comments}.
                   1551: 
1.48      anton    1552: 
                   1553: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
                   1554: @section Colon Definitions
1.66      anton    1555: @cindex colon definitions, tutorial
                   1556: @cindex definitions, tutorial
                   1557: @cindex procedures, tutorial
                   1558: @cindex functions, tutorial
1.48      anton    1559: 
                   1560: are similar to procedures and functions in other programming languages.
                   1561: 
                   1562: @example
                   1563: : squared ( n -- n^2 )
                   1564:    dup * ;
                   1565: 5 squared .
                   1566: 7 squared .
                   1567: @end example
                   1568: 
                   1569: @code{:} starts the colon definition; its name is @code{squared}.  The
                   1570: following comment describes its stack effect.  The words @code{dup *}
                   1571: are not executed, but compiled into the definition.  @code{;} ends the
                   1572: colon definition.
                   1573: 
                   1574: The newly-defined word can be used like any other word, including using
                   1575: it in other definitions:
                   1576: 
                   1577: @example
                   1578: : cubed ( n -- n^3 )
                   1579:    dup squared * ;
                   1580: -5 cubed .
                   1581: : fourth-power ( n -- n^4 )
                   1582:    squared squared ;
                   1583: 3 fourth-power .
                   1584: @end example
                   1585: 
1.141     anton    1586: @quotation Assignment
1.48      anton    1587: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
                   1588: @code{/mod} in terms of other Forth words, and check if they work (hint:
                   1589: test your tests on the originals first).  Don't let the
                   1590: @samp{redefined}-Messages spook you, they are just warnings.
1.141     anton    1591: @end quotation
1.48      anton    1592: 
1.66      anton    1593: Reference: @ref{Colon Definitions}.
                   1594: 
1.48      anton    1595: 
                   1596: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
                   1597: @section Decompilation
1.66      anton    1598: @cindex decompilation tutorial
                   1599: @cindex see tutorial
1.48      anton    1600: 
                   1601: You can decompile colon definitions with @code{see}:
                   1602: 
                   1603: @example
                   1604: see squared
                   1605: see cubed
                   1606: @end example
                   1607: 
                   1608: In Gforth @code{see} shows you a reconstruction of the source code from
                   1609: the executable code.  Informations that were present in the source, but
                   1610: not in the executable code, are lost (e.g., comments).
                   1611: 
1.65      anton    1612: You can also decompile the predefined words:
                   1613: 
                   1614: @example
                   1615: see .
                   1616: see +
                   1617: @end example
                   1618: 
                   1619: 
1.48      anton    1620: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
                   1621: @section Stack-Effect Comments
1.66      anton    1622: @cindex stack-effect comments, tutorial
                   1623: @cindex --, tutorial
1.48      anton    1624: By convention the comment after the name of a definition describes the
1.171     anton    1625: stack effect: The part in front of the @samp{--} describes the state of
1.48      anton    1626: the stack before the execution of the definition, i.e., the parameters
                   1627: that are passed into the colon definition; the part behind the @samp{--}
                   1628: is the state of the stack after the execution of the definition, i.e.,
                   1629: the results of the definition.  The stack comment only shows the top
                   1630: stack items that the definition accesses and/or changes.
                   1631: 
                   1632: You should put a correct stack effect on every definition, even if it is
                   1633: just @code{( -- )}.  You should also add some descriptive comment to
                   1634: more complicated words (I usually do this in the lines following
                   1635: @code{:}).  If you don't do this, your code becomes unreadable (because
1.117     anton    1636: you have to work through every definition before you can understand
1.48      anton    1637: any).
                   1638: 
1.141     anton    1639: @quotation Assignment
1.48      anton    1640: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
                   1641: x2 x1}.  Describe the stack effect of @code{-}, @code{drop}, @code{dup},
                   1642: @code{over}, @code{rot}, @code{nip}, and @code{tuck}.  Hint: When you
1.65      anton    1643: are done, you can compare your stack effects to those in this manual
1.48      anton    1644: (@pxref{Word Index}).
1.141     anton    1645: @end quotation
1.48      anton    1646: 
                   1647: Sometimes programmers put comments at various places in colon
                   1648: definitions that describe the contents of the stack at that place (stack
                   1649: comments); i.e., they are like the first part of a stack-effect
                   1650: comment. E.g.,
                   1651: 
                   1652: @example
                   1653: : cubed ( n -- n^3 )
                   1654:    dup squared  ( n n^2 ) * ;
                   1655: @end example
                   1656: 
                   1657: In this case the stack comment is pretty superfluous, because the word
                   1658: is simple enough.  If you think it would be a good idea to add such a
                   1659: comment to increase readability, you should also consider factoring the
                   1660: word into several simpler words (@pxref{Factoring Tutorial,,
1.60      anton    1661: Factoring}), which typically eliminates the need for the stack comment;
1.48      anton    1662: however, if you decide not to refactor it, then having such a comment is
                   1663: better than not having it.
                   1664: 
                   1665: The names of the stack items in stack-effect and stack comments in the
                   1666: standard, in this manual, and in many programs specify the type through
                   1667: a type prefix, similar to Fortran and Hungarian notation.  The most
                   1668: frequent prefixes are:
                   1669: 
                   1670: @table @code
                   1671: @item n
                   1672: signed integer
                   1673: @item u
                   1674: unsigned integer
                   1675: @item c
                   1676: character
                   1677: @item f
                   1678: Boolean flags, i.e. @code{false} or @code{true}.
                   1679: @item a-addr,a-
                   1680: Cell-aligned address
                   1681: @item c-addr,c-
                   1682: Char-aligned address (note that a Char may have two bytes in Windows NT)
                   1683: @item xt
                   1684: Execution token, same size as Cell
                   1685: @item w,x
                   1686: Cell, can contain an integer or an address.  It usually takes 32, 64 or
                   1687: 16 bits (depending on your platform and Forth system). A cell is more
                   1688: commonly known as machine word, but the term @emph{word} already means
                   1689: something different in Forth.
                   1690: @item d
                   1691: signed double-cell integer
                   1692: @item ud
                   1693: unsigned double-cell integer
                   1694: @item r
                   1695: Float (on the FP stack)
                   1696: @end table
                   1697: 
                   1698: You can find a more complete list in @ref{Notation}.
                   1699: 
1.141     anton    1700: @quotation Assignment
1.48      anton    1701: Write stack-effect comments for all definitions you have written up to
                   1702: now.
1.141     anton    1703: @end quotation
1.48      anton    1704: 
                   1705: 
                   1706: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
                   1707: @section Types
1.66      anton    1708: @cindex types tutorial
1.48      anton    1709: 
                   1710: In Forth the names of the operations are not overloaded; so similar
                   1711: operations on different types need different names; e.g., @code{+} adds
                   1712: integers, and you have to use @code{f+} to add floating-point numbers.
                   1713: The following prefixes are often used for related operations on
                   1714: different types:
                   1715: 
                   1716: @table @code
                   1717: @item (none)
                   1718: signed integer
                   1719: @item u
                   1720: unsigned integer
                   1721: @item c
                   1722: character
                   1723: @item d
                   1724: signed double-cell integer
                   1725: @item ud, du
                   1726: unsigned double-cell integer
                   1727: @item 2
                   1728: two cells (not-necessarily double-cell numbers)
                   1729: @item m, um
                   1730: mixed single-cell and double-cell operations
                   1731: @item f
                   1732: floating-point (note that in stack comments @samp{f} represents flags,
1.66      anton    1733: and @samp{r} represents FP numbers).
1.48      anton    1734: @end table
                   1735: 
                   1736: If there are no differences between the signed and the unsigned variant
                   1737: (e.g., for @code{+}), there is only the prefix-less variant.
                   1738: 
                   1739: Forth does not perform type checking, neither at compile time, nor at
                   1740: run time.  If you use the wrong oeration, the data are interpreted
                   1741: incorrectly:
                   1742: 
                   1743: @example
                   1744: -1 u.
                   1745: @end example
                   1746: 
                   1747: If you have only experience with type-checked languages until now, and
                   1748: have heard how important type-checking is, don't panic!  In my
                   1749: experience (and that of other Forthers), type errors in Forth code are
                   1750: usually easy to find (once you get used to it), the increased vigilance
                   1751: of the programmer tends to catch some harder errors in addition to most
                   1752: type errors, and you never have to work around the type system, so in
                   1753: most situations the lack of type-checking seems to be a win (projects to
                   1754: add type checking to Forth have not caught on).
                   1755: 
                   1756: 
                   1757: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
                   1758: @section Factoring
1.66      anton    1759: @cindex factoring tutorial
1.48      anton    1760: 
                   1761: If you try to write longer definitions, you will soon find it hard to
                   1762: keep track of the stack contents.  Therefore, good Forth programmers
                   1763: tend to write only short definitions (e.g., three lines).  The art of
                   1764: finding meaningful short definitions is known as factoring (as in
                   1765: factoring polynomials).
                   1766: 
                   1767: Well-factored programs offer additional advantages: smaller, more
                   1768: general words, are easier to test and debug and can be reused more and
                   1769: better than larger, specialized words.
                   1770: 
                   1771: So, if you run into difficulties with stack management, when writing
                   1772: code, try to define meaningful factors for the word, and define the word
                   1773: in terms of those.  Even if a factor contains only two words, it is
                   1774: often helpful.
                   1775: 
1.65      anton    1776: Good factoring is not easy, and it takes some practice to get the knack
                   1777: for it; but even experienced Forth programmers often don't find the
                   1778: right solution right away, but only when rewriting the program.  So, if
                   1779: you don't come up with a good solution immediately, keep trying, don't
                   1780: despair.
1.48      anton    1781: 
                   1782: @c example !!
                   1783: 
                   1784: 
                   1785: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
                   1786: @section Designing the stack effect
1.66      anton    1787: @cindex Stack effect design, tutorial
                   1788: @cindex design of stack effects, tutorial
1.48      anton    1789: 
                   1790: In other languages you can use an arbitrary order of parameters for a
1.65      anton    1791: function; and since there is only one result, you don't have to deal with
1.48      anton    1792: the order of results, either.
                   1793: 
1.117     anton    1794: In Forth (and other stack-based languages, e.g., PostScript) the
1.48      anton    1795: parameter and result order of a definition is important and should be
                   1796: designed well.  The general guideline is to design the stack effect such
                   1797: that the word is simple to use in most cases, even if that complicates
                   1798: the implementation of the word.  Some concrete rules are:
                   1799: 
                   1800: @itemize @bullet
                   1801: 
                   1802: @item
                   1803: Words consume all of their parameters (e.g., @code{.}).
                   1804: 
                   1805: @item
                   1806: If there is a convention on the order of parameters (e.g., from
                   1807: mathematics or another programming language), stick with it (e.g.,
                   1808: @code{-}).
                   1809: 
                   1810: @item
                   1811: If one parameter usually requires only a short computation (e.g., it is
                   1812: a constant), pass it on the top of the stack.  Conversely, parameters
                   1813: that usually require a long sequence of code to compute should be passed
                   1814: as the bottom (i.e., first) parameter.  This makes the code easier to
1.171     anton    1815: read, because the reader does not need to keep track of the bottom item
1.48      anton    1816: through a long sequence of code (or, alternatively, through stack
1.49      anton    1817: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48      anton    1818: address on top of the stack because it is usually simpler to compute
                   1819: than the stored value (often the address is just a variable).
                   1820: 
                   1821: @item
                   1822: Similarly, results that are usually consumed quickly should be returned
                   1823: on the top of stack, whereas a result that is often used in long
                   1824: computations should be passed as bottom result.  E.g., the file words
                   1825: like @code{open-file} return the error code on the top of stack, because
                   1826: it is usually consumed quickly by @code{throw}; moreover, the error code
                   1827: has to be checked before doing anything with the other results.
                   1828: 
                   1829: @end itemize
                   1830: 
                   1831: These rules are just general guidelines, don't lose sight of the overall
                   1832: goal to make the words easy to use.  E.g., if the convention rule
                   1833: conflicts with the computation-length rule, you might decide in favour
                   1834: of the convention if the word will be used rarely, and in favour of the
                   1835: computation-length rule if the word will be used frequently (because
                   1836: with frequent use the cost of breaking the computation-length rule would
                   1837: be quite high, and frequent use makes it easier to remember an
                   1838: unconventional order).
                   1839: 
                   1840: @c example !! structure package
                   1841: 
1.65      anton    1842: 
1.48      anton    1843: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
                   1844: @section Local Variables
1.66      anton    1845: @cindex local variables, tutorial
1.48      anton    1846: 
                   1847: You can define local variables (@emph{locals}) in a colon definition:
                   1848: 
                   1849: @example
                   1850: : swap @{ a b -- b a @}
                   1851:   b a ;
                   1852: 1 2 swap .s 2drop
                   1853: @end example
                   1854: 
                   1855: (If your Forth system does not support this syntax, include
1.187     anton    1856: @file{compat/anslocal.fs} first).
1.48      anton    1857: 
                   1858: In this example @code{@{ a b -- b a @}} is the locals definition; it
                   1859: takes two cells from the stack, puts the top of stack in @code{b} and
                   1860: the next stack element in @code{a}.  @code{--} starts a comment ending
                   1861: with @code{@}}.  After the locals definition, using the name of the
                   1862: local will push its value on the stack.  You can leave the comment
                   1863: part (@code{-- b a}) away:
                   1864: 
                   1865: @example
                   1866: : swap ( x1 x2 -- x2 x1 )
                   1867:   @{ a b @} b a ;
                   1868: @end example
                   1869: 
                   1870: In Gforth you can have several locals definitions, anywhere in a colon
                   1871: definition; in contrast, in a standard program you can have only one
                   1872: locals definition per colon definition, and that locals definition must
1.163     anton    1873: be outside any control structure.
1.48      anton    1874: 
                   1875: With locals you can write slightly longer definitions without running
                   1876: into stack trouble.  However, I recommend trying to write colon
                   1877: definitions without locals for exercise purposes to help you gain the
                   1878: essential factoring skills.
                   1879: 
1.141     anton    1880: @quotation Assignment
1.48      anton    1881: Rewrite your definitions until now with locals
1.141     anton    1882: @end quotation
1.48      anton    1883: 
1.66      anton    1884: Reference: @ref{Locals}.
                   1885: 
1.48      anton    1886: 
                   1887: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
                   1888: @section Conditional execution
1.66      anton    1889: @cindex conditionals, tutorial
                   1890: @cindex if, tutorial
1.48      anton    1891: 
                   1892: In Forth you can use control structures only inside colon definitions.
                   1893: An @code{if}-structure looks like this:
                   1894: 
                   1895: @example
                   1896: : abs ( n1 -- +n2 )
                   1897:     dup 0 < if
                   1898:         negate
                   1899:     endif ;
                   1900: 5 abs .
                   1901: -5 abs .
                   1902: @end example
                   1903: 
                   1904: @code{if} takes a flag from the stack.  If the flag is non-zero (true),
                   1905: the following code is performed, otherwise execution continues after the
1.51      pazsan   1906: @code{endif} (or @code{else}).  @code{<} compares the top two stack
1.171     anton    1907: elements and produces a flag:
1.48      anton    1908: 
                   1909: @example
                   1910: 1 2 < .
                   1911: 2 1 < .
                   1912: 1 1 < .
                   1913: @end example
                   1914: 
                   1915: Actually the standard name for @code{endif} is @code{then}.  This
                   1916: tutorial presents the examples using @code{endif}, because this is often
                   1917: less confusing for people familiar with other programming languages
                   1918: where @code{then} has a different meaning.  If your system does not have
                   1919: @code{endif}, define it with
                   1920: 
                   1921: @example
                   1922: : endif postpone then ; immediate
                   1923: @end example
                   1924: 
                   1925: You can optionally use an @code{else}-part:
                   1926: 
                   1927: @example
                   1928: : min ( n1 n2 -- n )
                   1929:   2dup < if
                   1930:     drop
                   1931:   else
                   1932:     nip
                   1933:   endif ;
                   1934: 2 3 min .
                   1935: 3 2 min .
                   1936: @end example
                   1937: 
1.141     anton    1938: @quotation Assignment
1.48      anton    1939: Write @code{min} without @code{else}-part (hint: what's the definition
                   1940: of @code{nip}?).
1.141     anton    1941: @end quotation
1.48      anton    1942: 
1.66      anton    1943: Reference: @ref{Selection}.
                   1944: 
1.48      anton    1945: 
                   1946: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
                   1947: @section Flags and Comparisons
1.66      anton    1948: @cindex flags tutorial
                   1949: @cindex comparison tutorial
1.48      anton    1950: 
                   1951: In a false-flag all bits are clear (0 when interpreted as integer).  In
                   1952: a canonical true-flag all bits are set (-1 as a twos-complement signed
                   1953: integer); in many contexts (e.g., @code{if}) any non-zero value is
                   1954: treated as true flag.
                   1955: 
                   1956: @example
                   1957: false .
                   1958: true .
                   1959: true hex u. decimal
                   1960: @end example
                   1961: 
                   1962: Comparison words produce canonical flags:
                   1963: 
                   1964: @example
                   1965: 1 1 = .
                   1966: 1 0= .
                   1967: 0 1 < .
                   1968: 0 0 < .
                   1969: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
                   1970: -1 1 < .
                   1971: @end example
                   1972: 
1.66      anton    1973: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
                   1974: (or none) and the comparisons @code{= <> < > <= >=}.  Only a part of
                   1975: these combinations are standard (for details see the standard,
                   1976: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48      anton    1977: 
1.171     anton    1978: You can use @code{and or xor invert} as operations on canonical flags.
                   1979: Actually they are bitwise operations:
1.48      anton    1980: 
                   1981: @example
                   1982: 1 2 and .
                   1983: 1 2 or .
                   1984: 1 3 xor .
                   1985: 1 invert .
                   1986: @end example
                   1987: 
                   1988: You can convert a zero/non-zero flag into a canonical flag with
                   1989: @code{0<>} (and complement it on the way with @code{0=}).
                   1990: 
                   1991: @example
                   1992: 1 0= .
                   1993: 1 0<> .
                   1994: @end example
                   1995: 
1.65      anton    1996: You can use the all-bits-set feature of canonical flags and the bitwise
1.48      anton    1997: operation of the Boolean operations to avoid @code{if}s:
                   1998: 
                   1999: @example
                   2000: : foo ( n1 -- n2 )
                   2001:   0= if
                   2002:     14
                   2003:   else
                   2004:     0
                   2005:   endif ;
                   2006: 0 foo .
                   2007: 1 foo .
                   2008: 
                   2009: : foo ( n1 -- n2 )
                   2010:   0= 14 and ;
                   2011: 0 foo .
                   2012: 1 foo .
                   2013: @end example
                   2014: 
1.141     anton    2015: @quotation Assignment
1.48      anton    2016: Write @code{min} without @code{if}.
1.141     anton    2017: @end quotation
1.48      anton    2018: 
1.66      anton    2019: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
                   2020: @ref{Bitwise operations}.
                   2021: 
1.48      anton    2022: 
                   2023: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
                   2024: @section General Loops
1.66      anton    2025: @cindex loops, indefinite, tutorial
1.48      anton    2026: 
                   2027: The endless loop is the most simple one:
                   2028: 
                   2029: @example
                   2030: : endless ( -- )
                   2031:   0 begin
                   2032:     dup . 1+
                   2033:   again ;
                   2034: endless
                   2035: @end example
                   2036: 
                   2037: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth).  @code{begin}
                   2038: does nothing at run-time, @code{again} jumps back to @code{begin}.
                   2039: 
                   2040: A loop with one exit at any place looks like this:
                   2041: 
                   2042: @example
                   2043: : log2 ( +n1 -- n2 )
                   2044: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2045:   assert( dup 0> )
                   2046:   2/ 0 begin
                   2047:     over 0> while
                   2048:       1+ swap 2/ swap
                   2049:   repeat
                   2050:   nip ;
                   2051: 7 log2 .
                   2052: 8 log2 .
                   2053: @end example
                   2054: 
                   2055: At run-time @code{while} consumes a flag; if it is 0, execution
1.51      pazsan   2056: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48      anton    2057: continues behind the @code{while}.  @code{Repeat} jumps back to
                   2058: @code{begin}, just like @code{again}.
                   2059: 
                   2060: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90      anton    2061: However, @code{2/} is not one of them; it shifts its argument right by
1.48      anton    2062: one bit (arithmetic shift right):
                   2063: 
                   2064: @example
                   2065: -5 2 / .
                   2066: -5 2/ .
                   2067: @end example
                   2068: 
                   2069: @code{assert(} is no standard word, but you can get it on systems other
1.198     anton    2070: than Gforth by including @file{compat/assert.fs}.  You can see what it
1.48      anton    2071: does by trying
                   2072: 
                   2073: @example
                   2074: 0 log2 .
                   2075: @end example
                   2076: 
                   2077: Here's a loop with an exit at the end:
                   2078: 
                   2079: @example
                   2080: : log2 ( +n1 -- n2 )
                   2081: \ logarithmus dualis of n1>0, rounded down to the next integer
                   2082:   assert( dup 0 > )
                   2083:   -1 begin
                   2084:     1+ swap 2/ swap
                   2085:     over 0 <=
                   2086:   until
                   2087:   nip ;
                   2088: @end example
                   2089: 
                   2090: @code{Until} consumes a flag; if it is non-zero, execution continues at
                   2091: the @code{begin}, otherwise after the @code{until}.
                   2092: 
1.141     anton    2093: @quotation Assignment
1.48      anton    2094: Write a definition for computing the greatest common divisor.
1.141     anton    2095: @end quotation
1.48      anton    2096: 
1.66      anton    2097: Reference: @ref{Simple Loops}.
                   2098: 
1.48      anton    2099: 
                   2100: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
                   2101: @section Counted loops
1.66      anton    2102: @cindex loops, counted, tutorial
1.48      anton    2103: 
                   2104: @example
                   2105: : ^ ( n1 u -- n )
1.171     anton    2106: \ n = the uth power of n1
1.48      anton    2107:   1 swap 0 u+do
                   2108:     over *
                   2109:   loop
                   2110:   nip ;
                   2111: 3 2 ^ .
                   2112: 4 3 ^ .
                   2113: @end example
                   2114: 
                   2115: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
                   2116: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
                   2117: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
                   2118: times (or not at all, if @code{u3-u4<0}).
                   2119: 
                   2120: You can see the stack effect design rules at work in the stack effect of
                   2121: the loop start words: Since the start value of the loop is more
                   2122: frequently constant than the end value, the start value is passed on
                   2123: the top-of-stack.
                   2124: 
                   2125: You can access the counter of a counted loop with @code{i}:
                   2126: 
                   2127: @example
                   2128: : fac ( u -- u! )
                   2129:   1 swap 1+ 1 u+do
                   2130:     i *
                   2131:   loop ;
                   2132: 5 fac .
                   2133: 7 fac .
                   2134: @end example
                   2135: 
                   2136: There is also @code{+do}, which expects signed numbers (important for
                   2137: deciding whether to enter the loop).
                   2138: 
1.141     anton    2139: @quotation Assignment
1.48      anton    2140: Write a definition for computing the nth Fibonacci number.
1.141     anton    2141: @end quotation
1.48      anton    2142: 
1.65      anton    2143: You can also use increments other than 1:
                   2144: 
                   2145: @example
                   2146: : up2 ( n1 n2 -- )
                   2147:   +do
                   2148:     i .
                   2149:   2 +loop ;
                   2150: 10 0 up2
                   2151: 
                   2152: : down2 ( n1 n2 -- )
                   2153:   -do
                   2154:     i .
                   2155:   2 -loop ;
                   2156: 0 10 down2
                   2157: @end example
1.48      anton    2158: 
1.66      anton    2159: Reference: @ref{Counted Loops}.
                   2160: 
1.48      anton    2161: 
                   2162: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
                   2163: @section Recursion
1.66      anton    2164: @cindex recursion tutorial
1.48      anton    2165: 
                   2166: Usually the name of a definition is not visible in the definition; but
                   2167: earlier definitions are usually visible:
                   2168: 
                   2169: @example
1.166     anton    2170: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48      anton    2171: : / ( n1 n2 -- n )
                   2172:   dup 0= if
                   2173:     -10 throw \ report division by zero
                   2174:   endif
                   2175:   /           \ old version
                   2176: ;
                   2177: 1 0 /
                   2178: @end example
                   2179: 
                   2180: For recursive definitions you can use @code{recursive} (non-standard) or
                   2181: @code{recurse}:
                   2182: 
                   2183: @example
                   2184: : fac1 ( n -- n! ) recursive
                   2185:  dup 0> if
                   2186:    dup 1- fac1 *
                   2187:  else
                   2188:    drop 1
                   2189:  endif ;
                   2190: 7 fac1 .
                   2191: 
                   2192: : fac2 ( n -- n! )
                   2193:  dup 0> if
                   2194:    dup 1- recurse *
                   2195:  else
                   2196:    drop 1
                   2197:  endif ;
                   2198: 8 fac2 .
                   2199: @end example
                   2200: 
1.141     anton    2201: @quotation Assignment
1.48      anton    2202: Write a recursive definition for computing the nth Fibonacci number.
1.141     anton    2203: @end quotation
1.48      anton    2204: 
1.66      anton    2205: Reference (including indirect recursion): @xref{Calls and returns}.
                   2206: 
1.48      anton    2207: 
                   2208: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
                   2209: @section Leaving definitions or loops
1.66      anton    2210: @cindex leaving definitions, tutorial
                   2211: @cindex leaving loops, tutorial
1.48      anton    2212: 
                   2213: @code{EXIT} exits the current definition right away.  For every counted
                   2214: loop that is left in this way, an @code{UNLOOP} has to be performed
                   2215: before the @code{EXIT}:
                   2216: 
                   2217: @c !! real examples
                   2218: @example
                   2219: : ...
                   2220:  ... u+do
                   2221:    ... if
                   2222:      ... unloop exit
                   2223:    endif
                   2224:    ...
                   2225:  loop
                   2226:  ... ;
                   2227: @end example
                   2228: 
                   2229: @code{LEAVE} leaves the innermost counted loop right away:
                   2230: 
                   2231: @example
                   2232: : ...
                   2233:  ... u+do
                   2234:    ... if
                   2235:      ... leave
                   2236:    endif
                   2237:    ...
                   2238:  loop
                   2239:  ... ;
                   2240: @end example
                   2241: 
1.65      anton    2242: @c !! example
1.48      anton    2243: 
1.66      anton    2244: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
                   2245: 
                   2246: 
1.48      anton    2247: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
                   2248: @section Return Stack
1.66      anton    2249: @cindex return stack tutorial
1.48      anton    2250: 
                   2251: In addition to the data stack Forth also has a second stack, the return
                   2252: stack; most Forth systems store the return addresses of procedure calls
                   2253: there (thus its name).  Programmers can also use this stack:
                   2254: 
                   2255: @example
                   2256: : foo ( n1 n2 -- )
                   2257:  .s
                   2258:  >r .s
1.50      anton    2259:  r@@ .
1.48      anton    2260:  >r .s
1.50      anton    2261:  r@@ .
1.48      anton    2262:  r> .
1.50      anton    2263:  r@@ .
1.48      anton    2264:  r> . ;
                   2265: 1 2 foo
                   2266: @end example
                   2267: 
                   2268: @code{>r} takes an element from the data stack and pushes it onto the
                   2269: return stack; conversely, @code{r>} moves an elementm from the return to
                   2270: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148     anton    2271: on the data stack.
1.48      anton    2272: 
                   2273: Forth programmers usually use the return stack for storing data
                   2274: temporarily, if using the data stack alone would be too complex, and
                   2275: factoring and locals are not an option:
                   2276: 
                   2277: @example
                   2278: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
                   2279:  rot >r rot r> ;
                   2280: @end example
                   2281: 
                   2282: The return address of the definition and the loop control parameters of
                   2283: counted loops usually reside on the return stack, so you have to take
                   2284: all items, that you have pushed on the return stack in a colon
                   2285: definition or counted loop, from the return stack before the definition
                   2286: or loop ends.  You cannot access items that you pushed on the return
                   2287: stack outside some definition or loop within the definition of loop.
                   2288: 
                   2289: If you miscount the return stack items, this usually ends in a crash:
                   2290: 
                   2291: @example
                   2292: : crash ( n -- )
                   2293:   >r ;
                   2294: 5 crash
                   2295: @end example
                   2296: 
                   2297: You cannot mix using locals and using the return stack (according to the
                   2298: standard; Gforth has no problem).  However, they solve the same
                   2299: problems, so this shouldn't be an issue.
                   2300: 
1.141     anton    2301: @quotation Assignment
1.48      anton    2302: Can you rewrite any of the definitions you wrote until now in a better
                   2303: way using the return stack?
1.141     anton    2304: @end quotation
1.48      anton    2305: 
1.66      anton    2306: Reference: @ref{Return stack}.
                   2307: 
1.48      anton    2308: 
                   2309: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
                   2310: @section Memory
1.66      anton    2311: @cindex memory access/allocation tutorial
1.48      anton    2312: 
                   2313: You can create a global variable @code{v} with
                   2314: 
                   2315: @example
                   2316: variable v ( -- addr )
                   2317: @end example
                   2318: 
                   2319: @code{v} pushes the address of a cell in memory on the stack.  This cell
                   2320: was reserved by @code{variable}.  You can use @code{!} (store) to store
                   2321: values into this cell and @code{@@} (fetch) to load the value from the
                   2322: stack into memory:
                   2323: 
                   2324: @example
                   2325: v .
                   2326: 5 v ! .s
1.50      anton    2327: v @@ .
1.48      anton    2328: @end example
                   2329: 
1.65      anton    2330: You can see a raw dump of memory with @code{dump}:
                   2331: 
                   2332: @example
                   2333: v 1 cells .s dump
                   2334: @end example
                   2335: 
                   2336: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
                   2337: generally, address units (aus)) that @code{n1 cells} occupy.  You can
                   2338: also reserve more memory:
1.48      anton    2339: 
                   2340: @example
                   2341: create v2 20 cells allot
1.65      anton    2342: v2 20 cells dump
1.48      anton    2343: @end example
                   2344: 
1.65      anton    2345: creates a word @code{v2} and reserves 20 uninitialized cells; the
                   2346: address pushed by @code{v2} points to the start of these 20 cells.  You
                   2347: can use address arithmetic to access these cells:
1.48      anton    2348: 
                   2349: @example
                   2350: 3 v2 5 cells + !
1.65      anton    2351: v2 20 cells dump
1.48      anton    2352: @end example
                   2353: 
                   2354: You can reserve and initialize memory with @code{,}:
                   2355: 
                   2356: @example
                   2357: create v3
                   2358:   5 , 4 , 3 , 2 , 1 ,
1.50      anton    2359: v3 @@ .
                   2360: v3 cell+ @@ .
                   2361: v3 2 cells + @@ .
1.65      anton    2362: v3 5 cells dump
1.48      anton    2363: @end example
                   2364: 
1.141     anton    2365: @quotation Assignment
1.48      anton    2366: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
                   2367: @code{u} cells, with the first of these cells at @code{addr}, the next
                   2368: one at @code{addr cell+} etc.
1.141     anton    2369: @end quotation
1.48      anton    2370: 
                   2371: You can also reserve memory without creating a new word:
                   2372: 
                   2373: @example
1.60      anton    2374: here 10 cells allot .
                   2375: here .
1.48      anton    2376: @end example
                   2377: 
                   2378: @code{Here} pushes the start address of the memory area.  You should
                   2379: store it somewhere, or you will have a hard time finding the memory area
                   2380: again.
                   2381: 
                   2382: @code{Allot} manages dictionary memory.  The dictionary memory contains
                   2383: the system's data structures for words etc. on Gforth and most other
                   2384: Forth systems.  It is managed like a stack: You can free the memory that
                   2385: you have just @code{allot}ed with
                   2386: 
                   2387: @example
                   2388: -10 cells allot
1.60      anton    2389: here .
1.48      anton    2390: @end example
                   2391: 
                   2392: Note that you cannot do this if you have created a new word in the
                   2393: meantime (because then your @code{allot}ed memory is no longer on the
                   2394: top of the dictionary ``stack'').
                   2395: 
                   2396: Alternatively, you can use @code{allocate} and @code{free} which allow
                   2397: freeing memory in any order:
                   2398: 
                   2399: @example
                   2400: 10 cells allocate throw .s
                   2401: 20 cells allocate throw .s
                   2402: swap
                   2403: free throw
                   2404: free throw
                   2405: @end example
                   2406: 
                   2407: The @code{throw}s deal with errors (e.g., out of memory).
                   2408: 
1.65      anton    2409: And there is also a
                   2410: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   2411: garbage collector}, which eliminates the need to @code{free} memory
                   2412: explicitly.
1.48      anton    2413: 
1.66      anton    2414: Reference: @ref{Memory}.
                   2415: 
1.48      anton    2416: 
                   2417: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
                   2418: @section Characters and Strings
1.66      anton    2419: @cindex strings tutorial
                   2420: @cindex characters tutorial
1.48      anton    2421: 
                   2422: On the stack characters take up a cell, like numbers.  In memory they
                   2423: have their own size (one 8-bit byte on most systems), and therefore
                   2424: require their own words for memory access:
                   2425: 
                   2426: @example
                   2427: create v4 
                   2428:   104 c, 97 c, 108 c, 108 c, 111 c,
1.50      anton    2429: v4 4 chars + c@@ .
1.65      anton    2430: v4 5 chars dump
1.48      anton    2431: @end example
                   2432: 
                   2433: The preferred representation of strings on the stack is @code{addr
                   2434: u-count}, where @code{addr} is the address of the first character and
                   2435: @code{u-count} is the number of characters in the string.
                   2436: 
                   2437: @example
                   2438: v4 5 type
                   2439: @end example
                   2440: 
                   2441: You get a string constant with
                   2442: 
                   2443: @example
                   2444: s" hello, world" .s
                   2445: type
                   2446: @end example
                   2447: 
                   2448: Make sure you have a space between @code{s"} and the string; @code{s"}
                   2449: is a normal Forth word and must be delimited with white space (try what
                   2450: happens when you remove the space).
                   2451: 
                   2452: However, this interpretive use of @code{s"} is quite restricted: the
                   2453: string exists only until the next call of @code{s"} (some Forth systems
                   2454: keep more than one of these strings, but usually they still have a
1.62      crook    2455: limited lifetime).
1.48      anton    2456: 
                   2457: @example
                   2458: s" hello," s" world" .s
                   2459: type
                   2460: type
                   2461: @end example
                   2462: 
1.62      crook    2463: You can also use @code{s"} in a definition, and the resulting
                   2464: strings then live forever (well, for as long as the definition):
1.48      anton    2465: 
                   2466: @example
                   2467: : foo s" hello," s" world" ;
                   2468: foo .s
                   2469: type
                   2470: type
                   2471: @end example
                   2472: 
1.141     anton    2473: @quotation Assignment
1.48      anton    2474: @code{Emit ( c -- )} types @code{c} as character (not a number).
                   2475: Implement @code{type ( addr u -- )}.
1.141     anton    2476: @end quotation
1.48      anton    2477: 
1.66      anton    2478: Reference: @ref{Memory Blocks}.
                   2479: 
                   2480: 
1.190     anton    2481: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
1.48      anton    2482: @section Alignment
1.66      anton    2483: @cindex alignment tutorial
                   2484: @cindex memory alignment tutorial
1.48      anton    2485: 
                   2486: On many processors cells have to be aligned in memory, if you want to
                   2487: access them with @code{@@} and @code{!} (and even if the processor does
1.62      crook    2488: not require alignment, access to aligned cells is faster).
1.48      anton    2489: 
                   2490: @code{Create} aligns @code{here} (i.e., the place where the next
                   2491: allocation will occur, and that the @code{create}d word points to).
                   2492: Likewise, the memory produced by @code{allocate} starts at an aligned
                   2493: address.  Adding a number of @code{cells} to an aligned address produces
                   2494: another aligned address.
                   2495: 
                   2496: However, address arithmetic involving @code{char+} and @code{chars} can
                   2497: create an address that is not cell-aligned.  @code{Aligned ( addr --
                   2498: a-addr )} produces the next aligned address:
                   2499: 
                   2500: @example
1.50      anton    2501: v3 char+ aligned .s @@ .
                   2502: v3 char+ .s @@ .
1.48      anton    2503: @end example
                   2504: 
                   2505: Similarly, @code{align} advances @code{here} to the next aligned
                   2506: address:
                   2507: 
                   2508: @example
                   2509: create v5 97 c,
                   2510: here .
                   2511: align here .
                   2512: 1000 ,
                   2513: @end example
                   2514: 
                   2515: Note that you should use aligned addresses even if your processor does
                   2516: not require them, if you want your program to be portable.
                   2517: 
1.66      anton    2518: Reference: @ref{Address arithmetic}.
                   2519: 
1.190     anton    2520: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
                   2521: @section Floating Point
                   2522: @cindex floating point tutorial
                   2523: @cindex FP tutorial
                   2524: 
                   2525: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
                   2526: might expect, but there are a few things worth noting:
                   2527: 
                   2528: The first point is not specific to Forth, but so important and yet not
                   2529: universally known that I mention it here: FP numbers are not reals.
                   2530: Many properties (e.g., arithmetic laws) that reals have and that one
                   2531: expects of all kinds of numbers do not hold for FP numbers.  If you
                   2532: want to use FP computations, you should learn about their problems and
                   2533: how to avoid them; a good starting point is @cite{David Goldberg,
                   2534: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
                   2535: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
                   2536: Computing Surveys 23(1):5@minus{}48, March 1991}.
                   2537: 
                   2538: In Forth source code literal FP numbers need an exponent, e.g.,
                   2539: @code{1e0}; this can also be written shorter as @code{1e},
                   2540: @code{+1.0e+0}, and many variations in between.  The reason for this
                   2541: is that, for historical reasons, Forth interprets a decimal point
                   2542: alone (e.g., @code{1.}) as indicating a double-cell integer.  Another
                   2543: requirement for literal FP numbers is that the current base is
                   2544: decimal; with a hex base @code{1e} is interpreted as an integer.
                   2545: 
                   2546: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
                   2547: ANS Forth system may implement the FP stack on the data stack, but
                   2548: virtually all systems implement a separate FP stack; and programming
                   2549: in a way that accommodates all models is so cumbersome that nobody
                   2550: does it.}  One advantage of this model is that cells are not in the
                   2551: way when accessing FP values, and vice versa.  Forth has a set of
                   2552: words for manipulating the FP stack: @code{fdup fswap fdrop fover
                   2553: frot} and (non-standard) @code{fnip ftuck fpick}.
                   2554: 
                   2555: FP arithmetic words are prefixed with @code{F}.  There is the usual
                   2556: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
                   2557: other functions, e.g., @code{fsqrt fsin fln fmin}.  One word that you
                   2558: might expect is @code{f=}; but @code{f=} is non-standard, because FP
                   2559: computation results are usually inaccurate, so exact comparison is
                   2560: usually a mistake, and one should use approximate comparison.
                   2561: Unfortunately, @code{f~}, the standard word for that purpose, is not
                   2562: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
                   2563: well.
                   2564: 
                   2565: And of course there are words for accessing FP numbers in memory
                   2566: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
                   2567: faligned}).  There are also variants of these words with an @code{sf}
                   2568: and @code{df} prefix for accessing IEEE format single-precision and
                   2569: double-precision numbers in memory; their main purpose is for
                   2570: accessing external FP data (e.g., that has been read from or will be
                   2571: written to a file).
                   2572: 
                   2573: Here is an example of a dot-product word and its use:
                   2574: 
                   2575: @example
                   2576: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   2577:   >r swap 2swap swap 0e r> 0 ?DO
                   2578:     dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
                   2579:   LOOP
                   2580:   2drop 2drop ;
1.48      anton    2581: 
1.190     anton    2582: create v 1.23e f, 4.56e f, 7.89e f,
                   2583: 
                   2584: v 1 floats  v 1 floats  3  v* f.
                   2585: @end example
                   2586: 
                   2587: @quotation Assignment
                   2588: Write a program to solve a quadratic equation.  Then read @cite{Henry
                   2589: G. Baker,
                   2590: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
                   2591: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
                   2592: 33(1):30@minus{}39, January 1998}, and see if you can improve your
                   2593: program.  Finally, find a test case where the original and the
                   2594: improved version produce different results.
                   2595: @end quotation
                   2596: 
                   2597: Reference: @ref{Floating Point}; @ref{Floating point stack};
                   2598: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
                   2599: arithmetic}.
                   2600: 
                   2601: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
1.84      pazsan   2602: @section Files
                   2603: @cindex files tutorial
                   2604: 
                   2605: This section gives a short introduction into how to use files inside
                   2606: Forth. It's broken up into five easy steps:
                   2607: 
                   2608: @enumerate 1
                   2609: @item Opened an ASCII text file for input
                   2610: @item Opened a file for output
                   2611: @item Read input file until string matched (or some other condition matched)
                   2612: @item Wrote some lines from input ( modified or not) to output
                   2613: @item Closed the files.
                   2614: @end enumerate
                   2615: 
1.153     anton    2616: Reference: @ref{General files}.
                   2617: 
1.84      pazsan   2618: @subsection Open file for input
                   2619: 
                   2620: @example
                   2621: s" foo.in"  r/o open-file throw Value fd-in
                   2622: @end example
                   2623: 
                   2624: @subsection Create file for output
                   2625: 
                   2626: @example
                   2627: s" foo.out" w/o create-file throw Value fd-out
                   2628: @end example
                   2629: 
                   2630: The available file modes are r/o for read-only access, r/w for
                   2631: read-write access, and w/o for write-only access. You could open both
                   2632: files with r/w, too, if you like. All file words return error codes; for
                   2633: most applications, it's best to pass there error codes with @code{throw}
                   2634: to the outer error handler.
                   2635: 
                   2636: If you want words for opening and assigning, define them as follows:
                   2637: 
                   2638: @example
                   2639: 0 Value fd-in
                   2640: 0 Value fd-out
                   2641: : open-input ( addr u -- )  r/o open-file throw to fd-in ;
                   2642: : open-output ( addr u -- )  w/o create-file throw to fd-out ;
                   2643: @end example
                   2644: 
                   2645: Usage example:
                   2646: 
                   2647: @example
                   2648: s" foo.in" open-input
                   2649: s" foo.out" open-output
                   2650: @end example
                   2651: 
                   2652: @subsection Scan file for a particular line
                   2653: 
                   2654: @example
                   2655: 256 Constant max-line
                   2656: Create line-buffer  max-line 2 + allot
                   2657: 
                   2658: : scan-file ( addr u -- )
                   2659:   begin
                   2660:       line-buffer max-line fd-in read-line throw
                   2661:   while
                   2662:          >r 2dup line-buffer r> compare 0=
                   2663:      until
                   2664:   else
                   2665:      drop
                   2666:   then
                   2667:   2drop ;
                   2668: @end example
                   2669: 
                   2670: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94      anton    2671: the buffer at addr, and returns the number of bytes read, a flag that is
                   2672: false when the end of file is reached, and an error code.
1.84      pazsan   2673: 
                   2674: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
                   2675: returns zero if both strings are equal. It returns a positive number if
                   2676: the first string is lexically greater, a negative if the second string
                   2677: is lexically greater.
                   2678: 
                   2679: We haven't seen this loop here; it has two exits. Since the @code{while}
                   2680: exits with the number of bytes read on the stack, we have to clean up
                   2681: that separately; that's after the @code{else}.
                   2682: 
                   2683: Usage example:
                   2684: 
                   2685: @example
                   2686: s" The text I search is here" scan-file
                   2687: @end example
                   2688: 
                   2689: @subsection Copy input to output
                   2690: 
                   2691: @example
                   2692: : copy-file ( -- )
                   2693:   begin
                   2694:       line-buffer max-line fd-in read-line throw
                   2695:   while
1.194     anton    2696:       line-buffer swap fd-out write-line throw
1.84      pazsan   2697:   repeat ;
                   2698: @end example
1.194     anton    2699: @c !! does not handle long lines, no newline at end of file
1.84      pazsan   2700: 
                   2701: @subsection Close files
                   2702: 
                   2703: @example
                   2704: fd-in close-file throw
                   2705: fd-out close-file throw
                   2706: @end example
                   2707: 
                   2708: Likewise, you can put that into definitions, too:
                   2709: 
                   2710: @example
                   2711: : close-input ( -- )  fd-in close-file throw ;
                   2712: : close-output ( -- )  fd-out close-file throw ;
                   2713: @end example
                   2714: 
1.141     anton    2715: @quotation Assignment
1.84      pazsan   2716: How could you modify @code{copy-file} so that it copies until a second line is
                   2717: matched? Can you write a program that extracts a section of a text file,
                   2718: given the line that starts and the line that terminates that section?
1.141     anton    2719: @end quotation
1.84      pazsan   2720: 
                   2721: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48      anton    2722: @section Interpretation and Compilation Semantics and Immediacy
1.66      anton    2723: @cindex semantics tutorial
                   2724: @cindex interpretation semantics tutorial
                   2725: @cindex compilation semantics tutorial
                   2726: @cindex immediate, tutorial
1.48      anton    2727: 
                   2728: When a word is compiled, it behaves differently from being interpreted.
                   2729: E.g., consider @code{+}:
                   2730: 
                   2731: @example
                   2732: 1 2 + .
                   2733: : foo + ;
                   2734: @end example
                   2735: 
                   2736: These two behaviours are known as compilation and interpretation
                   2737: semantics.  For normal words (e.g., @code{+}), the compilation semantics
                   2738: is to append the interpretation semantics to the currently defined word
                   2739: (@code{foo} in the example above).  I.e., when @code{foo} is executed
                   2740: later, the interpretation semantics of @code{+} (i.e., adding two
                   2741: numbers) will be performed.
                   2742: 
                   2743: However, there are words with non-default compilation semantics, e.g.,
                   2744: the control-flow words like @code{if}.  You can use @code{immediate} to
                   2745: change the compilation semantics of the last defined word to be equal to
                   2746: the interpretation semantics:
                   2747: 
                   2748: @example
                   2749: : [FOO] ( -- )
                   2750:  5 . ; immediate
                   2751: 
                   2752: [FOO]
                   2753: : bar ( -- )
                   2754:   [FOO] ;
                   2755: bar
                   2756: see bar
                   2757: @end example
                   2758: 
1.198     anton    2759: Two conventions to mark words with non-default compilation semantics are
1.48      anton    2760: names with brackets (more frequently used) and to write them all in
                   2761: upper case (less frequently used).
                   2762: 
                   2763: In Gforth (and many other systems) you can also remove the
                   2764: interpretation semantics with @code{compile-only} (the compilation
                   2765: semantics is derived from the original interpretation semantics):
                   2766: 
                   2767: @example
                   2768: : flip ( -- )
                   2769:  6 . ; compile-only \ but not immediate
                   2770: flip
                   2771: 
                   2772: : flop ( -- )
                   2773:  flip ;
                   2774: flop
                   2775: @end example
                   2776: 
                   2777: In this example the interpretation semantics of @code{flop} is equal to
                   2778: the original interpretation semantics of @code{flip}.
                   2779: 
                   2780: The text interpreter has two states: in interpret state, it performs the
                   2781: interpretation semantics of words it encounters; in compile state, it
                   2782: performs the compilation semantics of these words.
                   2783: 
                   2784: Among other things, @code{:} switches into compile state, and @code{;}
                   2785: switches back to interpret state.  They contain the factors @code{]}
                   2786: (switch to compile state) and @code{[} (switch to interpret state), that
                   2787: do nothing but switch the state.
                   2788: 
                   2789: @example
                   2790: : xxx ( -- )
                   2791:   [ 5 . ]
                   2792: ;
                   2793: 
                   2794: xxx
                   2795: see xxx
                   2796: @end example
                   2797: 
                   2798: These brackets are also the source of the naming convention mentioned
                   2799: above.
                   2800: 
1.66      anton    2801: Reference: @ref{Interpretation and Compilation Semantics}.
                   2802: 
1.48      anton    2803: 
                   2804: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
                   2805: @section Execution Tokens
1.66      anton    2806: @cindex execution tokens tutorial
                   2807: @cindex XT tutorial
1.48      anton    2808: 
                   2809: @code{' word} gives you the execution token (XT) of a word.  The XT is a
                   2810: cell representing the interpretation semantics of a word.  You can
                   2811: execute this semantics with @code{execute}:
                   2812: 
                   2813: @example
                   2814: ' + .s
                   2815: 1 2 rot execute .
                   2816: @end example
                   2817: 
                   2818: The XT is similar to a function pointer in C.  However, parameter
                   2819: passing through the stack makes it a little more flexible:
                   2820: 
                   2821: @example
                   2822: : map-array ( ... addr u xt -- ... )
1.50      anton    2823: \ executes xt ( ... x -- ... ) for every element of the array starting
                   2824: \ at addr and containing u elements
1.48      anton    2825:   @{ xt @}
                   2826:   cells over + swap ?do
1.50      anton    2827:     i @@ xt execute
1.48      anton    2828:   1 cells +loop ;
                   2829: 
                   2830: create a 3 , 4 , 2 , -1 , 4 ,
                   2831: a 5 ' . map-array .s
                   2832: 0 a 5 ' + map-array .
                   2833: s" max-n" environment? drop .s
                   2834: a 5 ' min map-array .
                   2835: @end example
                   2836: 
                   2837: You can use map-array with the XTs of words that consume one element
                   2838: more than they produce.  In theory you can also use it with other XTs,
                   2839: but the stack effect then depends on the size of the array, which is
                   2840: hard to understand.
                   2841: 
1.51      pazsan   2842: Since XTs are cell-sized, you can store them in memory and manipulate
                   2843: them on the stack like other cells.  You can also compile the XT into a
1.48      anton    2844: word with @code{compile,}:
                   2845: 
                   2846: @example
                   2847: : foo1 ( n1 n2 -- n )
                   2848:    [ ' + compile, ] ;
                   2849: see foo
                   2850: @end example
                   2851: 
                   2852: This is non-standard, because @code{compile,} has no compilation
                   2853: semantics in the standard, but it works in good Forth systems.  For the
                   2854: broken ones, use
                   2855: 
                   2856: @example
                   2857: : [compile,] compile, ; immediate
                   2858: 
                   2859: : foo1 ( n1 n2 -- n )
                   2860:    [ ' + ] [compile,] ;
                   2861: see foo
                   2862: @end example
                   2863: 
                   2864: @code{'} is a word with default compilation semantics; it parses the
                   2865: next word when its interpretation semantics are executed, not during
                   2866: compilation:
                   2867: 
                   2868: @example
                   2869: : foo ( -- xt )
                   2870:   ' ;
                   2871: see foo
                   2872: : bar ( ... "word" -- ... )
                   2873:   ' execute ;
                   2874: see bar
1.60      anton    2875: 1 2 bar + .
1.48      anton    2876: @end example
                   2877: 
                   2878: You often want to parse a word during compilation and compile its XT so
                   2879: it will be pushed on the stack at run-time.  @code{[']} does this:
                   2880: 
                   2881: @example
                   2882: : xt-+ ( -- xt )
                   2883:   ['] + ;
                   2884: see xt-+
                   2885: 1 2 xt-+ execute .
                   2886: @end example
                   2887: 
                   2888: Many programmers tend to see @code{'} and the word it parses as one
                   2889: unit, and expect it to behave like @code{[']} when compiled, and are
                   2890: confused by the actual behaviour.  If you are, just remember that the
                   2891: Forth system just takes @code{'} as one unit and has no idea that it is
                   2892: a parsing word (attempts to convenience programmers in this issue have
                   2893: usually resulted in even worse pitfalls, see
1.66      anton    2894: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
                   2895: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48      anton    2896: 
                   2897: Note that the state of the interpreter does not come into play when
1.51      pazsan   2898: creating and executing XTs.  I.e., even when you execute @code{'} in
1.48      anton    2899: compile state, it still gives you the interpretation semantics.  And
                   2900: whatever that state is, @code{execute} performs the semantics
1.66      anton    2901: represented by the XT (i.e., for XTs produced with @code{'} the
                   2902: interpretation semantics).
                   2903: 
                   2904: Reference: @ref{Tokens for Words}.
1.48      anton    2905: 
                   2906: 
                   2907: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
                   2908: @section Exceptions
1.66      anton    2909: @cindex exceptions tutorial
1.48      anton    2910: 
                   2911: @code{throw ( n -- )} causes an exception unless n is zero.
                   2912: 
                   2913: @example
                   2914: 100 throw .s
                   2915: 0 throw .s
                   2916: @end example
                   2917: 
                   2918: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
                   2919: it catches exceptions and pushes the number of the exception on the
                   2920: stack (or 0, if the xt executed without exception).  If there was an
                   2921: exception, the stacks have the same depth as when entering @code{catch}:
                   2922: 
                   2923: @example
                   2924: .s
                   2925: 3 0 ' / catch .s
                   2926: 3 2 ' / catch .s
                   2927: @end example
                   2928: 
1.141     anton    2929: @quotation Assignment
1.48      anton    2930: Try the same with @code{execute} instead of @code{catch}.
1.141     anton    2931: @end quotation
1.48      anton    2932: 
                   2933: @code{Throw} always jumps to the dynamically next enclosing
                   2934: @code{catch}, even if it has to leave several call levels to achieve
                   2935: this:
                   2936: 
                   2937: @example
                   2938: : foo 100 throw ;
                   2939: : foo1 foo ." after foo" ;
1.51      pazsan   2940: : bar ['] foo1 catch ;
1.60      anton    2941: bar .
1.48      anton    2942: @end example
                   2943: 
                   2944: It is often important to restore a value upon leaving a definition, even
                   2945: if the definition is left through an exception.  You can ensure this
                   2946: like this:
                   2947: 
                   2948: @example
                   2949: : ...
                   2950:    save-x
1.51      pazsan   2951:    ['] word-changing-x catch ( ... n )
1.48      anton    2952:    restore-x
                   2953:    ( ... n ) throw ;
                   2954: @end example
                   2955: 
1.172     anton    2956: However, this is still not safe against, e.g., the user pressing
                   2957: @kbd{Ctrl-C} when execution is between the @code{catch} and
                   2958: @code{restore-x}.
                   2959: 
                   2960: Gforth provides an alternative exception handling syntax that is safe
                   2961: against such cases: @code{try ... restore ... endtry}.  If the code
                   2962: between @code{try} and @code{endtry} has an exception, the stack
                   2963: depths are restored, the exception number is pushed on the stack, and
                   2964: the execution continues right after @code{restore}.
1.48      anton    2965: 
1.172     anton    2966: The safer equivalent to the restoration code above is
1.48      anton    2967: 
                   2968: @example
                   2969: : ...
                   2970:   save-x
                   2971:   try
1.92      anton    2972:     word-changing-x 0
1.172     anton    2973:   restore
                   2974:     restore-x
                   2975:   endtry
1.48      anton    2976:   throw ;
                   2977: @end example
                   2978: 
1.66      anton    2979: Reference: @ref{Exception Handling}.
                   2980: 
1.48      anton    2981: 
                   2982: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
                   2983: @section Defining Words
1.66      anton    2984: @cindex defining words tutorial
                   2985: @cindex does> tutorial
                   2986: @cindex create...does> tutorial
                   2987: 
                   2988: @c before semantics?
1.48      anton    2989: 
                   2990: @code{:}, @code{create}, and @code{variable} are definition words: They
                   2991: define other words.  @code{Constant} is another definition word:
                   2992: 
                   2993: @example
                   2994: 5 constant foo
                   2995: foo .
                   2996: @end example
                   2997: 
                   2998: You can also use the prefixes @code{2} (double-cell) and @code{f}
                   2999: (floating point) with @code{variable} and @code{constant}.
                   3000: 
                   3001: You can also define your own defining words.  E.g.:
                   3002: 
                   3003: @example
                   3004: : variable ( "name" -- )
                   3005:   create 0 , ;
                   3006: @end example
                   3007: 
                   3008: You can also define defining words that create words that do something
                   3009: other than just producing their address:
                   3010: 
                   3011: @example
                   3012: : constant ( n "name" -- )
                   3013:   create ,
                   3014: does> ( -- n )
1.50      anton    3015:   ( addr ) @@ ;
1.48      anton    3016: 
                   3017: 5 constant foo
                   3018: foo .
                   3019: @end example
                   3020: 
                   3021: The definition of @code{constant} above ends at the @code{does>}; i.e.,
                   3022: @code{does>} replaces @code{;}, but it also does something else: It
                   3023: changes the last defined word such that it pushes the address of the
                   3024: body of the word and then performs the code after the @code{does>}
                   3025: whenever it is called.
                   3026: 
                   3027: In the example above, @code{constant} uses @code{,} to store 5 into the
                   3028: body of @code{foo}.  When @code{foo} executes, it pushes the address of
                   3029: the body onto the stack, then (in the code after the @code{does>})
                   3030: fetches the 5 from there.
                   3031: 
                   3032: The stack comment near the @code{does>} reflects the stack effect of the
                   3033: defined word, not the stack effect of the code after the @code{does>}
                   3034: (the difference is that the code expects the address of the body that
                   3035: the stack comment does not show).
                   3036: 
                   3037: You can use these definition words to do factoring in cases that involve
                   3038: (other) definition words.  E.g., a field offset is always added to an
                   3039: address.  Instead of defining
                   3040: 
                   3041: @example
                   3042: 2 cells constant offset-field1
                   3043: @end example
                   3044: 
                   3045: and using this like
                   3046: 
                   3047: @example
                   3048: ( addr ) offset-field1 +
                   3049: @end example
                   3050: 
                   3051: you can define a definition word
                   3052: 
                   3053: @example
                   3054: : simple-field ( n "name" -- )
                   3055:   create ,
                   3056: does> ( n1 -- n1+n )
1.50      anton    3057:   ( addr ) @@ + ;
1.48      anton    3058: @end example
1.21      crook    3059: 
1.48      anton    3060: Definition and use of field offsets now look like this:
1.21      crook    3061: 
1.48      anton    3062: @example
                   3063: 2 cells simple-field field1
1.60      anton    3064: create mystruct 4 cells allot
                   3065: mystruct .s field1 .s drop
1.48      anton    3066: @end example
1.21      crook    3067: 
1.48      anton    3068: If you want to do something with the word without performing the code
                   3069: after the @code{does>}, you can access the body of a @code{create}d word
                   3070: with @code{>body ( xt -- addr )}:
1.21      crook    3071: 
1.48      anton    3072: @example
                   3073: : value ( n "name" -- )
                   3074:   create ,
                   3075: does> ( -- n1 )
1.50      anton    3076:   @@ ;
1.48      anton    3077: : to ( n "name" -- )
                   3078:   ' >body ! ;
1.21      crook    3079: 
1.48      anton    3080: 5 value foo
                   3081: foo .
                   3082: 7 to foo
                   3083: foo .
                   3084: @end example
1.21      crook    3085: 
1.141     anton    3086: @quotation Assignment
1.48      anton    3087: Define @code{defer ( "name" -- )}, which creates a word that stores an
                   3088: XT (at the start the XT of @code{abort}), and upon execution
                   3089: @code{execute}s the XT.  Define @code{is ( xt "name" -- )} that stores
                   3090: @code{xt} into @code{name}, a word defined with @code{defer}.  Indirect
                   3091: recursion is one application of @code{defer}.
1.141     anton    3092: @end quotation
1.29      crook    3093: 
1.66      anton    3094: Reference: @ref{User-defined Defining Words}.
                   3095: 
                   3096: 
1.48      anton    3097: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
                   3098: @section Arrays and Records
1.66      anton    3099: @cindex arrays tutorial
                   3100: @cindex records tutorial
                   3101: @cindex structs tutorial
1.29      crook    3102: 
1.48      anton    3103: Forth has no standard words for defining data structures such as arrays
                   3104: and records (structs in C terminology), but you can build them yourself
                   3105: based on address arithmetic.  You can also define words for defining
                   3106: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29      crook    3107: 
1.48      anton    3108: One of the first projects a Forth newcomer sets out upon when learning
                   3109: about defining words is an array defining word (possibly for
                   3110: n-dimensional arrays).  Go ahead and do it, I did it, too; you will
                   3111: learn something from it.  However, don't be disappointed when you later
                   3112: learn that you have little use for these words (inappropriate use would
1.198     anton    3113: be even worse).  I have not found a set of useful array words yet;
1.48      anton    3114: the needs are just too diverse, and named, global arrays (the result of
                   3115: naive use of defining words) are often not flexible enough (e.g.,
1.66      anton    3116: consider how to pass them as parameters).  Another such project is a set
                   3117: of words to help dealing with strings.
1.29      crook    3118: 
1.48      anton    3119: On the other hand, there is a useful set of record words, and it has
                   3120: been defined in @file{compat/struct.fs}; these words are predefined in
                   3121: Gforth.  They are explained in depth elsewhere in this manual (see
                   3122: @pxref{Structures}).  The @code{simple-field} example above is
                   3123: simplified variant of fields in this package.
1.21      crook    3124: 
                   3125: 
1.48      anton    3126: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
                   3127: @section @code{POSTPONE}
1.66      anton    3128: @cindex postpone tutorial
1.21      crook    3129: 
1.48      anton    3130: You can compile the compilation semantics (instead of compiling the
                   3131: interpretation semantics) of a word with @code{POSTPONE}:
1.21      crook    3132: 
1.48      anton    3133: @example
                   3134: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51      pazsan   3135:  POSTPONE + ; immediate
1.48      anton    3136: : foo ( n1 n2 -- n )
                   3137:  MY-+ ;
                   3138: 1 2 foo .
                   3139: see foo
                   3140: @end example
1.21      crook    3141: 
1.48      anton    3142: During the definition of @code{foo} the text interpreter performs the
                   3143: compilation semantics of @code{MY-+}, which performs the compilation
                   3144: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
                   3145: 
                   3146: This example also displays separate stack comments for the compilation
                   3147: semantics and for the stack effect of the compiled code.  For words with
                   3148: default compilation semantics these stack effects are usually not
                   3149: displayed; the stack effect of the compilation semantics is always
                   3150: @code{( -- )} for these words, the stack effect for the compiled code is
                   3151: the stack effect of the interpretation semantics.
                   3152: 
                   3153: Note that the state of the interpreter does not come into play when
                   3154: performing the compilation semantics in this way.  You can also perform
                   3155: it interpretively, e.g.:
                   3156: 
                   3157: @example
                   3158: : foo2 ( n1 n2 -- n )
                   3159:  [ MY-+ ] ;
                   3160: 1 2 foo .
                   3161: see foo
                   3162: @end example
1.21      crook    3163: 
1.48      anton    3164: However, there are some broken Forth systems where this does not always
1.62      crook    3165: work, and therefore this practice was been declared non-standard in
1.48      anton    3166: 1999.
                   3167: @c !! repair.fs
                   3168: 
                   3169: Here is another example for using @code{POSTPONE}:
1.44      crook    3170: 
1.48      anton    3171: @example
                   3172: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
                   3173:  POSTPONE negate POSTPONE + ; immediate compile-only
                   3174: : bar ( n1 n2 -- n )
                   3175:   MY-- ;
                   3176: 2 1 bar .
                   3177: see bar
                   3178: @end example
1.21      crook    3179: 
1.48      anton    3180: You can define @code{ENDIF} in this way:
1.21      crook    3181: 
1.48      anton    3182: @example
                   3183: : ENDIF ( Compilation: orig -- )
                   3184:   POSTPONE then ; immediate
                   3185: @end example
1.21      crook    3186: 
1.141     anton    3187: @quotation Assignment
1.48      anton    3188: Write @code{MY-2DUP} that has compilation semantics equivalent to
                   3189: @code{2dup}, but compiles @code{over over}.
1.141     anton    3190: @end quotation
1.29      crook    3191: 
1.66      anton    3192: @c !! @xref{Macros} for reference
                   3193: 
                   3194: 
1.48      anton    3195: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
                   3196: @section @code{Literal}
1.66      anton    3197: @cindex literal tutorial
1.29      crook    3198: 
1.48      anton    3199: You cannot @code{POSTPONE} numbers:
1.21      crook    3200: 
1.48      anton    3201: @example
                   3202: : [FOO] POSTPONE 500 ; immediate
1.21      crook    3203: @end example
                   3204: 
1.48      anton    3205: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29      crook    3206: 
1.48      anton    3207: @example
                   3208: : [FOO] ( compilation: --; run-time: -- n )
                   3209:   500 POSTPONE literal ; immediate
1.29      crook    3210: 
1.60      anton    3211: : flip [FOO] ;
1.48      anton    3212: flip .
                   3213: see flip
                   3214: @end example
1.29      crook    3215: 
1.48      anton    3216: @code{LITERAL} consumes a number at compile-time (when it's compilation
                   3217: semantics are executed) and pushes it at run-time (when the code it
                   3218: compiled is executed).  A frequent use of @code{LITERAL} is to compile a
                   3219: number computed at compile time into the current word:
1.29      crook    3220: 
1.48      anton    3221: @example
                   3222: : bar ( -- n )
                   3223:   [ 2 2 + ] literal ;
                   3224: see bar
                   3225: @end example
1.29      crook    3226: 
1.141     anton    3227: @quotation Assignment
1.48      anton    3228: Write @code{]L} which allows writing the example above as @code{: bar (
                   3229: -- n ) [ 2 2 + ]L ;}
1.141     anton    3230: @end quotation
1.48      anton    3231: 
1.66      anton    3232: @c !! @xref{Macros} for reference
                   3233: 
1.48      anton    3234: 
                   3235: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
                   3236: @section Advanced macros
1.66      anton    3237: @cindex macros, advanced tutorial
                   3238: @cindex run-time code generation, tutorial
1.48      anton    3239: 
1.66      anton    3240: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
                   3241: Execution Tokens}.  It frequently performs @code{execute}, a relatively
                   3242: expensive operation in some Forth implementations.  You can use
1.48      anton    3243: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
                   3244: and produce a word that contains the word to be performed directly:
                   3245: 
                   3246: @c use ]] ... [[
                   3247: @example
                   3248: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
                   3249: \ at run-time, execute xt ( ... x -- ... ) for each element of the
                   3250: \ array beginning at addr and containing u elements
                   3251:   @{ xt @}
                   3252:   POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50      anton    3253:     POSTPONE i POSTPONE @@ xt compile,
1.48      anton    3254:   1 cells POSTPONE literal POSTPONE +loop ;
                   3255: 
                   3256: : sum-array ( addr u -- n )
                   3257:  0 rot rot [ ' + compile-map-array ] ;
                   3258: see sum-array
                   3259: a 5 sum-array .
                   3260: @end example
                   3261: 
                   3262: You can use the full power of Forth for generating the code; here's an
                   3263: example where the code is generated in a loop:
                   3264: 
                   3265: @example
                   3266: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
                   3267: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50      anton    3268:   POSTPONE tuck POSTPONE @@
1.48      anton    3269:   POSTPONE literal POSTPONE * POSTPONE +
                   3270:   POSTPONE swap POSTPONE cell+ ;
                   3271: 
                   3272: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51      pazsan   3273: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48      anton    3274:   0 postpone literal postpone swap
                   3275:   [ ' compile-vmul-step compile-map-array ]
                   3276:   postpone drop ;
                   3277: see compile-vmul
                   3278: 
                   3279: : a-vmul ( addr -- n )
1.51      pazsan   3280: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48      anton    3281:  [ a 5 compile-vmul ] ;
                   3282: see a-vmul
                   3283: a a-vmul .
                   3284: @end example
                   3285: 
                   3286: This example uses @code{compile-map-array} to show off, but you could
1.66      anton    3287: also use @code{map-array} instead (try it now!).
1.48      anton    3288: 
                   3289: You can use this technique for efficient multiplication of large
                   3290: matrices.  In matrix multiplication, you multiply every line of one
                   3291: matrix with every column of the other matrix.  You can generate the code
                   3292: for one line once, and use it for every column.  The only downside of
                   3293: this technique is that it is cumbersome to recover the memory consumed
                   3294: by the generated code when you are done (and in more complicated cases
                   3295: it is not possible portably).
                   3296: 
1.66      anton    3297: @c !! @xref{Macros} for reference
                   3298: 
                   3299: 
1.48      anton    3300: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
                   3301: @section Compilation Tokens
1.66      anton    3302: @cindex compilation tokens, tutorial
                   3303: @cindex CT, tutorial
1.48      anton    3304: 
                   3305: This section is Gforth-specific.  You can skip it.
                   3306: 
                   3307: @code{' word compile,} compiles the interpretation semantics.  For words
                   3308: with default compilation semantics this is the same as performing the
                   3309: compilation semantics.  To represent the compilation semantics of other
                   3310: words (e.g., words like @code{if} that have no interpretation
                   3311: semantics), Gforth has the concept of a compilation token (CT,
                   3312: consisting of two cells), and words @code{comp'} and @code{[comp']}.
                   3313: You can perform the compilation semantics represented by a CT with
                   3314: @code{execute}:
1.29      crook    3315: 
1.48      anton    3316: @example
                   3317: : foo2 ( n1 n2 -- n )
                   3318:    [ comp' + execute ] ;
                   3319: see foo
                   3320: @end example
1.29      crook    3321: 
1.48      anton    3322: You can compile the compilation semantics represented by a CT with
                   3323: @code{postpone,}:
1.30      anton    3324: 
1.48      anton    3325: @example
                   3326: : foo3 ( -- )
                   3327:   [ comp' + postpone, ] ;
                   3328: see foo3
                   3329: @end example
1.30      anton    3330: 
1.51      pazsan   3331: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48      anton    3332: @code{comp'} is particularly useful for words that have no
                   3333: interpretation semantics:
1.29      crook    3334: 
1.30      anton    3335: @example
1.48      anton    3336: ' if
1.60      anton    3337: comp' if .s 2drop
1.30      anton    3338: @end example
                   3339: 
1.66      anton    3340: Reference: @ref{Tokens for Words}.
                   3341: 
1.29      crook    3342: 
1.48      anton    3343: @node Wordlists and Search Order Tutorial,  , Compilation Tokens Tutorial, Tutorial
                   3344: @section Wordlists and Search Order
1.66      anton    3345: @cindex wordlists tutorial
                   3346: @cindex search order, tutorial
1.48      anton    3347: 
                   3348: The dictionary is not just a memory area that allows you to allocate
                   3349: memory with @code{allot}, it also contains the Forth words, arranged in
                   3350: several wordlists.  When searching for a word in a wordlist,
                   3351: conceptually you start searching at the youngest and proceed towards
                   3352: older words (in reality most systems nowadays use hash-tables); i.e., if
                   3353: you define a word with the same name as an older word, the new word
                   3354: shadows the older word.
                   3355: 
                   3356: Which wordlists are searched in which order is determined by the search
                   3357: order.  You can display the search order with @code{order}.  It displays
                   3358: first the search order, starting with the wordlist searched first, then
                   3359: it displays the wordlist that will contain newly defined words.
1.21      crook    3360: 
1.48      anton    3361: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21      crook    3362: 
1.48      anton    3363: @example
                   3364: wordlist constant mywords
                   3365: @end example
1.21      crook    3366: 
1.48      anton    3367: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
                   3368: defined words (the @emph{current} wordlist):
1.21      crook    3369: 
1.48      anton    3370: @example
                   3371: mywords set-current
                   3372: order
                   3373: @end example
1.26      crook    3374: 
1.48      anton    3375: Gforth does not display a name for the wordlist in @code{mywords}
                   3376: because this wordlist was created anonymously with @code{wordlist}.
1.21      crook    3377: 
1.48      anton    3378: You can get the current wordlist with @code{get-current ( -- wid)}.  If
                   3379: you want to put something into a specific wordlist without overall
                   3380: effect on the current wordlist, this typically looks like this:
1.21      crook    3381: 
1.48      anton    3382: @example
                   3383: get-current mywords set-current ( wid )
                   3384: create someword
                   3385: ( wid ) set-current
                   3386: @end example
1.21      crook    3387: 
1.48      anton    3388: You can write the search order with @code{set-order ( wid1 .. widn n --
                   3389: )} and read it with @code{get-order ( -- wid1 .. widn n )}.  The first
                   3390: searched wordlist is topmost.
1.21      crook    3391: 
1.48      anton    3392: @example
                   3393: get-order mywords swap 1+ set-order
                   3394: order
                   3395: @end example
1.21      crook    3396: 
1.48      anton    3397: Yes, the order of wordlists in the output of @code{order} is reversed
                   3398: from stack comments and the output of @code{.s} and thus unintuitive.
1.21      crook    3399: 
1.141     anton    3400: @quotation Assignment
1.48      anton    3401: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
                   3402: wordlist to the search order.  Define @code{previous ( -- )}, which
                   3403: removes the first searched wordlist from the search order.  Experiment
                   3404: with boundary conditions (you will see some crashes or situations that
                   3405: are hard or impossible to leave).
1.141     anton    3406: @end quotation
1.21      crook    3407: 
1.48      anton    3408: The search order is a powerful foundation for providing features similar
                   3409: to Modula-2 modules and C++ namespaces.  However, trying to modularize
                   3410: programs in this way has disadvantages for debugging and reuse/factoring
                   3411: that overcome the advantages in my experience (I don't do huge projects,
1.55      anton    3412: though).  These disadvantages are not so clear in other
1.82      anton    3413: languages/programming environments, because these languages are not so
1.48      anton    3414: strong in debugging and reuse.
1.21      crook    3415: 
1.66      anton    3416: @c !! example
                   3417: 
                   3418: Reference: @ref{Word Lists}.
1.21      crook    3419: 
1.29      crook    3420: @c ******************************************************************
1.48      anton    3421: @node Introduction, Words, Tutorial, Top
1.29      crook    3422: @comment node-name,     next,           previous, up
                   3423: @chapter An Introduction to ANS Forth
                   3424: @cindex Forth - an introduction
1.21      crook    3425: 
1.83      anton    3426: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
                   3427: that it is slower-paced in its examples, but uses them to dive deep into
                   3428: explaining Forth internals (not covered by the Tutorial).  Apart from
                   3429: that, this chapter covers far less material.  It is suitable for reading
                   3430: without using a computer.
                   3431: 
1.29      crook    3432: The primary purpose of this manual is to document Gforth. However, since
                   3433: Forth is not a widely-known language and there is a lack of up-to-date
                   3434: teaching material, it seems worthwhile to provide some introductory
1.49      anton    3435: material.  For other sources of Forth-related
                   3436: information, see @ref{Forth-related information}.
1.21      crook    3437: 
1.29      crook    3438: The examples in this section should work on any ANS Forth; the
                   3439: output shown was produced using Gforth. Each example attempts to
                   3440: reproduce the exact output that Gforth produces. If you try out the
                   3441: examples (and you should), what you should type is shown @kbd{like this}
                   3442: and Gforth's response is shown @code{like this}. The single exception is
1.30      anton    3443: that, where the example shows @key{RET} it means that you should
1.29      crook    3444: press the ``carriage return'' key. Unfortunately, some output formats for
                   3445: this manual cannot show the difference between @kbd{this} and
                   3446: @code{this} which will make trying out the examples harder (but not
                   3447: impossible).
1.21      crook    3448: 
1.29      crook    3449: Forth is an unusual language. It provides an interactive development
                   3450: environment which includes both an interpreter and compiler. Forth
                   3451: programming style encourages you to break a problem down into many
                   3452: @cindex factoring
                   3453: small fragments (@dfn{factoring}), and then to develop and test each
                   3454: fragment interactively. Forth advocates assert that breaking the
                   3455: edit-compile-test cycle used by conventional programming languages can
                   3456: lead to great productivity improvements.
1.21      crook    3457: 
1.29      crook    3458: @menu
1.67      anton    3459: * Introducing the Text Interpreter::  
                   3460: * Stacks and Postfix notation::  
                   3461: * Your first definition::       
                   3462: * How does that work?::         
                   3463: * Forth is written in Forth::   
                   3464: * Review - elements of a Forth system::  
                   3465: * Where to go next::            
                   3466: * Exercises::                   
1.29      crook    3467: @end menu
1.21      crook    3468: 
1.29      crook    3469: @comment ----------------------------------------------
                   3470: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
                   3471: @section Introducing the Text Interpreter
                   3472: @cindex text interpreter
                   3473: @cindex outer interpreter
1.21      crook    3474: 
1.30      anton    3475: @c IMO this is too detailed and the pace is too slow for
                   3476: @c an introduction.  If you know German, take a look at
                   3477: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html 
                   3478: @c to see how I do it - anton 
                   3479: 
1.44      crook    3480: @c nac-> Where I have accepted your comments 100% and modified the text
                   3481: @c accordingly, I have deleted your comments. Elsewhere I have added a
                   3482: @c response like this to attempt to rationalise what I have done. Of
                   3483: @c course, this is a very clumsy mechanism for something that would be
                   3484: @c done far more efficiently over a beer. Please delete any dialogue
                   3485: @c you consider closed.
                   3486: 
1.29      crook    3487: When you invoke the Forth image, you will see a startup banner printed
                   3488: and nothing else (if you have Gforth installed on your system, try
1.30      anton    3489: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29      crook    3490: its command line interpreter, which is called the @dfn{Text Interpreter}
                   3491: (also known as the @dfn{Outer Interpreter}).  (You will learn a lot
1.49      anton    3492: about the text interpreter as you read through this chapter, for more
                   3493: detail @pxref{The Text Interpreter}).
1.21      crook    3494: 
1.29      crook    3495: Although it's not obvious, Forth is actually waiting for your
1.30      anton    3496: input. Type a number and press the @key{RET} key:
1.21      crook    3497: 
1.26      crook    3498: @example
1.30      anton    3499: @kbd{45@key{RET}}  ok
1.26      crook    3500: @end example
1.21      crook    3501: 
1.29      crook    3502: Rather than give you a prompt to invite you to input something, the text
                   3503: interpreter prints a status message @i{after} it has processed a line
                   3504: of input. The status message in this case (``@code{ ok}'' followed by
                   3505: carriage-return) indicates that the text interpreter was able to process
                   3506: all of your input successfully. Now type something illegal:
                   3507: 
                   3508: @example
1.30      anton    3509: @kbd{qwer341@key{RET}}
1.134     anton    3510: *the terminal*:2: Undefined word
                   3511: >>>qwer341<<<
                   3512: Backtrace:
                   3513: $2A95B42A20 throw 
                   3514: $2A95B57FB8 no.extensions 
1.29      crook    3515: @end example
1.23      crook    3516: 
1.134     anton    3517: The exact text, other than the ``Undefined word'' may differ slightly
                   3518: on your system, but the effect is the same; when the text interpreter
1.29      crook    3519: detects an error, it discards any remaining text on a line, resets
1.134     anton    3520: certain internal state and prints an error message. For a detailed
                   3521: description of error messages see @ref{Error messages}.
1.23      crook    3522: 
1.29      crook    3523: The text interpreter waits for you to press carriage-return, and then
                   3524: processes your input line. Starting at the beginning of the line, it
                   3525: breaks the line into groups of characters separated by spaces. For each
                   3526: group of characters in turn, it makes two attempts to do something:
1.23      crook    3527: 
1.29      crook    3528: @itemize @bullet
                   3529: @item
1.44      crook    3530: @cindex name dictionary
1.29      crook    3531: It tries to treat it as a command. It does this by searching a @dfn{name
                   3532: dictionary}. If the group of characters matches an entry in the name
                   3533: dictionary, the name dictionary provides the text interpreter with
                   3534: information that allows the text interpreter perform some actions. In
                   3535: Forth jargon, we say that the group
                   3536: @cindex word
                   3537: @cindex definition
                   3538: @cindex execution token
                   3539: @cindex xt
                   3540: of characters names a @dfn{word}, that the dictionary search returns an
                   3541: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
                   3542: word, and that the text interpreter executes the xt. Often, the terms
                   3543: @dfn{word} and @dfn{definition} are used interchangeably.
                   3544: @item
                   3545: If the text interpreter fails to find a match in the name dictionary, it
                   3546: tries to treat the group of characters as a number in the current number
                   3547: base (when you start up Forth, the current number base is base 10). If
                   3548: the group of characters legitimately represents a number, the text
                   3549: interpreter pushes the number onto a stack (we'll learn more about that
                   3550: in the next section).
                   3551: @end itemize
1.23      crook    3552: 
1.29      crook    3553: If the text interpreter is unable to do either of these things with any
                   3554: group of characters, it discards the group of characters and the rest of
                   3555: the line, then prints an error message. If the text interpreter reaches
                   3556: the end of the line without error, it prints the status message ``@code{ ok}''
                   3557: followed by carriage-return.
1.21      crook    3558: 
1.29      crook    3559: This is the simplest command we can give to the text interpreter:
1.23      crook    3560: 
                   3561: @example
1.30      anton    3562: @key{RET}  ok
1.23      crook    3563: @end example
1.21      crook    3564: 
1.29      crook    3565: The text interpreter did everything we asked it to do (nothing) without
                   3566: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
                   3567: command:
1.21      crook    3568: 
1.23      crook    3569: @example
1.30      anton    3570: @kbd{12 dup fred dup@key{RET}}
1.134     anton    3571: *the terminal*:3: Undefined word
                   3572: 12 dup >>>fred<<< dup
                   3573: Backtrace:
                   3574: $2A95B42A20 throw 
                   3575: $2A95B57FB8 no.extensions 
1.23      crook    3576: @end example
1.21      crook    3577: 
1.29      crook    3578: When you press the carriage-return key, the text interpreter starts to
                   3579: work its way along the line:
1.21      crook    3580: 
1.29      crook    3581: @itemize @bullet
                   3582: @item
                   3583: When it gets to the space after the @code{2}, it takes the group of
                   3584: characters @code{12} and looks them up in the name
                   3585: dictionary@footnote{We can't tell if it found them or not, but assume
                   3586: for now that it did not}. There is no match for this group of characters
                   3587: in the name dictionary, so it tries to treat them as a number. It is
                   3588: able to do this successfully, so it puts the number, 12, ``on the stack''
                   3589: (whatever that means).
                   3590: @item
                   3591: The text interpreter resumes scanning the line and gets the next group
                   3592: of characters, @code{dup}. It looks it up in the name dictionary and
                   3593: (you'll have to take my word for this) finds it, and executes the word
                   3594: @code{dup} (whatever that means).
                   3595: @item
                   3596: Once again, the text interpreter resumes scanning the line and gets the
                   3597: group of characters @code{fred}. It looks them up in the name
                   3598: dictionary, but can't find them. It tries to treat them as a number, but
                   3599: they don't represent any legal number.
                   3600: @end itemize
1.21      crook    3601: 
1.29      crook    3602: At this point, the text interpreter gives up and prints an error
                   3603: message. The error message shows exactly how far the text interpreter
                   3604: got in processing the line. In particular, it shows that the text
                   3605: interpreter made no attempt to do anything with the final character
                   3606: group, @code{dup}, even though we have good reason to believe that the
                   3607: text interpreter would have no problem looking that word up and
                   3608: executing it a second time.
1.21      crook    3609: 
                   3610: 
1.29      crook    3611: @comment ----------------------------------------------
                   3612: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
                   3613: @section Stacks, postfix notation and parameter passing
                   3614: @cindex text interpreter
                   3615: @cindex outer interpreter
1.21      crook    3616: 
1.29      crook    3617: In procedural programming languages (like C and Pascal), the
                   3618: building-block of programs is the @dfn{function} or @dfn{procedure}. These
                   3619: functions or procedures are called with @dfn{explicit parameters}. For
                   3620: example, in C we might write:
1.21      crook    3621: 
1.23      crook    3622: @example
1.29      crook    3623: total = total + new_volume(length,height,depth);
1.23      crook    3624: @end example
1.21      crook    3625: 
1.23      crook    3626: @noindent
1.29      crook    3627: where new_volume is a function-call to another piece of code, and total,
                   3628: length, height and depth are all variables. length, height and depth are
                   3629: parameters to the function-call.
1.21      crook    3630: 
1.29      crook    3631: In Forth, the equivalent of the function or procedure is the
                   3632: @dfn{definition} and parameters are implicitly passed between
                   3633: definitions using a shared stack that is visible to the
                   3634: programmer. Although Forth does support variables, the existence of the
                   3635: stack means that they are used far less often than in most other
                   3636: programming languages. When the text interpreter encounters a number, it
                   3637: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30      anton    3638: actual number is implementation-dependent ...) and the particular stack
1.29      crook    3639: used for any operation is implied unambiguously by the operation being
                   3640: performed. The stack used for all integer operations is called the @dfn{data
                   3641: stack} and, since this is the stack used most commonly, references to
                   3642: ``the data stack'' are often abbreviated to ``the stack''.
1.21      crook    3643: 
1.29      crook    3644: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21      crook    3645: 
1.23      crook    3646: @example
1.30      anton    3647: @kbd{1 2 3@key{RET}}  ok
1.23      crook    3648: @end example
1.21      crook    3649: 
1.29      crook    3650: Then this instructs the text interpreter to placed three numbers on the
                   3651: (data) stack. An analogy for the behaviour of the stack is to take a
                   3652: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
                   3653: the table. The 3 was the last card onto the pile (``last-in'') and if
                   3654: you take a card off the pile then, unless you're prepared to fiddle a
                   3655: bit, the card that you take off will be the 3 (``first-out''). The
                   3656: number that will be first-out of the stack is called the @dfn{top of
                   3657: stack}, which
                   3658: @cindex TOS definition
                   3659: is often abbreviated to @dfn{TOS}.
1.21      crook    3660: 
1.29      crook    3661: To understand how parameters are passed in Forth, consider the
                   3662: behaviour of the definition @code{+} (pronounced ``plus''). You will not
                   3663: be surprised to learn that this definition performs addition. More
                   3664: precisely, it adds two number together and produces a result. Where does
                   3665: it get the two numbers from? It takes the top two numbers off the
                   3666: stack. Where does it place the result? On the stack. You can act-out the
                   3667: behaviour of @code{+} with your playing cards like this:
1.21      crook    3668: 
                   3669: @itemize @bullet
                   3670: @item
1.29      crook    3671: Pick up two cards from the stack on the table
1.21      crook    3672: @item
1.29      crook    3673: Stare at them intently and ask yourself ``what @i{is} the sum of these two
                   3674: numbers''
1.21      crook    3675: @item
1.29      crook    3676: Decide that the answer is 5
1.21      crook    3677: @item
1.29      crook    3678: Shuffle the two cards back into the pack and find a 5
1.21      crook    3679: @item
1.29      crook    3680: Put a 5 on the remaining ace that's on the table.
1.21      crook    3681: @end itemize
                   3682: 
1.29      crook    3683: If you don't have a pack of cards handy but you do have Forth running,
                   3684: you can use the definition @code{.s} to show the current state of the stack,
                   3685: without affecting the stack. Type:
1.21      crook    3686: 
                   3687: @example
1.124     anton    3688: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30      anton    3689: @kbd{.s@key{RET}} <3> 1 2 3  ok
1.23      crook    3690: @end example
                   3691: 
1.124     anton    3692: The text interpreter looks up the word @code{clearstacks} and executes
                   3693: it; it tidies up the stacks and removes any entries that may have been
1.29      crook    3694: left on it by earlier examples. The text interpreter pushes each of the
                   3695: three numbers in turn onto the stack. Finally, the text interpreter
                   3696: looks up the word @code{.s} and executes it. The effect of executing
                   3697: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
                   3698: followed by a list of all the items on the stack; the item on the far
                   3699: right-hand side is the TOS.
1.21      crook    3700: 
1.29      crook    3701: You can now type:
1.21      crook    3702: 
1.29      crook    3703: @example
1.30      anton    3704: @kbd{+ .s@key{RET}} <2> 1 5  ok
1.29      crook    3705: @end example
1.21      crook    3706: 
1.29      crook    3707: @noindent
                   3708: which is correct; there are now 2 items on the stack and the result of
                   3709: the addition is 5.
1.23      crook    3710: 
1.29      crook    3711: If you're playing with cards, try doing a second addition: pick up the
                   3712: two cards, work out that their sum is 6, shuffle them into the pack,
                   3713: look for a 6 and place that on the table. You now have just one item on
                   3714: the stack. What happens if you try to do a third addition? Pick up the
                   3715: first card, pick up the second card -- ah! There is no second card. This
                   3716: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95      anton    3717: do the same thing with Forth it often reports an error (probably a Stack
1.29      crook    3718: Underflow or an Invalid Memory Address error).
1.23      crook    3719: 
1.29      crook    3720: The opposite situation to a stack underflow is a @dfn{stack overflow},
                   3721: which simply accepts that there is a finite amount of storage space
                   3722: reserved for the stack. To stretch the playing card analogy, if you had
                   3723: enough packs of cards and you piled the cards up on the table, you would
                   3724: eventually be unable to add another card; you'd hit the ceiling. Gforth
                   3725: allows you to set the maximum size of the stacks. In general, the only
                   3726: time that you will get a stack overflow is because a definition has a
                   3727: bug in it and is generating data on the stack uncontrollably.
1.23      crook    3728: 
1.29      crook    3729: There's one final use for the playing card analogy. If you model your
                   3730: stack using a pack of playing cards, the maximum number of items on
                   3731: your stack will be 52 (I assume you didn't use the Joker). The maximum
                   3732: @i{value} of any item on the stack is 13 (the King). In fact, the only
                   3733: possible numbers are positive integer numbers 1 through 13; you can't
                   3734: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
                   3735: think about some of the cards, you can accommodate different
                   3736: numbers. For example, you could think of the Jack as representing 0,
                   3737: the Queen as representing -1 and the King as representing -2. Your
1.45      crook    3738: @i{range} remains unchanged (you can still only represent a total of 13
1.29      crook    3739: numbers) but the numbers that you can represent are -2 through 10.
1.28      crook    3740: 
1.29      crook    3741: In that analogy, the limit was the amount of information that a single
                   3742: stack entry could hold, and Forth has a similar limit. In Forth, the
                   3743: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
                   3744: implementation dependent and affects the maximum value that a stack
                   3745: entry can hold. A Standard Forth provides a cell size of at least
                   3746: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21      crook    3747: 
1.29      crook    3748: Forth does not do any type checking for you, so you are free to
                   3749: manipulate and combine stack items in any way you wish. A convenient way
                   3750: of treating stack items is as 2's complement signed integers, and that
                   3751: is what Standard words like @code{+} do. Therefore you can type:
1.21      crook    3752: 
1.29      crook    3753: @example
1.30      anton    3754: @kbd{-5 12 + .s@key{RET}} <1> 7  ok
1.29      crook    3755: @end example
1.21      crook    3756: 
1.29      crook    3757: If you use numbers and definitions like @code{+} in order to turn Forth
                   3758: into a great big pocket calculator, you will realise that it's rather
                   3759: different from a normal calculator. Rather than typing 2 + 3 = you had
                   3760: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
                   3761: result). The terminology used to describe this difference is to say that
                   3762: your calculator uses @dfn{Infix Notation} (parameters and operators are
                   3763: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
                   3764: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21      crook    3765: 
1.29      crook    3766: Whilst postfix notation might look confusing to begin with, it has
                   3767: several important advantages:
1.21      crook    3768: 
1.23      crook    3769: @itemize @bullet
                   3770: @item
1.29      crook    3771: it is unambiguous
1.23      crook    3772: @item
1.29      crook    3773: it is more concise
1.23      crook    3774: @item
1.29      crook    3775: it fits naturally with a stack-based system
1.23      crook    3776: @end itemize
1.21      crook    3777: 
1.29      crook    3778: To examine these claims in more detail, consider these sums:
1.21      crook    3779: 
1.29      crook    3780: @example
                   3781: 6 + 5 * 4 =
                   3782: 4 * 5 + 6 =
                   3783: @end example
1.21      crook    3784: 
1.29      crook    3785: If you're just learning maths or your maths is very rusty, you will
                   3786: probably come up with the answer 44 for the first and 26 for the
                   3787: second. If you are a bit of a whizz at maths you will remember the
                   3788: @i{convention} that multiplication takes precendence over addition, and
                   3789: you'd come up with the answer 26 both times. To explain the answer 26
                   3790: to someone who got the answer 44, you'd probably rewrite the first sum
                   3791: like this:
1.21      crook    3792: 
1.29      crook    3793: @example
                   3794: 6 + (5 * 4) =
                   3795: @end example
1.21      crook    3796: 
1.29      crook    3797: If what you really wanted was to perform the addition before the
                   3798: multiplication, you would have to use parentheses to force it.
1.21      crook    3799: 
1.29      crook    3800: If you did the first two sums on a pocket calculator you would probably
                   3801: get the right answers, unless you were very cautious and entered them using
                   3802: these keystroke sequences:
1.21      crook    3803: 
1.29      crook    3804: 6 + 5 = * 4 =
                   3805: 4 * 5 = + 6 =
1.21      crook    3806: 
1.29      crook    3807: Postfix notation is unambiguous because the order that the operators
                   3808: are applied is always explicit; that also means that parentheses are
                   3809: never required. The operators are @i{active} (the act of quoting the
                   3810: operator makes the operation occur) which removes the need for ``=''.
1.28      crook    3811: 
1.29      crook    3812: The sum 6 + 5 * 4 can be written (in postfix notation) in two
                   3813: equivalent ways:
1.26      crook    3814: 
                   3815: @example
1.29      crook    3816: 6 5 4 * +      or:
                   3817: 5 4 * 6 +
1.26      crook    3818: @end example
1.23      crook    3819: 
1.29      crook    3820: An important thing that you should notice about this notation is that
                   3821: the @i{order} of the numbers does not change; if you want to subtract
                   3822: 2 from 10 you type @code{10 2 -}.
1.1       anton    3823: 
1.29      crook    3824: The reason that Forth uses postfix notation is very simple to explain: it
                   3825: makes the implementation extremely simple, and it follows naturally from
                   3826: using the stack as a mechanism for passing parameters. Another way of
                   3827: thinking about this is to realise that all Forth definitions are
                   3828: @i{active}; they execute as they are encountered by the text
                   3829: interpreter. The result of this is that the syntax of Forth is trivially
                   3830: simple.
1.1       anton    3831: 
                   3832: 
                   3833: 
1.29      crook    3834: @comment ----------------------------------------------
                   3835: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
                   3836: @section Your first Forth definition
                   3837: @cindex first definition
1.1       anton    3838: 
1.29      crook    3839: Until now, the examples we've seen have been trivial; we've just been
                   3840: using Forth as a bigger-than-pocket calculator. Also, each calculation
                   3841: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
                   3842: again@footnote{That's not quite true. If you press the up-arrow key on
                   3843: your keyboard you should be able to scroll back to any earlier command,
                   3844: edit it and re-enter it.} In this section we'll see how to add new
                   3845: words to Forth's vocabulary.
1.1       anton    3846: 
1.29      crook    3847: The easiest way to create a new word is to use a @dfn{colon
                   3848: definition}. We'll define a few and try them out before worrying too
                   3849: much about how they work. Try typing in these examples; be careful to
                   3850: copy the spaces accurately:
1.1       anton    3851: 
1.29      crook    3852: @example
                   3853: : add-two 2 + . ;
                   3854: : greet ." Hello and welcome" ;
                   3855: : demo 5 add-two ;
                   3856: @end example
1.1       anton    3857: 
1.29      crook    3858: @noindent
                   3859: Now try them out:
1.1       anton    3860: 
1.29      crook    3861: @example
1.30      anton    3862: @kbd{greet@key{RET}} Hello and welcome  ok
                   3863: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome  ok
                   3864: @kbd{4 add-two@key{RET}} 6  ok
                   3865: @kbd{demo@key{RET}} 7  ok
                   3866: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11  ok
1.29      crook    3867: @end example
1.1       anton    3868: 
1.29      crook    3869: The first new thing that we've introduced here is the pair of words
                   3870: @code{:} and @code{;}. These are used to start and terminate a new
                   3871: definition, respectively. The first word after the @code{:} is the name
                   3872: for the new definition.
1.1       anton    3873: 
1.29      crook    3874: As you can see from the examples, a definition is built up of words that
                   3875: have already been defined; Forth makes no distinction between
                   3876: definitions that existed when you started the system up, and those that
                   3877: you define yourself.
1.1       anton    3878: 
1.29      crook    3879: The examples also introduce the words @code{.} (dot), @code{."}
                   3880: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
                   3881: the stack and displays it. It's like @code{.s} except that it only
                   3882: displays the top item of the stack and it is destructive; after it has
                   3883: executed, the number is no longer on the stack. There is always one
                   3884: space printed after the number, and no spaces before it. Dot-quote
                   3885: defines a string (a sequence of characters) that will be printed when
                   3886: the word is executed. The string can contain any printable characters
                   3887: except @code{"}. A @code{"} has a special function; it is not a Forth
                   3888: word but it acts as a delimiter (the way that delimiters work is
                   3889: described in the next section). Finally, @code{dup} duplicates the value
                   3890: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1       anton    3891: 
1.29      crook    3892: We already know that the text interpreter searches through the
                   3893: dictionary to locate names. If you've followed the examples earlier, you
                   3894: will already have a definition called @code{add-two}. Lets try modifying
                   3895: it by typing in a new definition:
1.1       anton    3896: 
1.29      crook    3897: @example
1.30      anton    3898: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two  ok
1.29      crook    3899: @end example
1.5       anton    3900: 
1.29      crook    3901: Forth recognised that we were defining a word that already exists, and
                   3902: printed a message to warn us of that fact. Let's try out the new
                   3903: definition:
1.5       anton    3904: 
1.29      crook    3905: @example
1.30      anton    3906: @kbd{9 add-two@key{RET}} 9 + 2 =11  ok
1.29      crook    3907: @end example
1.1       anton    3908: 
1.29      crook    3909: @noindent
                   3910: All that we've actually done here, though, is to create a new
                   3911: definition, with a particular name. The fact that there was already a
                   3912: definition with the same name did not make any difference to the way
                   3913: that the new definition was created (except that Forth printed a warning
                   3914: message). The old definition of add-two still exists (try @code{demo}
                   3915: again to see that this is true). Any new definition will use the new
                   3916: definition of @code{add-two}, but old definitions continue to use the
                   3917: version that already existed at the time that they were @code{compiled}.
1.1       anton    3918: 
1.29      crook    3919: Before you go on to the next section, try defining and redefining some
                   3920: words of your own.
1.1       anton    3921: 
1.29      crook    3922: @comment ----------------------------------------------
                   3923: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
                   3924: @section How does that work?
                   3925: @cindex parsing words
1.1       anton    3926: 
1.30      anton    3927: @c That's pretty deep (IMO way too deep) for an introduction. - anton
                   3928: 
                   3929: @c Is it a good idea to talk about the interpretation semantics of a
                   3930: @c number? We don't have an xt to go along with it. - anton
                   3931: 
                   3932: @c Now that I have eliminated execution semantics, I wonder if it would not
                   3933: @c be better to keep them (or add run-time semantics), to make it easier to
                   3934: @c explain what compilation semantics usually does. - anton
                   3935: 
1.44      crook    3936: @c nac-> I removed the term ``default compilation sematics'' from the
                   3937: @c introductory chapter. Removing ``execution semantics'' was making
                   3938: @c everything simpler to explain, then I think the use of this term made
                   3939: @c everything more complex again. I replaced it with ``default
                   3940: @c semantics'' (which is used elsewhere in the manual) by which I mean
                   3941: @c ``a definition that has neither the immediate nor the compile-only
1.83      anton    3942: @c flag set''.
                   3943: 
                   3944: @c anton: I have eliminated default semantics (except in one place where it
                   3945: @c means "default interpretation and compilation semantics"), because it
                   3946: @c makes no sense in the presence of combined words.  I reverted to
                   3947: @c "execution semantics" where necessary.
                   3948: 
                   3949: @c nac-> I reworded big chunks of the ``how does that work''
1.44      crook    3950: @c section (and, unusually for me, I think I even made it shorter!).  See
                   3951: @c what you think -- I know I have not addressed your primary concern
                   3952: @c that it is too heavy-going for an introduction. From what I understood
                   3953: @c of your course notes it looks as though they might be a good framework. 
                   3954: @c Things that I've tried to capture here are some things that came as a
                   3955: @c great revelation here when I first understood them. Also, I like the
                   3956: @c fact that a very simple code example shows up almost all of the issues
                   3957: @c that you need to understand to see how Forth works. That's unique and
                   3958: @c worthwhile to emphasise.
                   3959: 
1.83      anton    3960: @c anton: I think it's a good idea to present the details, especially those
                   3961: @c that you found to be a revelation, and probably the tutorial tries to be
                   3962: @c too superficial and does not get some of the things across that make
                   3963: @c Forth special.  I do believe that most of the time these things should
                   3964: @c be discussed at the end of a section or in separate sections instead of
                   3965: @c in the middle of a section (e.g., the stuff you added in "User-defined
                   3966: @c defining words" leads in a completely different direction from the rest
                   3967: @c of the section).
                   3968: 
1.29      crook    3969: Now we're going to take another look at the definition of @code{add-two}
                   3970: from the previous section. From our knowledge of the way that the text
                   3971: interpreter works, we would have expected this result when we tried to
                   3972: define @code{add-two}:
1.21      crook    3973: 
1.29      crook    3974: @example
1.44      crook    3975: @kbd{: add-two 2 + . ;@key{RET}}
1.134     anton    3976: *the terminal*:4: Undefined word
                   3977: : >>>add-two<<< 2 + . ;
1.29      crook    3978: @end example
1.28      crook    3979: 
1.29      crook    3980: The reason that this didn't happen is bound up in the way that @code{:}
                   3981: works. The word @code{:} does two special things. The first special
                   3982: thing that it does prevents the text interpreter from ever seeing the
                   3983: characters @code{add-two}. The text interpreter uses a variable called
                   3984: @cindex modifying >IN
1.44      crook    3985: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29      crook    3986: input line. When it encounters the word @code{:} it behaves in exactly
                   3987: the same way as it does for any other word; it looks it up in the name
                   3988: dictionary, finds its xt and executes it. When @code{:} executes, it
                   3989: looks at the input buffer, finds the word @code{add-two} and advances the
                   3990: value of @code{>IN} to point past it. It then does some other stuff
                   3991: associated with creating the new definition (including creating an entry
                   3992: for @code{add-two} in the name dictionary). When the execution of @code{:}
                   3993: completes, control returns to the text interpreter, which is oblivious
                   3994: to the fact that it has been tricked into ignoring part of the input
                   3995: line.
1.21      crook    3996: 
1.29      crook    3997: @cindex parsing words
                   3998: Words like @code{:} -- words that advance the value of @code{>IN} and so
                   3999: prevent the text interpreter from acting on the whole of the input line
                   4000: -- are called @dfn{parsing words}.
1.21      crook    4001: 
1.29      crook    4002: @cindex @code{state} - effect on the text interpreter
                   4003: @cindex text interpreter - effect of state
                   4004: The second special thing that @code{:} does is change the value of a
                   4005: variable called @code{state}, which affects the way that the text
                   4006: interpreter behaves. When Gforth starts up, @code{state} has the value
                   4007: 0, and the text interpreter is said to be @dfn{interpreting}. During a
                   4008: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44      crook    4009: the text interpreter is said to be @dfn{compiling}.
                   4010: 
                   4011: In this example, the text interpreter is compiling when it processes the
                   4012: string ``@code{2 + . ;}''. It still breaks the string down into
                   4013: character sequences in the same way. However, instead of pushing the
                   4014: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
                   4015: into the definition of @code{add-two} that will make the number @code{2} get
                   4016: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
                   4017: the behaviours of @code{+} and @code{.} are also compiled into the
                   4018: definition.
                   4019: 
                   4020: One category of words don't get compiled. These so-called @dfn{immediate
                   4021: words} get executed (performed @i{now}) regardless of whether the text
                   4022: interpreter is interpreting or compiling. The word @code{;} is an
                   4023: immediate word. Rather than being compiled into the definition, it
                   4024: executes. Its effect is to terminate the current definition, which
                   4025: includes changing the value of @code{state} back to 0.
                   4026: 
                   4027: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
                   4028: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
                   4029: definition.
1.28      crook    4030: 
1.30      anton    4031: In Forth, every word or number can be described in terms of two
1.29      crook    4032: properties:
1.28      crook    4033: 
                   4034: @itemize @bullet
                   4035: @item
1.29      crook    4036: @cindex interpretation semantics
1.44      crook    4037: Its @dfn{interpretation semantics} describe how it will behave when the
                   4038: text interpreter encounters it in @dfn{interpret} state. The
                   4039: interpretation semantics of a word are represented by an @dfn{execution
                   4040: token}.
1.28      crook    4041: @item
1.29      crook    4042: @cindex compilation semantics
1.44      crook    4043: Its @dfn{compilation semantics} describe how it will behave when the
                   4044: text interpreter encounters it in @dfn{compile} state. The compilation
                   4045: semantics of a word are represented in an implementation-dependent way;
                   4046: Gforth uses a @dfn{compilation token}.
1.29      crook    4047: @end itemize
                   4048: 
                   4049: @noindent
                   4050: Numbers are always treated in a fixed way:
                   4051: 
                   4052: @itemize @bullet
1.28      crook    4053: @item
1.44      crook    4054: When the number is @dfn{interpreted}, its behaviour is to push the
                   4055: number onto the stack.
1.28      crook    4056: @item
1.30      anton    4057: When the number is @dfn{compiled}, a piece of code is appended to the
                   4058: current definition that pushes the number when it runs. (In other words,
                   4059: the compilation semantics of a number are to postpone its interpretation
                   4060: semantics until the run-time of the definition that it is being compiled
                   4061: into.)
1.29      crook    4062: @end itemize
                   4063: 
1.44      crook    4064: Words don't behave in such a regular way, but most have @i{default
                   4065: semantics} which means that they behave like this:
1.29      crook    4066: 
                   4067: @itemize @bullet
1.28      crook    4068: @item
1.30      anton    4069: The @dfn{interpretation semantics} of the word are to do something useful.
                   4070: @item
1.29      crook    4071: The @dfn{compilation semantics} of the word are to append its
1.30      anton    4072: @dfn{interpretation semantics} to the current definition (so that its
                   4073: run-time behaviour is to do something useful).
1.28      crook    4074: @end itemize
                   4075: 
1.30      anton    4076: @cindex immediate words
1.44      crook    4077: The actual behaviour of any particular word can be controlled by using
                   4078: the words @code{immediate} and @code{compile-only} when the word is
                   4079: defined. These words set flags in the name dictionary entry of the most
                   4080: recently defined word, and these flags are retrieved by the text
                   4081: interpreter when it finds the word in the name dictionary.
                   4082: 
                   4083: A word that is marked as @dfn{immediate} has compilation semantics that
                   4084: are identical to its interpretation semantics. In other words, it
                   4085: behaves like this:
1.29      crook    4086: 
                   4087: @itemize @bullet
                   4088: @item
1.30      anton    4089: The @dfn{interpretation semantics} of the word are to do something useful.
1.29      crook    4090: @item
1.30      anton    4091: The @dfn{compilation semantics} of the word are to do something useful
                   4092: (and actually the same thing); i.e., it is executed during compilation.
1.29      crook    4093: @end itemize
1.28      crook    4094: 
1.44      crook    4095: Marking a word as @dfn{compile-only} prohibits the text interpreter from
                   4096: performing the interpretation semantics of the word directly; an attempt
                   4097: to do so will generate an error. It is never necessary to use
                   4098: @code{compile-only} (and it is not even part of ANS Forth, though it is
                   4099: provided by many implementations) but it is good etiquette to apply it
                   4100: to a word that will not behave correctly (and might have unexpected
                   4101: side-effects) in interpret state. For example, it is only legal to use
                   4102: the conditional word @code{IF} within a definition. If you forget this
                   4103: and try to use it elsewhere, the fact that (in Gforth) it is marked as
                   4104: @code{compile-only} allows the text interpreter to generate a helpful
                   4105: error message rather than subjecting you to the consequences of your
                   4106: folly.
                   4107: 
1.29      crook    4108: This example shows the difference between an immediate and a
                   4109: non-immediate word:
1.28      crook    4110: 
1.29      crook    4111: @example
                   4112: : show-state state @@ . ;
                   4113: : show-state-now show-state ; immediate
                   4114: : word1 show-state ;
                   4115: : word2 show-state-now ;
1.28      crook    4116: @end example
1.23      crook    4117: 
1.29      crook    4118: The word @code{immediate} after the definition of @code{show-state-now}
                   4119: makes that word an immediate word. These definitions introduce a new
                   4120: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
                   4121: variable, and leaves it on the stack. Therefore, the behaviour of
                   4122: @code{show-state} is to print a number that represents the current value
                   4123: of @code{state}.
1.28      crook    4124: 
1.29      crook    4125: When you execute @code{word1}, it prints the number 0, indicating that
                   4126: the system is interpreting. When the text interpreter compiled the
                   4127: definition of @code{word1}, it encountered @code{show-state} whose
1.30      anton    4128: compilation semantics are to append its interpretation semantics to the
1.29      crook    4129: current definition. When you execute @code{word1}, it performs the
1.30      anton    4130: interpretation semantics of @code{show-state}.  At the time that @code{word1}
1.29      crook    4131: (and therefore @code{show-state}) are executed, the system is
                   4132: interpreting.
1.28      crook    4133: 
1.30      anton    4134: When you pressed @key{RET} after entering the definition of @code{word2},
1.29      crook    4135: you should have seen the number -1 printed, followed by ``@code{
                   4136: ok}''. When the text interpreter compiled the definition of
                   4137: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30      anton    4138: whose compilation semantics are therefore to perform its interpretation
1.29      crook    4139: semantics. It is executed straight away (even before the text
                   4140: interpreter has moved on to process another group of characters; the
                   4141: @code{;} in this example). The effect of executing it are to display the
                   4142: value of @code{state} @i{at the time that the definition of}
                   4143: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
                   4144: system is compiling at this time. If you execute @code{word2} it does
                   4145: nothing at all.
1.28      crook    4146: 
1.29      crook    4147: @cindex @code{."}, how it works
                   4148: Before leaving the subject of immediate words, consider the behaviour of
                   4149: @code{."} in the definition of @code{greet}, in the previous
                   4150: section. This word is both a parsing word and an immediate word. Notice
                   4151: that there is a space between @code{."} and the start of the text
                   4152: @code{Hello and welcome}, but that there is no space between the last
                   4153: letter of @code{welcome} and the @code{"} character. The reason for this
                   4154: is that @code{."} is a Forth word; it must have a space after it so that
                   4155: the text interpreter can identify it. The @code{"} is not a Forth word;
                   4156: it is a @dfn{delimiter}. The examples earlier show that, when the string
                   4157: is displayed, there is neither a space before the @code{H} nor after the
                   4158: @code{e}. Since @code{."} is an immediate word, it executes at the time
                   4159: that @code{greet} is defined. When it executes, its behaviour is to
                   4160: search forward in the input line looking for the delimiter. When it
                   4161: finds the delimiter, it updates @code{>IN} to point past the
                   4162: delimiter. It also compiles some magic code into the definition of
                   4163: @code{greet}; the xt of a run-time routine that prints a text string. It
                   4164: compiles the string @code{Hello and welcome} into memory so that it is
                   4165: available to be printed later. When the text interpreter gains control,
                   4166: the next word it finds in the input stream is @code{;} and so it
                   4167: terminates the definition of @code{greet}.
1.28      crook    4168: 
                   4169: 
                   4170: @comment ----------------------------------------------
1.29      crook    4171: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
                   4172: @section Forth is written in Forth
                   4173: @cindex structure of Forth programs
                   4174: 
                   4175: When you start up a Forth compiler, a large number of definitions
                   4176: already exist. In Forth, you develop a new application using bottom-up
                   4177: programming techniques to create new definitions that are defined in
                   4178: terms of existing definitions. As you create each definition you can
                   4179: test and debug it interactively.
                   4180: 
                   4181: If you have tried out the examples in this section, you will probably
                   4182: have typed them in by hand; when you leave Gforth, your definitions will
                   4183: be lost. You can avoid this by using a text editor to enter Forth source
                   4184: code into a file, and then loading code from the file using
1.49      anton    4185: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29      crook    4186: processed by the text interpreter, just as though you had typed it in by
                   4187: hand@footnote{Actually, there are some subtle differences -- see
                   4188: @ref{The Text Interpreter}.}.
                   4189: 
                   4190: Gforth also supports the traditional Forth alternative to using text
1.49      anton    4191: files for program entry (@pxref{Blocks}).
1.28      crook    4192: 
1.29      crook    4193: In common with many, if not most, Forth compilers, most of Gforth is
                   4194: actually written in Forth. All of the @file{.fs} files in the
                   4195: installation directory@footnote{For example,
1.30      anton    4196: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29      crook    4197: study to see examples of Forth programming.
1.28      crook    4198: 
1.29      crook    4199: Gforth maintains a history file that records every line that you type to
                   4200: the text interpreter. This file is preserved between sessions, and is
                   4201: used to provide a command-line recall facility. If you enter long
                   4202: definitions by hand, you can use a text editor to paste them out of the
                   4203: history file into a Forth source file for reuse at a later time
1.49      anton    4204: (for more information @pxref{Command-line editing}).
1.28      crook    4205: 
                   4206: 
                   4207: @comment ----------------------------------------------
1.29      crook    4208: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
                   4209: @section Review - elements of a Forth system
                   4210: @cindex elements of a Forth system
1.28      crook    4211: 
1.29      crook    4212: To summarise this chapter:
1.28      crook    4213: 
                   4214: @itemize @bullet
                   4215: @item
1.29      crook    4216: Forth programs use @dfn{factoring} to break a problem down into small
                   4217: fragments called @dfn{words} or @dfn{definitions}.
                   4218: @item
                   4219: Forth program development is an interactive process.
                   4220: @item
                   4221: The main command loop that accepts input, and controls both
                   4222: interpretation and compilation, is called the @dfn{text interpreter}
                   4223: (also known as the @dfn{outer interpreter}).
                   4224: @item
                   4225: Forth has a very simple syntax, consisting of words and numbers
                   4226: separated by spaces or carriage-return characters. Any additional syntax
                   4227: is imposed by @dfn{parsing words}.
                   4228: @item
                   4229: Forth uses a stack to pass parameters between words. As a result, it
                   4230: uses postfix notation.
                   4231: @item
                   4232: To use a word that has previously been defined, the text interpreter
                   4233: searches for the word in the @dfn{name dictionary}.
                   4234: @item
1.30      anton    4235: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28      crook    4236: @item
1.29      crook    4237: The text interpreter uses the value of @code{state} to select between
                   4238: the use of the @dfn{interpretation semantics} and the  @dfn{compilation
                   4239: semantics} of a word that it encounters.
1.28      crook    4240: @item
1.30      anton    4241: The relationship between the @dfn{interpretation semantics} and
                   4242: @dfn{compilation semantics} for a word
1.29      crook    4243: depend upon the way in which the word was defined (for example, whether
                   4244: it is an @dfn{immediate} word).
1.28      crook    4245: @item
1.29      crook    4246: Forth definitions can be implemented in Forth (called @dfn{high-level
                   4247: definitions}) or in some other way (usually a lower-level language and
                   4248: as a result often called @dfn{low-level definitions}, @dfn{code
                   4249: definitions} or @dfn{primitives}).
1.28      crook    4250: @item
1.29      crook    4251: Many Forth systems are implemented mainly in Forth.
1.28      crook    4252: @end itemize
                   4253: 
                   4254: 
1.29      crook    4255: @comment ----------------------------------------------
1.48      anton    4256: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29      crook    4257: @section Where To Go Next
                   4258: @cindex where to go next
1.28      crook    4259: 
1.29      crook    4260: Amazing as it may seem, if you have read (and understood) this far, you
                   4261: know almost all the fundamentals about the inner workings of a Forth
                   4262: system. You certainly know enough to be able to read and understand the
                   4263: rest of this manual and the ANS Forth document, to learn more about the
                   4264: facilities that Forth in general and Gforth in particular provide. Even
                   4265: scarier, you know almost enough to implement your own Forth system.
1.30      anton    4266: However, that's not a good idea just yet... better to try writing some
1.29      crook    4267: programs in Gforth.
1.28      crook    4268: 
1.29      crook    4269: Forth has such a rich vocabulary that it can be hard to know where to
                   4270: start in learning it. This section suggests a few sets of words that are
                   4271: enough to write small but useful programs. Use the word index in this
                   4272: document to learn more about each word, then try it out and try to write
                   4273: small definitions using it. Start by experimenting with these words:
1.28      crook    4274: 
                   4275: @itemize @bullet
                   4276: @item
1.29      crook    4277: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
                   4278: @item
                   4279: Comparison: @code{MIN MAX =}
                   4280: @item
                   4281: Logic: @code{AND OR XOR NOT}
                   4282: @item
                   4283: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28      crook    4284: @item
1.29      crook    4285: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28      crook    4286: @item
1.29      crook    4287: Input/Output: @code{. ." EMIT CR KEY}
1.28      crook    4288: @item
1.29      crook    4289: Defining words: @code{: ; CREATE}
1.28      crook    4290: @item
1.29      crook    4291: Memory allocation words: @code{ALLOT ,}
1.28      crook    4292: @item
1.29      crook    4293: Tools: @code{SEE WORDS .S MARKER}
                   4294: @end itemize
                   4295: 
                   4296: When you have mastered those, go on to:
                   4297: 
                   4298: @itemize @bullet
1.28      crook    4299: @item
1.29      crook    4300: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28      crook    4301: @item
1.29      crook    4302: Memory access: @code{@@ !}
1.28      crook    4303: @end itemize
1.23      crook    4304: 
1.29      crook    4305: When you have mastered these, there's nothing for it but to read through
                   4306: the whole of this manual and find out what you've missed.
                   4307: 
                   4308: @comment ----------------------------------------------
1.48      anton    4309: @node Exercises,  , Where to go next, Introduction
1.29      crook    4310: @section Exercises
                   4311: @cindex exercises
                   4312: 
                   4313: TODO: provide a set of programming excercises linked into the stuff done
                   4314: already and into other sections of the manual. Provide solutions to all
                   4315: the exercises in a .fs file in the distribution.
                   4316: 
                   4317: @c Get some inspiration from Starting Forth and Kelly&Spies.
                   4318: 
                   4319: @c excercises:
                   4320: @c 1. take inches and convert to feet and inches.
                   4321: @c 2. take temperature and convert from fahrenheight to celcius;
                   4322: @c    may need to care about symmetric vs floored??
                   4323: @c 3. take input line and do character substitution
                   4324: @c    to encipher or decipher
                   4325: @c 4. as above but work on a file for in and out
                   4326: @c 5. take input line and convert to pig-latin 
                   4327: @c
                   4328: @c thing of sets of things to exercise then come up with
                   4329: @c problems that need those things.
                   4330: 
                   4331: 
1.26      crook    4332: @c ******************************************************************
1.29      crook    4333: @node Words, Error messages, Introduction, Top
1.1       anton    4334: @chapter Forth Words
1.26      crook    4335: @cindex words
1.1       anton    4336: 
                   4337: @menu
                   4338: * Notation::                    
1.65      anton    4339: * Case insensitivity::          
                   4340: * Comments::                    
                   4341: * Boolean Flags::               
1.1       anton    4342: * Arithmetic::                  
                   4343: * Stack Manipulation::          
1.5       anton    4344: * Memory::                      
1.1       anton    4345: * Control Structures::          
                   4346: * Defining Words::              
1.65      anton    4347: * Interpretation and Compilation Semantics::  
1.47      crook    4348: * Tokens for Words::            
1.81      anton    4349: * Compiling words::             
1.65      anton    4350: * The Text Interpreter::        
1.111     anton    4351: * The Input Stream::            
1.65      anton    4352: * Word Lists::                  
                   4353: * Environmental Queries::       
1.12      anton    4354: * Files::                       
                   4355: * Blocks::                      
                   4356: * Other I/O::                   
1.121     anton    4357: * OS command line arguments::   
1.78      anton    4358: * Locals::                      
                   4359: * Structures::                  
                   4360: * Object-oriented Forth::       
1.12      anton    4361: * Programming Tools::           
1.150     anton    4362: * C Interface::                 
1.12      anton    4363: * Assembler and Code Words::    
                   4364: * Threading Words::             
1.65      anton    4365: * Passing Commands to the OS::  
                   4366: * Keeping track of Time::       
                   4367: * Miscellaneous Words::         
1.1       anton    4368: @end menu
                   4369: 
1.65      anton    4370: @node Notation, Case insensitivity, Words, Words
1.1       anton    4371: @section Notation
                   4372: @cindex notation of glossary entries
                   4373: @cindex format of glossary entries
                   4374: @cindex glossary notation format
                   4375: @cindex word glossary entry format
                   4376: 
                   4377: The Forth words are described in this section in the glossary notation
1.67      anton    4378: that has become a de-facto standard for Forth texts:
1.1       anton    4379: 
                   4380: @format
1.29      crook    4381: @i{word}     @i{Stack effect}   @i{wordset}   @i{pronunciation}
1.1       anton    4382: @end format
1.29      crook    4383: @i{Description}
1.1       anton    4384: 
                   4385: @table @var
                   4386: @item word
1.28      crook    4387: The name of the word.
1.1       anton    4388: 
                   4389: @item Stack effect
                   4390: @cindex stack effect
1.29      crook    4391: The stack effect is written in the notation @code{@i{before} --
                   4392: @i{after}}, where @i{before} and @i{after} describe the top of
1.1       anton    4393: stack entries before and after the execution of the word. The rest of
                   4394: the stack is not touched by the word. The top of stack is rightmost,
                   4395: i.e., a stack sequence is written as it is typed in. Note that Gforth
                   4396: uses a separate floating point stack, but a unified stack
1.29      crook    4397: notation. Also, return stack effects are not shown in @i{stack
                   4398: effect}, but in @i{Description}. The name of a stack item describes
1.1       anton    4399: the type and/or the function of the item. See below for a discussion of
                   4400: the types.
                   4401: 
                   4402: All words have two stack effects: A compile-time stack effect and a
                   4403: run-time stack effect. The compile-time stack-effect of most words is
1.29      crook    4404: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1       anton    4405: this standard behaviour, or the word does other unusual things at
                   4406: compile time, both stack effects are shown; otherwise only the run-time
                   4407: stack effect is shown.
                   4408: 
                   4409: @cindex pronounciation of words
                   4410: @item pronunciation
                   4411: How the word is pronounced.
                   4412: 
                   4413: @cindex wordset
1.67      anton    4414: @cindex environment wordset
1.1       anton    4415: @item wordset
1.21      crook    4416: The ANS Forth standard is divided into several word sets. A standard
                   4417: system need not support all of them. Therefore, in theory, the fewer
                   4418: word sets your program uses the more portable it will be. However, we
                   4419: suspect that most ANS Forth systems on personal machines will feature
1.26      crook    4420: all word sets. Words that are not defined in ANS Forth have
1.21      crook    4421: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1       anton    4422: describes words that will work in future releases of Gforth;
                   4423: @code{gforth-internal} words are more volatile. Environmental query
                   4424: strings are also displayed like words; you can recognize them by the
1.21      crook    4425: @code{environment} in the word set field.
1.1       anton    4426: 
                   4427: @item Description
                   4428: A description of the behaviour of the word.
                   4429: @end table
                   4430: 
                   4431: @cindex types of stack items
                   4432: @cindex stack item types
                   4433: The type of a stack item is specified by the character(s) the name
                   4434: starts with:
                   4435: 
                   4436: @table @code
                   4437: @item f
                   4438: @cindex @code{f}, stack item type
                   4439: Boolean flags, i.e. @code{false} or @code{true}.
                   4440: @item c
                   4441: @cindex @code{c}, stack item type
                   4442: Char
                   4443: @item w
                   4444: @cindex @code{w}, stack item type
                   4445: Cell, can contain an integer or an address
                   4446: @item n
                   4447: @cindex @code{n}, stack item type
                   4448: signed integer
                   4449: @item u
                   4450: @cindex @code{u}, stack item type
                   4451: unsigned integer
                   4452: @item d
                   4453: @cindex @code{d}, stack item type
                   4454: double sized signed integer
                   4455: @item ud
                   4456: @cindex @code{ud}, stack item type
                   4457: double sized unsigned integer
                   4458: @item r
                   4459: @cindex @code{r}, stack item type
                   4460: Float (on the FP stack)
1.21      crook    4461: @item a-
1.1       anton    4462: @cindex @code{a_}, stack item type
                   4463: Cell-aligned address
1.21      crook    4464: @item c-
1.1       anton    4465: @cindex @code{c_}, stack item type
                   4466: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21      crook    4467: @item f-
1.1       anton    4468: @cindex @code{f_}, stack item type
                   4469: Float-aligned address
1.21      crook    4470: @item df-
1.1       anton    4471: @cindex @code{df_}, stack item type
                   4472: Address aligned for IEEE double precision float
1.21      crook    4473: @item sf-
1.1       anton    4474: @cindex @code{sf_}, stack item type
                   4475: Address aligned for IEEE single precision float
                   4476: @item xt
                   4477: @cindex @code{xt}, stack item type
                   4478: Execution token, same size as Cell
                   4479: @item wid
                   4480: @cindex @code{wid}, stack item type
1.21      crook    4481: Word list ID, same size as Cell
1.68      anton    4482: @item ior, wior
                   4483: @cindex ior type description
                   4484: @cindex wior type description
                   4485: I/O result code, cell-sized.  In Gforth, you can @code{throw} iors.
1.1       anton    4486: @item f83name
                   4487: @cindex @code{f83name}, stack item type
                   4488: Pointer to a name structure
                   4489: @item "
                   4490: @cindex @code{"}, stack item type
1.12      anton    4491: string in the input stream (not on the stack). The terminating character
                   4492: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1       anton    4493: quotes.
                   4494: @end table
                   4495: 
1.65      anton    4496: @comment ----------------------------------------------
                   4497: @node Case insensitivity, Comments, Notation, Words
                   4498: @section Case insensitivity
                   4499: @cindex case sensitivity
                   4500: @cindex upper and lower case
                   4501: 
                   4502: Gforth is case-insensitive; you can enter definitions and invoke
                   4503: Standard words using upper, lower or mixed case (however,
                   4504: @pxref{core-idef, Implementation-defined options, Implementation-defined
                   4505: options}).
                   4506: 
                   4507: ANS Forth only @i{requires} implementations to recognise Standard words
                   4508: when they are typed entirely in upper case. Therefore, a Standard
                   4509: program must use upper case for all Standard words. You can use whatever
                   4510: case you like for words that you define, but in a Standard program you
                   4511: have to use the words in the same case that you defined them.
                   4512: 
                   4513: Gforth supports case sensitivity through @code{table}s (case-sensitive
                   4514: wordlists, @pxref{Word Lists}).
                   4515: 
                   4516: Two people have asked how to convert Gforth to be case-sensitive; while
                   4517: we think this is a bad idea, you can change all wordlists into tables
                   4518: like this:
                   4519: 
                   4520: @example
                   4521: ' table-find forth-wordlist wordlist-map @ !
                   4522: @end example
                   4523: 
                   4524: Note that you now have to type the predefined words in the same case
                   4525: that we defined them, which are varying.  You may want to convert them
                   4526: to your favourite case before doing this operation (I won't explain how,
                   4527: because if you are even contemplating doing this, you'd better have
                   4528: enough knowledge of Forth systems to know this already).
                   4529: 
                   4530: @node Comments, Boolean Flags, Case insensitivity, Words
1.21      crook    4531: @section Comments
1.26      crook    4532: @cindex comments
1.21      crook    4533: 
1.29      crook    4534: Forth supports two styles of comment; the traditional @i{in-line} comment,
                   4535: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21      crook    4536: 
1.44      crook    4537: 
1.23      crook    4538: doc-(
1.21      crook    4539: doc-\
1.23      crook    4540: doc-\G
1.21      crook    4541: 
1.44      crook    4542: 
1.21      crook    4543: @node Boolean Flags, Arithmetic, Comments, Words
                   4544: @section Boolean Flags
1.26      crook    4545: @cindex Boolean flags
1.21      crook    4546: 
                   4547: A Boolean flag is cell-sized. A cell with all bits clear represents the
                   4548: flag @code{false} and a flag with all bits set represents the flag
1.26      crook    4549: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29      crook    4550: a cell that has @i{any} bit set as @code{true}.
1.67      anton    4551: @c on and off to Memory? 
                   4552: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44      crook    4553: 
1.21      crook    4554: doc-true
                   4555: doc-false
1.29      crook    4556: doc-on
                   4557: doc-off
1.21      crook    4558: 
1.44      crook    4559: 
1.21      crook    4560: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1       anton    4561: @section Arithmetic
                   4562: @cindex arithmetic words
                   4563: 
                   4564: @cindex division with potentially negative operands
                   4565: Forth arithmetic is not checked, i.e., you will not hear about integer
                   4566: overflow on addition or multiplication, you may hear about division by
                   4567: zero if you are lucky. The operator is written after the operands, but
                   4568: the operands are still in the original order. I.e., the infix @code{2-1}
                   4569: corresponds to @code{2 1 -}. Forth offers a variety of division
                   4570: operators. If you perform division with potentially negative operands,
                   4571: you do not want to use @code{/} or @code{/mod} with its undefined
                   4572: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
                   4573: former, @pxref{Mixed precision}).
1.26      crook    4574: @comment TODO discuss the different division forms and the std approach
1.1       anton    4575: 
                   4576: @menu
                   4577: * Single precision::            
1.67      anton    4578: * Double precision::            Double-cell integer arithmetic
1.1       anton    4579: * Bitwise operations::          
1.67      anton    4580: * Numeric comparison::          
1.29      crook    4581: * Mixed precision::             Operations with single and double-cell integers
1.1       anton    4582: * Floating Point::              
                   4583: @end menu
                   4584: 
1.67      anton    4585: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1       anton    4586: @subsection Single precision
                   4587: @cindex single precision arithmetic words
                   4588: 
1.67      anton    4589: @c !! cell undefined
                   4590: 
                   4591: By default, numbers in Forth are single-precision integers that are one
1.26      crook    4592: cell in size. They can be signed or unsigned, depending upon how you
1.49      anton    4593: treat them. For the rules used by the text interpreter for recognising
                   4594: single-precision integers see @ref{Number Conversion}.
1.21      crook    4595: 
1.67      anton    4596: These words are all defined for signed operands, but some of them also
                   4597: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
                   4598: @code{*}.
1.44      crook    4599: 
1.1       anton    4600: doc-+
1.21      crook    4601: doc-1+
1.128     anton    4602: doc-under+
1.1       anton    4603: doc--
1.21      crook    4604: doc-1-
1.1       anton    4605: doc-*
                   4606: doc-/
                   4607: doc-mod
                   4608: doc-/mod
                   4609: doc-negate
                   4610: doc-abs
                   4611: doc-min
                   4612: doc-max
1.27      crook    4613: doc-floored
1.1       anton    4614: 
1.44      crook    4615: 
1.67      anton    4616: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21      crook    4617: @subsection Double precision
                   4618: @cindex double precision arithmetic words
                   4619: 
1.49      anton    4620: For the rules used by the text interpreter for
                   4621: recognising double-precision integers, see @ref{Number Conversion}.
1.21      crook    4622: 
                   4623: A double precision number is represented by a cell pair, with the most
1.67      anton    4624: significant cell at the TOS. It is trivial to convert an unsigned single
                   4625: to a double: simply push a @code{0} onto the TOS. Since numbers are
                   4626: represented by Gforth using 2's complement arithmetic, converting a
                   4627: signed single to a (signed) double requires sign-extension across the
                   4628: most significant cell. This can be achieved using @code{s>d}. The moral
                   4629: of the story is that you cannot convert a number without knowing whether
                   4630: it represents an unsigned or a signed number.
1.21      crook    4631: 
1.67      anton    4632: These words are all defined for signed operands, but some of them also
                   4633: work for unsigned numbers: @code{d+}, @code{d-}.
1.44      crook    4634: 
1.21      crook    4635: doc-s>d
1.67      anton    4636: doc-d>s
1.21      crook    4637: doc-d+
                   4638: doc-d-
                   4639: doc-dnegate
                   4640: doc-dabs
                   4641: doc-dmin
                   4642: doc-dmax
                   4643: 
1.44      crook    4644: 
1.67      anton    4645: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
                   4646: @subsection Bitwise operations
                   4647: @cindex bitwise operation words
                   4648: 
                   4649: 
                   4650: doc-and
                   4651: doc-or
                   4652: doc-xor
                   4653: doc-invert
                   4654: doc-lshift
                   4655: doc-rshift
                   4656: doc-2*
                   4657: doc-d2*
                   4658: doc-2/
                   4659: doc-d2/
                   4660: 
                   4661: 
                   4662: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21      crook    4663: @subsection Numeric comparison
                   4664: @cindex numeric comparison words
                   4665: 
1.67      anton    4666: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
                   4667: d0= d0<>}) work for for both signed and unsigned numbers.
1.44      crook    4668: 
1.28      crook    4669: doc-<
                   4670: doc-<=
                   4671: doc-<>
                   4672: doc-=
                   4673: doc->
                   4674: doc->=
                   4675: 
1.21      crook    4676: doc-0<
1.23      crook    4677: doc-0<=
1.21      crook    4678: doc-0<>
                   4679: doc-0=
1.23      crook    4680: doc-0>
                   4681: doc-0>=
1.28      crook    4682: 
                   4683: doc-u<
                   4684: doc-u<=
1.44      crook    4685: @c u<> and u= exist but are the same as <> and =
1.31      anton    4686: @c doc-u<>
                   4687: @c doc-u=
1.28      crook    4688: doc-u>
                   4689: doc-u>=
                   4690: 
                   4691: doc-within
                   4692: 
                   4693: doc-d<
                   4694: doc-d<=
                   4695: doc-d<>
                   4696: doc-d=
                   4697: doc-d>
                   4698: doc-d>=
1.23      crook    4699: 
1.21      crook    4700: doc-d0<
1.23      crook    4701: doc-d0<=
                   4702: doc-d0<>
1.21      crook    4703: doc-d0=
1.23      crook    4704: doc-d0>
                   4705: doc-d0>=
                   4706: 
1.21      crook    4707: doc-du<
1.28      crook    4708: doc-du<=
1.44      crook    4709: @c du<> and du= exist but are the same as d<> and d=
1.31      anton    4710: @c doc-du<>
                   4711: @c doc-du=
1.28      crook    4712: doc-du>
                   4713: doc-du>=
1.1       anton    4714: 
1.44      crook    4715: 
1.21      crook    4716: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1       anton    4717: @subsection Mixed precision
                   4718: @cindex mixed precision arithmetic words
                   4719: 
1.44      crook    4720: 
1.1       anton    4721: doc-m+
                   4722: doc-*/
                   4723: doc-*/mod
                   4724: doc-m*
                   4725: doc-um*
                   4726: doc-m*/
                   4727: doc-um/mod
                   4728: doc-fm/mod
                   4729: doc-sm/rem
                   4730: 
1.44      crook    4731: 
1.21      crook    4732: @node Floating Point,  , Mixed precision, Arithmetic
1.1       anton    4733: @subsection Floating Point
                   4734: @cindex floating point arithmetic words
                   4735: 
1.49      anton    4736: For the rules used by the text interpreter for
                   4737: recognising floating-point numbers see @ref{Number Conversion}.
1.1       anton    4738: 
1.67      anton    4739: Gforth has a separate floating point stack, but the documentation uses
                   4740: the unified notation.@footnote{It's easy to generate the separate
                   4741: notation from that by just separating the floating-point numbers out:
                   4742: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
                   4743: r3 )}.}
1.1       anton    4744: 
                   4745: @cindex floating-point arithmetic, pitfalls
                   4746: Floating point numbers have a number of unpleasant surprises for the
1.190     anton    4747: unwary (e.g., floating point addition is not associative) and even a
                   4748: few for the wary. You should not use them unless you know what you are
                   4749: doing or you don't care that the results you get are totally bogus. If
                   4750: you want to learn about the problems of floating point numbers (and
                   4751: how to avoid them), you might start with @cite{David Goldberg,
                   4752: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
                   4753: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
                   4754: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1       anton    4755: 
1.44      crook    4756: 
1.21      crook    4757: doc-d>f
                   4758: doc-f>d
1.1       anton    4759: doc-f+
                   4760: doc-f-
                   4761: doc-f*
                   4762: doc-f/
                   4763: doc-fnegate
                   4764: doc-fabs
                   4765: doc-fmax
                   4766: doc-fmin
                   4767: doc-floor
                   4768: doc-fround
                   4769: doc-f**
                   4770: doc-fsqrt
                   4771: doc-fexp
                   4772: doc-fexpm1
                   4773: doc-fln
                   4774: doc-flnp1
                   4775: doc-flog
                   4776: doc-falog
1.32      anton    4777: doc-f2*
                   4778: doc-f2/
                   4779: doc-1/f
                   4780: doc-precision
                   4781: doc-set-precision
                   4782: 
                   4783: @cindex angles in trigonometric operations
                   4784: @cindex trigonometric operations
                   4785: Angles in floating point operations are given in radians (a full circle
                   4786: has 2 pi radians).
                   4787: 
1.1       anton    4788: doc-fsin
                   4789: doc-fcos
                   4790: doc-fsincos
                   4791: doc-ftan
                   4792: doc-fasin
                   4793: doc-facos
                   4794: doc-fatan
                   4795: doc-fatan2
                   4796: doc-fsinh
                   4797: doc-fcosh
                   4798: doc-ftanh
                   4799: doc-fasinh
                   4800: doc-facosh
                   4801: doc-fatanh
1.21      crook    4802: doc-pi
1.28      crook    4803: 
1.32      anton    4804: @cindex equality of floats
                   4805: @cindex floating-point comparisons
1.31      anton    4806: One particular problem with floating-point arithmetic is that comparison
                   4807: for equality often fails when you would expect it to succeed.  For this
                   4808: reason approximate equality is often preferred (but you still have to
1.67      anton    4809: know what you are doing).  Also note that IEEE NaNs may compare
1.68      anton    4810: differently from what you might expect.  The comparison words are:
1.31      anton    4811: 
                   4812: doc-f~rel
                   4813: doc-f~abs
1.68      anton    4814: doc-f~
1.31      anton    4815: doc-f=
                   4816: doc-f<>
                   4817: 
                   4818: doc-f<
                   4819: doc-f<=
                   4820: doc-f>
                   4821: doc-f>=
                   4822: 
1.21      crook    4823: doc-f0<
1.28      crook    4824: doc-f0<=
                   4825: doc-f0<>
1.21      crook    4826: doc-f0=
1.28      crook    4827: doc-f0>
                   4828: doc-f0>=
                   4829: 
1.1       anton    4830: 
                   4831: @node Stack Manipulation, Memory, Arithmetic, Words
                   4832: @section Stack Manipulation
                   4833: @cindex stack manipulation words
                   4834: 
                   4835: @cindex floating-point stack in the standard
1.21      crook    4836: Gforth maintains a number of separate stacks:
                   4837: 
1.29      crook    4838: @cindex data stack
                   4839: @cindex parameter stack
1.21      crook    4840: @itemize @bullet
                   4841: @item
1.29      crook    4842: A data stack (also known as the @dfn{parameter stack}) -- for
                   4843: characters, cells, addresses, and double cells.
1.21      crook    4844: 
1.29      crook    4845: @cindex floating-point stack
1.21      crook    4846: @item
1.44      crook    4847: A floating point stack -- for holding floating point (FP) numbers.
1.21      crook    4848: 
1.29      crook    4849: @cindex return stack
1.21      crook    4850: @item
1.44      crook    4851: A return stack -- for holding the return addresses of colon
1.32      anton    4852: definitions and other (non-FP) data.
1.21      crook    4853: 
1.29      crook    4854: @cindex locals stack
1.21      crook    4855: @item
1.44      crook    4856: A locals stack -- for holding local variables.
1.21      crook    4857: @end itemize
                   4858: 
1.1       anton    4859: @menu
                   4860: * Data stack::                  
                   4861: * Floating point stack::        
                   4862: * Return stack::                
                   4863: * Locals stack::                
                   4864: * Stack pointer manipulation::  
                   4865: @end menu
                   4866: 
                   4867: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
                   4868: @subsection Data stack
                   4869: @cindex data stack manipulation words
                   4870: @cindex stack manipulations words, data stack
                   4871: 
1.44      crook    4872: 
1.1       anton    4873: doc-drop
                   4874: doc-nip
                   4875: doc-dup
                   4876: doc-over
                   4877: doc-tuck
                   4878: doc-swap
1.21      crook    4879: doc-pick
1.1       anton    4880: doc-rot
                   4881: doc--rot
                   4882: doc-?dup
                   4883: doc-roll
                   4884: doc-2drop
                   4885: doc-2nip
                   4886: doc-2dup
                   4887: doc-2over
                   4888: doc-2tuck
                   4889: doc-2swap
                   4890: doc-2rot
                   4891: 
1.44      crook    4892: 
1.1       anton    4893: @node Floating point stack, Return stack, Data stack, Stack Manipulation
                   4894: @subsection Floating point stack
                   4895: @cindex floating-point stack manipulation words
                   4896: @cindex stack manipulation words, floating-point stack
                   4897: 
1.32      anton    4898: Whilst every sane Forth has a separate floating-point stack, it is not
                   4899: strictly required; an ANS Forth system could theoretically keep
                   4900: floating-point numbers on the data stack. As an additional difficulty,
                   4901: you don't know how many cells a floating-point number takes. It is
                   4902: reportedly possible to write words in a way that they work also for a
                   4903: unified stack model, but we do not recommend trying it. Instead, just
                   4904: say that your program has an environmental dependency on a separate
                   4905: floating-point stack.
                   4906: 
                   4907: doc-floating-stack
                   4908: 
1.1       anton    4909: doc-fdrop
                   4910: doc-fnip
                   4911: doc-fdup
                   4912: doc-fover
                   4913: doc-ftuck
                   4914: doc-fswap
1.21      crook    4915: doc-fpick
1.1       anton    4916: doc-frot
                   4917: 
1.44      crook    4918: 
1.1       anton    4919: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
                   4920: @subsection Return stack
                   4921: @cindex return stack manipulation words
                   4922: @cindex stack manipulation words, return stack
                   4923: 
1.32      anton    4924: @cindex return stack and locals
                   4925: @cindex locals and return stack
                   4926: A Forth system is allowed to keep local variables on the
                   4927: return stack. This is reasonable, as local variables usually eliminate
                   4928: the need to use the return stack explicitly. So, if you want to produce
                   4929: a standard compliant program and you are using local variables in a
                   4930: word, forget about return stack manipulations in that word (refer to the
                   4931: standard document for the exact rules).
                   4932: 
1.1       anton    4933: doc->r
                   4934: doc-r>
                   4935: doc-r@
                   4936: doc-rdrop
                   4937: doc-2>r
                   4938: doc-2r>
                   4939: doc-2r@
                   4940: doc-2rdrop
                   4941: 
1.44      crook    4942: 
1.1       anton    4943: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
                   4944: @subsection Locals stack
                   4945: 
1.78      anton    4946: Gforth uses an extra locals stack.  It is described, along with the
                   4947: reasons for its existence, in @ref{Locals implementation}.
1.21      crook    4948: 
1.1       anton    4949: @node Stack pointer manipulation,  , Locals stack, Stack Manipulation
                   4950: @subsection Stack pointer manipulation
                   4951: @cindex stack pointer manipulation words
                   4952: 
1.44      crook    4953: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21      crook    4954: doc-sp0
1.1       anton    4955: doc-sp@
                   4956: doc-sp!
1.21      crook    4957: doc-fp0
1.1       anton    4958: doc-fp@
                   4959: doc-fp!
1.21      crook    4960: doc-rp0
1.1       anton    4961: doc-rp@
                   4962: doc-rp!
1.21      crook    4963: doc-lp0
1.1       anton    4964: doc-lp@
                   4965: doc-lp!
                   4966: 
1.44      crook    4967: 
1.1       anton    4968: @node Memory, Control Structures, Stack Manipulation, Words
                   4969: @section Memory
1.26      crook    4970: @cindex memory words
1.1       anton    4971: 
1.32      anton    4972: @menu
                   4973: * Memory model::                
                   4974: * Dictionary allocation::       
                   4975: * Heap Allocation::             
                   4976: * Memory Access::               
                   4977: * Address arithmetic::          
                   4978: * Memory Blocks::               
                   4979: @end menu
                   4980: 
1.67      anton    4981: In addition to the standard Forth memory allocation words, there is also
                   4982: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   4983: garbage collector}.
                   4984: 
1.32      anton    4985: @node Memory model, Dictionary allocation, Memory, Memory
                   4986: @subsection ANS Forth and Gforth memory models
                   4987: 
                   4988: @c The ANS Forth description is a mess (e.g., is the heap part of
                   4989: @c the dictionary?), so let's not stick to closely with it.
                   4990: 
1.67      anton    4991: ANS Forth considers a Forth system as consisting of several address
                   4992: spaces, of which only @dfn{data space} is managed and accessible with
                   4993: the memory words.  Memory not necessarily in data space includes the
                   4994: stacks, the code (called code space) and the headers (called name
                   4995: space). In Gforth everything is in data space, but the code for the
                   4996: primitives is usually read-only.
1.32      anton    4997: 
                   4998: Data space is divided into a number of areas: The (data space portion of
                   4999: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
                   5000: refer to the search data structure embodied in word lists and headers,
                   5001: because it is used for looking up names, just as you would in a
                   5002: conventional dictionary.}, the heap, and a number of system-allocated
                   5003: buffers.
                   5004: 
1.68      anton    5005: @cindex address arithmetic restrictions, ANS vs. Gforth
                   5006: @cindex contiguous regions, ANS vs. Gforth
1.32      anton    5007: In ANS Forth data space is also divided into contiguous regions.  You
                   5008: can only use address arithmetic within a contiguous region, not between
                   5009: them.  Usually each allocation gives you one contiguous region, but the
1.33      anton    5010: dictionary allocation words have additional rules (@pxref{Dictionary
1.32      anton    5011: allocation}).
                   5012: 
                   5013: Gforth provides one big address space, and address arithmetic can be
                   5014: performed between any addresses. However, in the dictionary headers or
                   5015: code are interleaved with data, so almost the only contiguous data space
                   5016: regions there are those described by ANS Forth as contiguous; but you
                   5017: can be sure that the dictionary is allocated towards increasing
                   5018: addresses even between contiguous regions.  The memory order of
                   5019: allocations in the heap is platform-dependent (and possibly different
                   5020: from one run to the next).
                   5021: 
1.27      crook    5022: 
1.32      anton    5023: @node Dictionary allocation, Heap Allocation, Memory model, Memory
                   5024: @subsection Dictionary allocation
1.27      crook    5025: @cindex reserving data space
                   5026: @cindex data space - reserving some
                   5027: 
1.32      anton    5028: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
                   5029: you want to deallocate X, you also deallocate everything
                   5030: allocated after X.
                   5031: 
1.68      anton    5032: @cindex contiguous regions in dictionary allocation
1.32      anton    5033: The allocations using the words below are contiguous and grow the region
                   5034: towards increasing addresses.  Other words that allocate dictionary
                   5035: memory of any kind (i.e., defining words including @code{:noname}) end
                   5036: the contiguous region and start a new one.
                   5037: 
                   5038: In ANS Forth only @code{create}d words are guaranteed to produce an
                   5039: address that is the start of the following contiguous region.  In
                   5040: particular, the cell allocated by @code{variable} is not guaranteed to
                   5041: be contiguous with following @code{allot}ed memory.
                   5042: 
                   5043: You can deallocate memory by using @code{allot} with a negative argument
                   5044: (with some restrictions, see @code{allot}). For larger deallocations use
                   5045: @code{marker}.
1.27      crook    5046: 
1.29      crook    5047: 
1.27      crook    5048: doc-here
                   5049: doc-unused
                   5050: doc-allot
                   5051: doc-c,
1.29      crook    5052: doc-f,
1.27      crook    5053: doc-,
                   5054: doc-2,
                   5055: 
1.32      anton    5056: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
                   5057: course you should allocate memory in an aligned way, too. I.e., before
                   5058: allocating allocating a cell, @code{here} must be cell-aligned, etc.
                   5059: The words below align @code{here} if it is not already.  Basically it is
                   5060: only already aligned for a type, if the last allocation was a multiple
                   5061: of the size of this type and if @code{here} was aligned for this type
                   5062: before.
                   5063: 
                   5064: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
                   5065: ANS Forth (@code{maxalign}ed in Gforth).
                   5066: 
                   5067: doc-align
                   5068: doc-falign
                   5069: doc-sfalign
                   5070: doc-dfalign
                   5071: doc-maxalign
                   5072: doc-cfalign
                   5073: 
                   5074: 
                   5075: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
                   5076: @subsection Heap allocation
                   5077: @cindex heap allocation
                   5078: @cindex dynamic allocation of memory
                   5079: @cindex memory-allocation word set
                   5080: 
1.68      anton    5081: @cindex contiguous regions and heap allocation
1.32      anton    5082: Heap allocation supports deallocation of allocated memory in any
                   5083: order. Dictionary allocation is not affected by it (i.e., it does not
                   5084: end a contiguous region). In Gforth, these words are implemented using
                   5085: the standard C library calls malloc(), free() and resize().
                   5086: 
1.68      anton    5087: The memory region produced by one invocation of @code{allocate} or
                   5088: @code{resize} is internally contiguous.  There is no contiguity between
                   5089: such a region and any other region (including others allocated from the
                   5090: heap).
                   5091: 
1.32      anton    5092: doc-allocate
                   5093: doc-free
                   5094: doc-resize
                   5095: 
1.27      crook    5096: 
1.32      anton    5097: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1       anton    5098: @subsection Memory Access
                   5099: @cindex memory access words
                   5100: 
                   5101: doc-@
                   5102: doc-!
                   5103: doc-+!
                   5104: doc-c@
                   5105: doc-c!
                   5106: doc-2@
                   5107: doc-2!
                   5108: doc-f@
                   5109: doc-f!
                   5110: doc-sf@
                   5111: doc-sf!
                   5112: doc-df@
                   5113: doc-df!
1.144     anton    5114: doc-sw@
                   5115: doc-uw@
                   5116: doc-w!
                   5117: doc-sl@
                   5118: doc-ul@
                   5119: doc-l!
1.68      anton    5120: 
1.32      anton    5121: @node Address arithmetic, Memory Blocks, Memory Access, Memory
                   5122: @subsection Address arithmetic
1.1       anton    5123: @cindex address arithmetic words
                   5124: 
1.67      anton    5125: Address arithmetic is the foundation on which you can build data
                   5126: structures like arrays, records (@pxref{Structures}) and objects
                   5127: (@pxref{Object-oriented Forth}).
1.32      anton    5128: 
1.68      anton    5129: @cindex address unit
                   5130: @cindex au (address unit)
1.1       anton    5131: ANS Forth does not specify the sizes of the data types. Instead, it
                   5132: offers a number of words for computing sizes and doing address
1.29      crook    5133: arithmetic. Address arithmetic is performed in terms of address units
                   5134: (aus); on most systems the address unit is one byte. Note that a
                   5135: character may have more than one au, so @code{chars} is no noop (on
1.68      anton    5136: platforms where it is a noop, it compiles to nothing).
1.1       anton    5137: 
1.67      anton    5138: The basic address arithmetic words are @code{+} and @code{-}.  E.g., if
                   5139: you have the address of a cell, perform @code{1 cells +}, and you will
                   5140: have the address of the next cell.
                   5141: 
1.68      anton    5142: @cindex contiguous regions and address arithmetic
1.67      anton    5143: In ANS Forth you can perform address arithmetic only within a contiguous
                   5144: region, i.e., if you have an address into one region, you can only add
                   5145: and subtract such that the result is still within the region; you can
                   5146: only subtract or compare addresses from within the same contiguous
                   5147: region.  Reasons: several contiguous regions can be arranged in memory
                   5148: in any way; on segmented systems addresses may have unusual
                   5149: representations, such that address arithmetic only works within a
                   5150: region.  Gforth provides a few more guarantees (linear address space,
                   5151: dictionary grows upwards), but in general I have found it easy to stay
                   5152: within contiguous regions (exception: computing and comparing to the
                   5153: address just beyond the end of an array).
                   5154: 
1.1       anton    5155: @cindex alignment of addresses for types
                   5156: ANS Forth also defines words for aligning addresses for specific
                   5157: types. Many computers require that accesses to specific data types
                   5158: must only occur at specific addresses; e.g., that cells may only be
                   5159: accessed at addresses divisible by 4. Even if a machine allows unaligned
                   5160: accesses, it can usually perform aligned accesses faster. 
                   5161: 
                   5162: For the performance-conscious: alignment operations are usually only
                   5163: necessary during the definition of a data structure, not during the
                   5164: (more frequent) accesses to it.
                   5165: 
                   5166: ANS Forth defines no words for character-aligning addresses. This is not
                   5167: an oversight, but reflects the fact that addresses that are not
                   5168: char-aligned have no use in the standard and therefore will not be
                   5169: created.
                   5170: 
                   5171: @cindex @code{CREATE} and alignment
1.29      crook    5172: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1       anton    5173: are cell-aligned; in addition, Gforth guarantees that these addresses
                   5174: are aligned for all purposes.
                   5175: 
1.26      crook    5176: Note that the ANS Forth word @code{char} has nothing to do with address
                   5177: arithmetic.
1.1       anton    5178: 
1.44      crook    5179: 
1.1       anton    5180: doc-chars
                   5181: doc-char+
                   5182: doc-cells
                   5183: doc-cell+
                   5184: doc-cell
                   5185: doc-aligned
                   5186: doc-floats
                   5187: doc-float+
                   5188: doc-float
                   5189: doc-faligned
                   5190: doc-sfloats
                   5191: doc-sfloat+
                   5192: doc-sfaligned
                   5193: doc-dfloats
                   5194: doc-dfloat+
                   5195: doc-dfaligned
                   5196: doc-maxaligned
                   5197: doc-cfaligned
                   5198: doc-address-unit-bits
1.145     anton    5199: doc-/w
                   5200: doc-/l
1.44      crook    5201: 
1.32      anton    5202: @node Memory Blocks,  , Address arithmetic, Memory
1.1       anton    5203: @subsection Memory Blocks
                   5204: @cindex memory block words
1.27      crook    5205: @cindex character strings - moving and copying
                   5206: 
1.49      anton    5207: Memory blocks often represent character strings; For ways of storing
                   5208: character strings in memory see @ref{String Formats}.  For other
                   5209: string-processing words see @ref{Displaying characters and strings}.
1.1       anton    5210: 
1.67      anton    5211: A few of these words work on address unit blocks.  In that case, you
                   5212: usually have to insert @code{CHARS} before the word when working on
                   5213: character strings.  Most words work on character blocks, and expect a
                   5214: char-aligned address.
                   5215: 
                   5216: When copying characters between overlapping memory regions, use
                   5217: @code{chars move} or choose carefully between @code{cmove} and
                   5218: @code{cmove>}.
1.44      crook    5219: 
1.1       anton    5220: doc-move
                   5221: doc-erase
                   5222: doc-cmove
                   5223: doc-cmove>
                   5224: doc-fill
                   5225: doc-blank
1.21      crook    5226: doc-compare
1.111     anton    5227: doc-str=
                   5228: doc-str<
                   5229: doc-string-prefix?
1.21      crook    5230: doc-search
1.27      crook    5231: doc--trailing
                   5232: doc-/string
1.82      anton    5233: doc-bounds
1.141     anton    5234: doc-pad
1.111     anton    5235: 
1.27      crook    5236: @comment TODO examples
                   5237: 
1.1       anton    5238: 
1.26      crook    5239: @node Control Structures, Defining Words, Memory, Words
1.1       anton    5240: @section Control Structures
                   5241: @cindex control structures
                   5242: 
1.33      anton    5243: Control structures in Forth cannot be used interpretively, only in a
                   5244: colon definition@footnote{To be precise, they have no interpretation
                   5245: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
                   5246: not like this limitation, but have not seen a satisfying way around it
                   5247: yet, although many schemes have been proposed.
1.1       anton    5248: 
                   5249: @menu
1.33      anton    5250: * Selection::                   IF ... ELSE ... ENDIF
                   5251: * Simple Loops::                BEGIN ...
1.29      crook    5252: * Counted Loops::               DO
1.67      anton    5253: * Arbitrary control structures::  
                   5254: * Calls and returns::           
1.1       anton    5255: * Exception Handling::          
                   5256: @end menu
                   5257: 
                   5258: @node Selection, Simple Loops, Control Structures, Control Structures
                   5259: @subsection Selection
                   5260: @cindex selection control structures
                   5261: @cindex control structures for selection
                   5262: 
                   5263: @cindex @code{IF} control structure
                   5264: @example
1.29      crook    5265: @i{flag}
1.1       anton    5266: IF
1.29      crook    5267:   @i{code}
1.1       anton    5268: ENDIF
                   5269: @end example
1.21      crook    5270: @noindent
1.33      anton    5271: 
1.44      crook    5272: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
                   5273: with any bit set represents truth) @i{code} is executed.
1.33      anton    5274: 
1.1       anton    5275: @example
1.29      crook    5276: @i{flag}
1.1       anton    5277: IF
1.29      crook    5278:   @i{code1}
1.1       anton    5279: ELSE
1.29      crook    5280:   @i{code2}
1.1       anton    5281: ENDIF
                   5282: @end example
                   5283: 
1.44      crook    5284: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
                   5285: executed.
1.33      anton    5286: 
1.1       anton    5287: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
                   5288: standard, and @code{ENDIF} is not, although it is quite popular. We
                   5289: recommend using @code{ENDIF}, because it is less confusing for people
                   5290: who also know other languages (and is not prone to reinforcing negative
                   5291: prejudices against Forth in these people). Adding @code{ENDIF} to a
                   5292: system that only supplies @code{THEN} is simple:
                   5293: @example
1.82      anton    5294: : ENDIF   POSTPONE then ; immediate
1.1       anton    5295: @end example
                   5296: 
                   5297: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
                   5298: (adv.)}  has the following meanings:
                   5299: @quotation
                   5300: ... 2b: following next after in order ... 3d: as a necessary consequence
                   5301: (if you were there, then you saw them).
                   5302: @end quotation
                   5303: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
                   5304: and many other programming languages has the meaning 3d.]
                   5305: 
1.21      crook    5306: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1       anton    5307: you can avoid using @code{?dup}. Using these alternatives is also more
1.26      crook    5308: efficient than using @code{?dup}. Definitions in ANS Forth
1.1       anton    5309: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
                   5310: @file{compat/control.fs}.
                   5311: 
                   5312: @cindex @code{CASE} control structure
                   5313: @example
1.29      crook    5314: @i{n}
1.1       anton    5315: CASE
1.29      crook    5316:   @i{n1} OF @i{code1} ENDOF
                   5317:   @i{n2} OF @i{code2} ENDOF
1.1       anton    5318:   @dots{}
1.68      anton    5319:   ( n ) @i{default-code} ( n )
1.131     anton    5320: ENDCASE ( )
1.1       anton    5321: @end example
                   5322: 
1.131     anton    5323: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}.  If
                   5324: no @i{ni} matches, the optional @i{default-code} is executed. The
                   5325: optional default case can be added by simply writing the code after
                   5326: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
                   5327: but must not consume it.  The value @i{n} is consumed by this
                   5328: construction (either by a OF that matches, or by the ENDCASE, if no OF
                   5329: matches).
1.1       anton    5330: 
1.69      anton    5331: @progstyle
1.131     anton    5332: To keep the code understandable, you should ensure that you change the
                   5333: stack in the same way (wrt. number and types of stack items consumed
                   5334: and pushed) on all paths through a selection construct.
1.69      anton    5335: 
1.1       anton    5336: @node Simple Loops, Counted Loops, Selection, Control Structures
                   5337: @subsection Simple Loops
                   5338: @cindex simple loops
                   5339: @cindex loops without count 
                   5340: 
                   5341: @cindex @code{WHILE} loop
                   5342: @example
                   5343: BEGIN
1.29      crook    5344:   @i{code1}
                   5345:   @i{flag}
1.1       anton    5346: WHILE
1.29      crook    5347:   @i{code2}
1.1       anton    5348: REPEAT
                   5349: @end example
                   5350: 
1.29      crook    5351: @i{code1} is executed and @i{flag} is computed. If it is true,
                   5352: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1       anton    5353: false, execution continues after the @code{REPEAT}.
                   5354: 
                   5355: @cindex @code{UNTIL} loop
                   5356: @example
                   5357: BEGIN
1.29      crook    5358:   @i{code}
                   5359:   @i{flag}
1.1       anton    5360: UNTIL
                   5361: @end example
                   5362: 
1.29      crook    5363: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1       anton    5364: 
1.69      anton    5365: @progstyle
                   5366: To keep the code understandable, a complete iteration of the loop should
                   5367: not change the number and types of the items on the stacks.
                   5368: 
1.1       anton    5369: @cindex endless loop
                   5370: @cindex loops, endless
                   5371: @example
                   5372: BEGIN
1.29      crook    5373:   @i{code}
1.1       anton    5374: AGAIN
                   5375: @end example
                   5376: 
                   5377: This is an endless loop.
                   5378: 
                   5379: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
                   5380: @subsection Counted Loops
                   5381: @cindex counted loops
                   5382: @cindex loops, counted
                   5383: @cindex @code{DO} loops
                   5384: 
                   5385: The basic counted loop is:
                   5386: @example
1.29      crook    5387: @i{limit} @i{start}
1.1       anton    5388: ?DO
1.29      crook    5389:   @i{body}
1.1       anton    5390: LOOP
                   5391: @end example
                   5392: 
1.29      crook    5393: This performs one iteration for every integer, starting from @i{start}
                   5394: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21      crook    5395: accessed with @code{i}. For example, the loop:
1.1       anton    5396: @example
                   5397: 10 0 ?DO
                   5398:   i .
                   5399: LOOP
                   5400: @end example
1.21      crook    5401: @noindent
                   5402: prints @code{0 1 2 3 4 5 6 7 8 9}
                   5403: 
1.1       anton    5404: The index of the innermost loop can be accessed with @code{i}, the index
                   5405: of the next loop with @code{j}, and the index of the third loop with
                   5406: @code{k}.
                   5407: 
1.44      crook    5408: 
1.1       anton    5409: doc-i
                   5410: doc-j
                   5411: doc-k
                   5412: 
1.44      crook    5413: 
1.1       anton    5414: The loop control data are kept on the return stack, so there are some
1.21      crook    5415: restrictions on mixing return stack accesses and counted loop words. In
                   5416: particuler, if you put values on the return stack outside the loop, you
                   5417: cannot read them inside the loop@footnote{well, not in a way that is
                   5418: portable.}. If you put values on the return stack within a loop, you
                   5419: have to remove them before the end of the loop and before accessing the
                   5420: index of the loop.
1.1       anton    5421: 
                   5422: There are several variations on the counted loop:
                   5423: 
1.21      crook    5424: @itemize @bullet
                   5425: @item
                   5426: @code{LEAVE} leaves the innermost counted loop immediately; execution
                   5427: continues after the associated @code{LOOP} or @code{NEXT}. For example:
                   5428: 
                   5429: @example
                   5430: 10 0 ?DO  i DUP . 3 = IF LEAVE THEN LOOP
                   5431: @end example
                   5432: prints @code{0 1 2 3}
                   5433: 
1.1       anton    5434: 
1.21      crook    5435: @item
                   5436: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
                   5437: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
                   5438: return stack so @code{EXIT} can get to its return address. For example:
                   5439: 
                   5440: @example
                   5441: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
                   5442: @end example
                   5443: prints @code{0 1 2 3}
                   5444: 
                   5445: 
                   5446: @item
1.29      crook    5447: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1       anton    5448: (and @code{LOOP} iterates until they become equal by wrap-around
                   5449: arithmetic). This behaviour is usually not what you want. Therefore,
                   5450: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29      crook    5451: @code{?DO}), which do not enter the loop if @i{start} is greater than
                   5452: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1       anton    5453: unsigned loop parameters.
                   5454: 
1.21      crook    5455: @item
                   5456: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
                   5457: the loop, independent of the loop parameters. Do not use @code{DO}, even
                   5458: if you know that the loop is entered in any case. Such knowledge tends
                   5459: to become invalid during maintenance of a program, and then the
                   5460: @code{DO} will make trouble.
                   5461: 
                   5462: @item
1.29      crook    5463: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
                   5464: index by @i{n} instead of by 1. The loop is terminated when the border
                   5465: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1       anton    5466: 
1.21      crook    5467: @example
                   5468: 4 0 +DO  i .  2 +LOOP
                   5469: @end example
                   5470: @noindent
                   5471: prints @code{0 2}
                   5472: 
                   5473: @example
                   5474: 4 1 +DO  i .  2 +LOOP
                   5475: @end example
                   5476: @noindent
                   5477: prints @code{1 3}
1.1       anton    5478: 
1.68      anton    5479: @item
1.1       anton    5480: @cindex negative increment for counted loops
                   5481: @cindex counted loops with negative increment
1.29      crook    5482: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1       anton    5483: 
1.21      crook    5484: @example
                   5485: -1 0 ?DO  i .  -1 +LOOP
                   5486: @end example
                   5487: @noindent
                   5488: prints @code{0 -1}
1.1       anton    5489: 
1.21      crook    5490: @example
                   5491: 0 0 ?DO  i .  -1 +LOOP
                   5492: @end example
                   5493: prints nothing.
1.1       anton    5494: 
1.29      crook    5495: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
                   5496: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
                   5497: index by @i{u} each iteration. The loop is terminated when the border
                   5498: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1       anton    5499: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
                   5500: 
1.21      crook    5501: @example
                   5502: -2 0 -DO  i .  1 -LOOP
                   5503: @end example
                   5504: @noindent
                   5505: prints @code{0 -1}
1.1       anton    5506: 
1.21      crook    5507: @example
                   5508: -1 0 -DO  i .  1 -LOOP
                   5509: @end example
                   5510: @noindent
                   5511: prints @code{0}
                   5512: 
                   5513: @example
                   5514: 0 0 -DO  i .  1 -LOOP
                   5515: @end example
                   5516: @noindent
                   5517: prints nothing.
1.1       anton    5518: 
1.21      crook    5519: @end itemize
1.1       anton    5520: 
                   5521: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26      crook    5522: @code{-LOOP} are not defined in ANS Forth. However, an implementation
                   5523: for these words that uses only standard words is provided in
                   5524: @file{compat/loops.fs}.
1.1       anton    5525: 
                   5526: 
                   5527: @cindex @code{FOR} loops
1.26      crook    5528: Another counted loop is:
1.1       anton    5529: @example
1.29      crook    5530: @i{n}
1.1       anton    5531: FOR
1.29      crook    5532:   @i{body}
1.1       anton    5533: NEXT
                   5534: @end example
                   5535: This is the preferred loop of native code compiler writers who are too
1.26      crook    5536: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29      crook    5537: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
                   5538: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26      crook    5539: Forth systems may behave differently, even if they support @code{FOR}
                   5540: loops. To avoid problems, don't use @code{FOR} loops.
1.1       anton    5541: 
                   5542: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
                   5543: @subsection Arbitrary control structures
                   5544: @cindex control structures, user-defined
                   5545: 
                   5546: @cindex control-flow stack
                   5547: ANS Forth permits and supports using control structures in a non-nested
                   5548: way. Information about incomplete control structures is stored on the
                   5549: control-flow stack. This stack may be implemented on the Forth data
                   5550: stack, and this is what we have done in Gforth.
                   5551: 
                   5552: @cindex @code{orig}, control-flow stack item
                   5553: @cindex @code{dest}, control-flow stack item
                   5554: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
                   5555: entry represents a backward branch target. A few words are the basis for
                   5556: building any control structure possible (except control structures that
                   5557: need storage, like calls, coroutines, and backtracking).
                   5558: 
1.44      crook    5559: 
1.1       anton    5560: doc-if
                   5561: doc-ahead
                   5562: doc-then
                   5563: doc-begin
                   5564: doc-until
                   5565: doc-again
                   5566: doc-cs-pick
                   5567: doc-cs-roll
                   5568: 
1.44      crook    5569: 
1.21      crook    5570: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
                   5571: manipulate the control-flow stack in a portable way. Without them, you
                   5572: would need to know how many stack items are occupied by a control-flow
                   5573: entry (many systems use one cell. In Gforth they currently take three,
                   5574: but this may change in the future).
                   5575: 
1.1       anton    5576: Some standard control structure words are built from these words:
                   5577: 
1.44      crook    5578: 
1.1       anton    5579: doc-else
                   5580: doc-while
                   5581: doc-repeat
                   5582: 
1.44      crook    5583: 
                   5584: @noindent
1.1       anton    5585: Gforth adds some more control-structure words:
                   5586: 
1.44      crook    5587: 
1.1       anton    5588: doc-endif
                   5589: doc-?dup-if
                   5590: doc-?dup-0=-if
                   5591: 
1.44      crook    5592: 
                   5593: @noindent
1.1       anton    5594: Counted loop words constitute a separate group of words:
                   5595: 
1.44      crook    5596: 
1.1       anton    5597: doc-?do
                   5598: doc-+do
                   5599: doc-u+do
                   5600: doc--do
                   5601: doc-u-do
                   5602: doc-do
                   5603: doc-for
                   5604: doc-loop
                   5605: doc-+loop
                   5606: doc--loop
                   5607: doc-next
                   5608: doc-leave
                   5609: doc-?leave
                   5610: doc-unloop
                   5611: doc-done
                   5612: 
1.44      crook    5613: 
1.21      crook    5614: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
                   5615: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1       anton    5616: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
                   5617: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
                   5618: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
                   5619: resolved (by using one of the loop-ending words or @code{DONE}).
                   5620: 
1.44      crook    5621: @noindent
1.26      crook    5622: Another group of control structure words are:
1.1       anton    5623: 
1.44      crook    5624: 
1.1       anton    5625: doc-case
                   5626: doc-endcase
                   5627: doc-of
                   5628: doc-endof
                   5629: 
1.44      crook    5630: 
1.21      crook    5631: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
                   5632: @code{CS-ROLL}.
1.1       anton    5633: 
                   5634: @subsubsection Programming Style
1.47      crook    5635: @cindex control structures programming style
                   5636: @cindex programming style, arbitrary control structures
1.1       anton    5637: 
                   5638: In order to ensure readability we recommend that you do not create
                   5639: arbitrary control structures directly, but define new control structure
                   5640: words for the control structure you want and use these words in your
1.26      crook    5641: program. For example, instead of writing:
1.1       anton    5642: 
                   5643: @example
1.26      crook    5644: BEGIN
1.1       anton    5645:   ...
1.26      crook    5646: IF [ 1 CS-ROLL ]
1.1       anton    5647:   ...
1.26      crook    5648: AGAIN THEN
1.1       anton    5649: @end example
                   5650: 
1.21      crook    5651: @noindent
1.1       anton    5652: we recommend defining control structure words, e.g.,
                   5653: 
                   5654: @example
1.26      crook    5655: : WHILE ( DEST -- ORIG DEST )
                   5656:  POSTPONE IF
                   5657:  1 CS-ROLL ; immediate
                   5658: 
                   5659: : REPEAT ( orig dest -- )
                   5660:  POSTPONE AGAIN
                   5661:  POSTPONE THEN ; immediate
1.1       anton    5662: @end example
                   5663: 
1.21      crook    5664: @noindent
1.1       anton    5665: and then using these to create the control structure:
                   5666: 
                   5667: @example
1.26      crook    5668: BEGIN
1.1       anton    5669:   ...
1.26      crook    5670: WHILE
1.1       anton    5671:   ...
1.26      crook    5672: REPEAT
1.1       anton    5673: @end example
                   5674: 
                   5675: That's much easier to read, isn't it? Of course, @code{REPEAT} and
                   5676: @code{WHILE} are predefined, so in this example it would not be
                   5677: necessary to define them.
                   5678: 
                   5679: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
                   5680: @subsection Calls and returns
                   5681: @cindex calling a definition
                   5682: @cindex returning from a definition
                   5683: 
1.3       anton    5684: @cindex recursive definitions
                   5685: A definition can be called simply be writing the name of the definition
1.26      crook    5686: to be called. Normally a definition is invisible during its own
1.3       anton    5687: definition. If you want to write a directly recursive definition, you
1.26      crook    5688: can use @code{recursive} to make the current definition visible, or
                   5689: @code{recurse} to call the current definition directly.
1.3       anton    5690: 
1.44      crook    5691: 
1.3       anton    5692: doc-recursive
                   5693: doc-recurse
                   5694: 
1.44      crook    5695: 
1.21      crook    5696: @comment TODO add example of the two recursion methods
1.12      anton    5697: @quotation
                   5698: @progstyle
                   5699: I prefer using @code{recursive} to @code{recurse}, because calling the
                   5700: definition by name is more descriptive (if the name is well-chosen) than
                   5701: the somewhat cryptic @code{recurse}.  E.g., in a quicksort
                   5702: implementation, it is much better to read (and think) ``now sort the
                   5703: partitions'' than to read ``now do a recursive call''.
                   5704: @end quotation
1.3       anton    5705: 
1.29      crook    5706: For mutual recursion, use @code{Defer}red words, like this:
1.3       anton    5707: 
                   5708: @example
1.28      crook    5709: Defer foo
1.3       anton    5710: 
                   5711: : bar ( ... -- ... )
                   5712:  ... foo ... ;
                   5713: 
                   5714: :noname ( ... -- ... )
                   5715:  ... bar ... ;
                   5716: IS foo
                   5717: @end example
                   5718: 
1.170     pazsan   5719: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33      anton    5720: 
1.26      crook    5721: The current definition returns control to the calling definition when
1.33      anton    5722: the end of the definition is reached or @code{EXIT} is encountered.
1.1       anton    5723: 
                   5724: doc-exit
                   5725: doc-;s
                   5726: 
1.44      crook    5727: 
1.1       anton    5728: @node Exception Handling,  , Calls and returns, Control Structures
                   5729: @subsection Exception Handling
1.26      crook    5730: @cindex exceptions
1.1       anton    5731: 
1.68      anton    5732: @c quit is a very bad idea for error handling, 
                   5733: @c because it does not translate into a THROW
                   5734: @c it also does not belong into this chapter
                   5735: 
                   5736: If a word detects an error condition that it cannot handle, it can
                   5737: @code{throw} an exception.  In the simplest case, this will terminate
                   5738: your program, and report an appropriate error.
1.21      crook    5739: 
1.68      anton    5740: doc-throw
1.1       anton    5741: 
1.69      anton    5742: @code{Throw} consumes a cell-sized error number on the stack. There are
                   5743: some predefined error numbers in ANS Forth (see @file{errors.fs}).  In
                   5744: Gforth (and most other systems) you can use the iors produced by various
                   5745: words as error numbers (e.g., a typical use of @code{allocate} is
                   5746: @code{allocate throw}).  Gforth also provides the word @code{exception}
                   5747: to define your own error numbers (with decent error reporting); an ANS
                   5748: Forth version of this word (but without the error messages) is available
                   5749: in @code{compat/except.fs}.  And finally, you can use your own error
1.68      anton    5750: numbers (anything outside the range -4095..0), but won't get nice error
                   5751: messages, only numbers.  For example, try:
                   5752: 
                   5753: @example
1.69      anton    5754: -10 throw                    \ ANS defined
                   5755: -267 throw                   \ system defined
                   5756: s" my error" exception throw \ user defined
                   5757: 7 throw                      \ arbitrary number
1.68      anton    5758: @end example
                   5759: 
                   5760: doc---exception-exception
1.1       anton    5761: 
1.69      anton    5762: A common idiom to @code{THROW} a specific error if a flag is true is
                   5763: this:
                   5764: 
                   5765: @example
                   5766: @code{( flag ) 0<> @i{errno} and throw}
                   5767: @end example
                   5768: 
                   5769: Your program can provide exception handlers to catch exceptions.  An
                   5770: exception handler can be used to correct the problem, or to clean up
                   5771: some data structures and just throw the exception to the next exception
                   5772: handler.  Note that @code{throw} jumps to the dynamically innermost
                   5773: exception handler.  The system's exception handler is outermost, and just
                   5774: prints an error and restarts command-line interpretation (or, in batch
                   5775: mode (i.e., while processing the shell command line), leaves Gforth).
1.1       anton    5776: 
1.68      anton    5777: The ANS Forth way to catch exceptions is @code{catch}:
1.1       anton    5778: 
1.68      anton    5779: doc-catch
1.160     anton    5780: doc-nothrow
1.68      anton    5781: 
                   5782: The most common use of exception handlers is to clean up the state when
                   5783: an error happens.  E.g.,
1.1       anton    5784: 
1.26      crook    5785: @example
1.68      anton    5786: base @ >r hex \ actually the hex should be inside foo, or we h
                   5787: ['] foo catch ( nerror|0 )
                   5788: r> base !
1.69      anton    5789: ( nerror|0 ) throw \ pass it on
1.26      crook    5790: @end example
1.1       anton    5791: 
1.69      anton    5792: A use of @code{catch} for handling the error @code{myerror} might look
                   5793: like this:
1.44      crook    5794: 
1.68      anton    5795: @example
1.69      anton    5796: ['] foo catch
                   5797: CASE
1.160     anton    5798:   myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5799:   dup throw \ default: pass other errors on, do nothing on non-errors
                   5800: ENDCASE
1.68      anton    5801: @end example
1.44      crook    5802: 
1.68      anton    5803: Having to wrap the code into a separate word is often cumbersome,
                   5804: therefore Gforth provides an alternative syntax:
1.1       anton    5805: 
                   5806: @example
1.69      anton    5807: TRY
1.68      anton    5808:   @i{code1}
1.172     anton    5809:   IFERROR
                   5810:     @i{code2}
                   5811:   THEN
                   5812:   @i{code3}
1.69      anton    5813: ENDTRY
1.1       anton    5814: @end example
                   5815: 
1.172     anton    5816: This performs @i{code1}.  If @i{code1} completes normally, execution
                   5817: continues with @i{code3}.  If @i{code1} or there is an exception
                   5818: before @code{endtry}, the stacks are reset to the state during
                   5819: @code{try}, the throw value is pushed on the data stack, and execution
                   5820: constinues at @i{code2}, and finally falls through the @i{code3}.
1.26      crook    5821: 
1.68      anton    5822: doc-try
                   5823: doc-endtry
1.172     anton    5824: doc-iferror
                   5825: 
                   5826: If you don't need @i{code2}, you can write @code{restore} instead of
                   5827: @code{iferror then}:
                   5828: 
                   5829: @example
                   5830: TRY
                   5831:   @i{code1}
                   5832: RESTORE
                   5833:   @i{code3}
                   5834: ENDTRY
                   5835: @end example
1.26      crook    5836: 
1.172     anton    5837: @cindex unwind-protect
1.69      anton    5838: The cleanup example from above in this syntax:
1.26      crook    5839: 
1.68      anton    5840: @example
1.174     anton    5841: base @@ @{ oldbase @}
1.172     anton    5842: TRY
1.68      anton    5843:   hex foo \ now the hex is placed correctly
1.69      anton    5844:   0       \ value for throw
1.172     anton    5845: RESTORE
                   5846:   oldbase base !
                   5847: ENDTRY
                   5848: throw
1.1       anton    5849: @end example
                   5850: 
1.172     anton    5851: An additional advantage of this variant is that an exception between
                   5852: @code{restore} and @code{endtry} (e.g., from the user pressing
                   5853: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
                   5854: so the base will be restored under all circumstances.
                   5855: 
                   5856: However, you have to ensure that this code does not cause an exception
                   5857: itself, otherwise the @code{iferror}/@code{restore} code will loop.
                   5858: Moreover, you should also make sure that the stack contents needed by
                   5859: the @code{iferror}/@code{restore} code exist everywhere between
                   5860: @code{try} and @code{endtry}; in our example this is achived by
                   5861: putting the data in a local before the @code{try} (you cannot use the
                   5862: return stack because the exception frame (@i{sys1}) is in the way
                   5863: there).
                   5864: 
                   5865: This kind of usage corresponds to Lisp's @code{unwind-protect}.
                   5866: 
                   5867: @cindex @code{recover} (old Gforth versions)
                   5868: If you do not want this exception-restarting behaviour, you achieve
                   5869: this as follows:
                   5870: 
                   5871: @example
                   5872: TRY
                   5873:   @i{code1}
                   5874: ENDTRY-IFERROR
                   5875:   @i{code2}
                   5876: THEN
                   5877: @end example
                   5878: 
                   5879: If there is an exception in @i{code1}, then @i{code2} is executed,
                   5880: otherwise execution continues behind the @code{then} (or in a possible
                   5881: @code{else} branch).  This corresponds to the construct
                   5882: 
                   5883: @example
                   5884: TRY
                   5885:   @i{code1}
                   5886: RECOVER
                   5887:   @i{code2}
                   5888: ENDTRY
                   5889: @end example
                   5890: 
                   5891: in Gforth before version 0.7.  So you can directly replace
                   5892: @code{recover}-using code; however, we recommend that you check if it
                   5893: would not be better to use one of the other @code{try} variants while
                   5894: you are at it.
                   5895: 
1.173     anton    5896: To ease the transition, Gforth provides two compatibility files:
                   5897: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
                   5898: ... then} syntax (but not @code{iferror} or @code{restore}) for old
                   5899: systems; @file{recover-endtry.fs} provides the @code{try ... recover
                   5900: ... endtry} syntax on new systems, so you can use that file as a
                   5901: stopgap to run old programs.  Both files work on any system (they just
                   5902: do nothing if the system already has the syntax it implements), so you
                   5903: can unconditionally @code{require} one of these files, even if you use
                   5904: a mix old and new systems.
                   5905: 
1.172     anton    5906: doc-restore
                   5907: doc-endtry-iferror
                   5908: 
                   5909: Here's the error handling example:
1.1       anton    5910: 
1.68      anton    5911: @example
1.69      anton    5912: TRY
1.68      anton    5913:   foo
1.172     anton    5914: ENDTRY-IFERROR
1.69      anton    5915:   CASE
1.160     anton    5916:     myerror OF ... ( do something about it ) nothrow ENDOF
1.69      anton    5917:     throw \ pass other errors on
                   5918:   ENDCASE
1.172     anton    5919: THEN
1.68      anton    5920: @end example
1.1       anton    5921: 
1.69      anton    5922: @progstyle
                   5923: As usual, you should ensure that the stack depth is statically known at
                   5924: the end: either after the @code{throw} for passing on errors, or after
                   5925: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
                   5926: selection construct for handling the error).
                   5927: 
1.68      anton    5928: There are two alternatives to @code{throw}: @code{Abort"} is conditional
                   5929: and you can provide an error message.  @code{Abort} just produces an
                   5930: ``Aborted'' error.
1.1       anton    5931: 
1.68      anton    5932: The problem with these words is that exception handlers cannot
                   5933: differentiate between different @code{abort"}s; they just look like
                   5934: @code{-2 throw} to them (the error message cannot be accessed by
                   5935: standard programs).  Similar @code{abort} looks like @code{-1 throw} to
                   5936: exception handlers.
1.44      crook    5937: 
1.68      anton    5938: doc-abort"
1.26      crook    5939: doc-abort
1.29      crook    5940: 
                   5941: 
1.44      crook    5942: 
1.29      crook    5943: @c -------------------------------------------------------------
1.47      crook    5944: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29      crook    5945: @section Defining Words
                   5946: @cindex defining words
                   5947: 
1.47      crook    5948: Defining words are used to extend Forth by creating new entries in the dictionary.
                   5949: 
1.29      crook    5950: @menu
1.67      anton    5951: * CREATE::                      
1.44      crook    5952: * Variables::                   Variables and user variables
1.67      anton    5953: * Constants::                   
1.44      crook    5954: * Values::                      Initialised variables
1.67      anton    5955: * Colon Definitions::           
1.44      crook    5956: * Anonymous Definitions::       Definitions without names
1.69      anton    5957: * Supplying names::             Passing definition names as strings
1.67      anton    5958: * User-defined Defining Words::  
1.170     pazsan   5959: * Deferred Words::              Allow forward references
1.67      anton    5960: * Aliases::                     
1.29      crook    5961: @end menu
                   5962: 
1.44      crook    5963: @node CREATE, Variables, Defining Words, Defining Words
                   5964: @subsection @code{CREATE}
1.29      crook    5965: @cindex simple defining words
                   5966: @cindex defining words, simple
                   5967: 
                   5968: Defining words are used to create new entries in the dictionary. The
                   5969: simplest defining word is @code{CREATE}. @code{CREATE} is used like
                   5970: this:
                   5971: 
                   5972: @example
                   5973: CREATE new-word1
                   5974: @end example
                   5975: 
1.69      anton    5976: @code{CREATE} is a parsing word, i.e., it takes an argument from the
                   5977: input stream (@code{new-word1} in our example).  It generates a
                   5978: dictionary entry for @code{new-word1}. When @code{new-word1} is
                   5979: executed, all that it does is leave an address on the stack. The address
                   5980: represents the value of the data space pointer (@code{HERE}) at the time
                   5981: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
                   5982: associating a name with the address of a region of memory.
1.29      crook    5983: 
1.34      anton    5984: doc-create
                   5985: 
1.69      anton    5986: Note that in ANS Forth guarantees only for @code{create} that its body
                   5987: is in dictionary data space (i.e., where @code{here}, @code{allot}
                   5988: etc. work, @pxref{Dictionary allocation}).  Also, in ANS Forth only
                   5989: @code{create}d words can be modified with @code{does>}
                   5990: (@pxref{User-defined Defining Words}).  And in ANS Forth @code{>body}
                   5991: can only be applied to @code{create}d words.
                   5992: 
1.29      crook    5993: By extending this example to reserve some memory in data space, we end
1.69      anton    5994: up with something like a @i{variable}. Here are two different ways to do
                   5995: it:
1.29      crook    5996: 
                   5997: @example
                   5998: CREATE new-word2 1 cells allot  \ reserve 1 cell - initial value undefined
                   5999: CREATE new-word3 4 ,            \ reserve 1 cell and initialise it (to 4)
                   6000: @end example
                   6001: 
                   6002: The variable can be examined and modified using @code{@@} (``fetch'') and
                   6003: @code{!} (``store'') like this:
                   6004: 
                   6005: @example
                   6006: new-word2 @@ .      \ get address, fetch from it and display
                   6007: 1234 new-word2 !   \ new value, get address, store to it
                   6008: @end example
                   6009: 
1.44      crook    6010: @cindex arrays
                   6011: A similar mechanism can be used to create arrays. For example, an
                   6012: 80-character text input buffer:
1.29      crook    6013: 
                   6014: @example
1.44      crook    6015: CREATE text-buf 80 chars allot
                   6016: 
1.168     anton    6017: text-buf 0 chars + c@@ \ the 1st character (offset 0)
                   6018: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44      crook    6019: @end example
1.29      crook    6020: 
1.44      crook    6021: You can build arbitrarily complex data structures by allocating
1.49      anton    6022: appropriate areas of memory. For further discussions of this, and to
1.66      anton    6023: learn about some Gforth tools that make it easier,
1.49      anton    6024: @xref{Structures}.
1.44      crook    6025: 
                   6026: 
                   6027: @node Variables, Constants, CREATE, Defining Words
                   6028: @subsection Variables
                   6029: @cindex variables
                   6030: 
                   6031: The previous section showed how a sequence of commands could be used to
                   6032: generate a variable.  As a final refinement, the whole code sequence can
                   6033: be wrapped up in a defining word (pre-empting the subject of the next
                   6034: section), making it easier to create new variables:
                   6035: 
                   6036: @example
                   6037: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
                   6038: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
                   6039: 
                   6040: myvariableX foo \ variable foo starts off with an unknown value
                   6041: myvariable0 joe \ whilst joe is initialised to 0
1.29      crook    6042: 
                   6043: 45 3 * foo !   \ set foo to 135
                   6044: 1234 joe !     \ set joe to 1234
                   6045: 3 joe +!       \ increment joe by 3.. to 1237
                   6046: @end example
                   6047: 
                   6048: Not surprisingly, there is no need to define @code{myvariable}, since
1.44      crook    6049: Forth already has a definition @code{Variable}. ANS Forth does not
1.69      anton    6050: guarantee that a @code{Variable} is initialised when it is created
                   6051: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
                   6052: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
                   6053: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47      crook    6054: @code{fvariable} for double and floating-point variables, respectively
1.69      anton    6055: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47      crook    6056: store a boolean, you can use @code{on} and @code{off} to toggle its
                   6057: state.
1.29      crook    6058: 
1.34      anton    6059: doc-variable
                   6060: doc-2variable
                   6061: doc-fvariable
                   6062: 
1.29      crook    6063: @cindex user variables
                   6064: @cindex user space
                   6065: The defining word @code{User} behaves in the same way as @code{Variable}.
                   6066: The difference is that it reserves space in @i{user (data) space} rather
                   6067: than normal data space. In a Forth system that has a multi-tasker, each
                   6068: task has its own set of user variables.
                   6069: 
1.34      anton    6070: doc-user
1.67      anton    6071: @c doc-udp
                   6072: @c doc-uallot
1.34      anton    6073: 
1.29      crook    6074: @comment TODO is that stuff about user variables strictly correct? Is it
                   6075: @comment just terminal tasks that have user variables?
                   6076: @comment should document tasker.fs (with some examples) elsewhere
                   6077: @comment in this manual, then expand on user space and user variables.
                   6078: 
1.44      crook    6079: @node Constants, Values, Variables, Defining Words
                   6080: @subsection Constants
                   6081: @cindex constants
                   6082: 
                   6083: @code{Constant} allows you to declare a fixed value and refer to it by
                   6084: name. For example:
1.29      crook    6085: 
                   6086: @example
                   6087: 12 Constant INCHES-PER-FOOT
                   6088: 3E+08 fconstant SPEED-O-LIGHT
                   6089: @end example
                   6090: 
                   6091: A @code{Variable} can be both read and written, so its run-time
                   6092: behaviour is to supply an address through which its current value can be
                   6093: manipulated. In contrast, the value of a @code{Constant} cannot be
                   6094: changed once it has been declared@footnote{Well, often it can be -- but
                   6095: not in a Standard, portable way. It's safer to use a @code{Value} (read
                   6096: on).} so it's not necessary to supply the address -- it is more
                   6097: efficient to return the value of the constant directly. That's exactly
                   6098: what happens; the run-time effect of a constant is to put its value on
1.49      anton    6099: the top of the stack (You can find one
                   6100: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29      crook    6101: 
1.69      anton    6102: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29      crook    6103: double and floating-point constants, respectively.
                   6104: 
1.34      anton    6105: doc-constant
                   6106: doc-2constant
                   6107: doc-fconstant
                   6108: 
                   6109: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44      crook    6110: @c nac-> How could that not be true in an ANS Forth? You can't define a
                   6111: @c constant, use it and then delete the definition of the constant..
1.69      anton    6112: 
                   6113: @c anton->An ANS Forth system can compile a constant to a literal; On
                   6114: @c decompilation you would see only the number, just as if it had been used
                   6115: @c in the first place.  The word will stay, of course, but it will only be
                   6116: @c used by the text interpreter (no run-time duties, except when it is 
                   6117: @c POSTPONEd or somesuch).
                   6118: 
                   6119: @c nac:
1.44      crook    6120: @c I agree that it's rather deep, but IMO it is an important difference
                   6121: @c relative to other programming languages.. often it's annoying: it
                   6122: @c certainly changes my programming style relative to C.
                   6123: 
1.69      anton    6124: @c anton: In what way?
                   6125: 
1.29      crook    6126: Constants in Forth behave differently from their equivalents in other
                   6127: programming languages. In other languages, a constant (such as an EQU in
                   6128: assembler or a #define in C) only exists at compile-time; in the
                   6129: executable program the constant has been translated into an absolute
                   6130: number and, unless you are using a symbolic debugger, it's impossible to
                   6131: know what abstract thing that number represents. In Forth a constant has
1.44      crook    6132: an entry in the header space and remains there after the code that uses
                   6133: it has been defined. In fact, it must remain in the dictionary since it
                   6134: has run-time duties to perform. For example:
1.29      crook    6135: 
                   6136: @example
                   6137: 12 Constant INCHES-PER-FOOT
                   6138: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
                   6139: @end example
                   6140: 
                   6141: @cindex in-lining of constants
                   6142: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
                   6143: associated with the constant @code{INCHES-PER-FOOT}. If you use
                   6144: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
                   6145: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
                   6146: attempt to optimise constants by in-lining them where they are used. You
                   6147: can force Gforth to in-line a constant like this:
                   6148: 
                   6149: @example
                   6150: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
                   6151: @end example
                   6152: 
                   6153: If you use @code{see} to decompile @i{this} version of
                   6154: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49      anton    6155: longer present. To understand how this works, read
                   6156: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29      crook    6157: 
                   6158: In-lining constants in this way might improve execution time
                   6159: fractionally, and can ensure that a constant is now only referenced at
                   6160: compile-time. However, the definition of the constant still remains in
                   6161: the dictionary. Some Forth compilers provide a mechanism for controlling
                   6162: a second dictionary for holding transient words such that this second
                   6163: dictionary can be deleted later in order to recover memory
                   6164: space. However, there is no standard way of doing this.
                   6165: 
                   6166: 
1.44      crook    6167: @node Values, Colon Definitions, Constants, Defining Words
                   6168: @subsection Values
                   6169: @cindex values
1.34      anton    6170: 
1.69      anton    6171: A @code{Value} behaves like a @code{Constant}, but it can be changed.
                   6172: @code{TO} is a parsing word that changes a @code{Values}.  In Gforth
                   6173: (not in ANS Forth) you can access (and change) a @code{value} also with
                   6174: @code{>body}.
                   6175: 
                   6176: Here are some
                   6177: examples:
1.29      crook    6178: 
                   6179: @example
1.69      anton    6180: 12 Value APPLES     \ Define APPLES with an initial value of 12
                   6181: 34 TO APPLES        \ Change the value of APPLES. TO is a parsing word
                   6182: 1 ' APPLES >body +! \ Increment APPLES.  Non-standard usage.
                   6183: APPLES              \ puts 35 on the top of the stack.
1.29      crook    6184: @end example
                   6185: 
1.44      crook    6186: doc-value
                   6187: doc-to
1.29      crook    6188: 
1.35      anton    6189: 
1.69      anton    6190: 
1.44      crook    6191: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
                   6192: @subsection Colon Definitions
                   6193: @cindex colon definitions
1.35      anton    6194: 
                   6195: @example
1.44      crook    6196: : name ( ... -- ... )
                   6197:     word1 word2 word3 ;
1.29      crook    6198: @end example
                   6199: 
1.44      crook    6200: @noindent
                   6201: Creates a word called @code{name} that, upon execution, executes
                   6202: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29      crook    6203: 
1.49      anton    6204: The explanation above is somewhat superficial. For simple examples of
                   6205: colon definitions see @ref{Your first definition}.  For an in-depth
1.66      anton    6206: discussion of some of the issues involved, @xref{Interpretation and
1.49      anton    6207: Compilation Semantics}.
1.29      crook    6208: 
1.44      crook    6209: doc-:
                   6210: doc-;
1.1       anton    6211: 
1.34      anton    6212: 
1.69      anton    6213: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44      crook    6214: @subsection Anonymous Definitions
                   6215: @cindex colon definitions
                   6216: @cindex defining words without name
1.34      anton    6217: 
1.44      crook    6218: Sometimes you want to define an @dfn{anonymous word}; a word without a
                   6219: name. You can do this with:
1.1       anton    6220: 
1.44      crook    6221: doc-:noname
1.1       anton    6222: 
1.44      crook    6223: This leaves the execution token for the word on the stack after the
                   6224: closing @code{;}. Here's an example in which a deferred word is
                   6225: initialised with an @code{xt} from an anonymous colon definition:
1.1       anton    6226: 
1.29      crook    6227: @example
1.44      crook    6228: Defer deferred
                   6229: :noname ( ... -- ... )
                   6230:   ... ;
                   6231: IS deferred
1.29      crook    6232: @end example
1.26      crook    6233: 
1.44      crook    6234: @noindent
                   6235: Gforth provides an alternative way of doing this, using two separate
                   6236: words:
1.27      crook    6237: 
1.44      crook    6238: doc-noname
                   6239: @cindex execution token of last defined word
1.116     anton    6240: doc-latestxt
1.1       anton    6241: 
1.44      crook    6242: @noindent
                   6243: The previous example can be rewritten using @code{noname} and
1.116     anton    6244: @code{latestxt}:
1.1       anton    6245: 
1.26      crook    6246: @example
1.44      crook    6247: Defer deferred
                   6248: noname : ( ... -- ... )
                   6249:   ... ;
1.116     anton    6250: latestxt IS deferred
1.26      crook    6251: @end example
1.1       anton    6252: 
1.29      crook    6253: @noindent
1.44      crook    6254: @code{noname} works with any defining word, not just @code{:}.
                   6255: 
1.116     anton    6256: @code{latestxt} also works when the last word was not defined as
1.71      anton    6257: @code{noname}.  It does not work for combined words, though.  It also has
                   6258: the useful property that is is valid as soon as the header for a
                   6259: definition has been built. Thus:
1.44      crook    6260: 
                   6261: @example
1.116     anton    6262: latestxt . : foo [ latestxt . ] ; ' foo .
1.44      crook    6263: @end example
1.1       anton    6264: 
1.44      crook    6265: @noindent
                   6266: prints 3 numbers; the last two are the same.
1.26      crook    6267: 
1.69      anton    6268: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
                   6269: @subsection Supplying the name of a defined word
                   6270: @cindex names for defined words
                   6271: @cindex defining words, name given in a string
                   6272: 
                   6273: By default, a defining word takes the name for the defined word from the
                   6274: input stream. Sometimes you want to supply the name from a string. You
                   6275: can do this with:
                   6276: 
                   6277: doc-nextname
                   6278: 
                   6279: For example:
                   6280: 
                   6281: @example
                   6282: s" foo" nextname create
                   6283: @end example
                   6284: 
                   6285: @noindent
                   6286: is equivalent to:
                   6287: 
                   6288: @example
                   6289: create foo
                   6290: @end example
                   6291: 
                   6292: @noindent
                   6293: @code{nextname} works with any defining word.
                   6294: 
1.1       anton    6295: 
1.170     pazsan   6296: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26      crook    6297: @subsection User-defined Defining Words
                   6298: @cindex user-defined defining words
                   6299: @cindex defining words, user-defined
1.1       anton    6300: 
1.29      crook    6301: You can create a new defining word by wrapping defining-time code around
                   6302: an existing defining word and putting the sequence in a colon
1.69      anton    6303: definition. 
                   6304: 
                   6305: @c anton: This example is very complex and leads in a quite different
                   6306: @c direction from the CREATE-DOES> stuff that follows.  It should probably
                   6307: @c be done elsewhere, or as a subsubsection of this subsection (or as a
                   6308: @c subsection of Defining Words)
                   6309: 
                   6310: For example, suppose that you have a word @code{stats} that
1.29      crook    6311: gathers statistics about colon definitions given the @i{xt} of the
                   6312: definition, and you want every colon definition in your application to
                   6313: make a call to @code{stats}. You can define and use a new version of
                   6314: @code{:} like this:
                   6315: 
                   6316: @example
                   6317: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
                   6318:   ... ;  \ other code
                   6319: 
1.116     anton    6320: : my: : latestxt postpone literal ['] stats compile, ;
1.29      crook    6321: 
                   6322: my: foo + - ;
                   6323: @end example
                   6324: 
                   6325: When @code{foo} is defined using @code{my:} these steps occur:
                   6326: 
                   6327: @itemize @bullet
                   6328: @item
                   6329: @code{my:} is executed.
                   6330: @item
                   6331: The @code{:} within the definition (the one between @code{my:} and
1.116     anton    6332: @code{latestxt}) is executed, and does just what it always does; it parses
1.29      crook    6333: the input stream for a name, builds a dictionary header for the name
                   6334: @code{foo} and switches @code{state} from interpret to compile.
                   6335: @item
1.116     anton    6336: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29      crook    6337: being defined -- @code{foo} -- onto the stack.
                   6338: @item
                   6339: The code that was produced by @code{postpone literal} is executed; this
                   6340: causes the value on the stack to be compiled as a literal in the code
                   6341: area of @code{foo}.
                   6342: @item
                   6343: The code @code{['] stats} compiles a literal into the definition of
                   6344: @code{my:}. When @code{compile,} is executed, that literal -- the
                   6345: execution token for @code{stats} -- is layed down in the code area of
                   6346: @code{foo} , following the literal@footnote{Strictly speaking, the
                   6347: mechanism that @code{compile,} uses to convert an @i{xt} into something
                   6348: in the code area is implementation-dependent. A threaded implementation
                   6349: might spit out the execution token directly whilst another
                   6350: implementation might spit out a native code sequence.}.
                   6351: @item
                   6352: At this point, the execution of @code{my:} is complete, and control
                   6353: returns to the text interpreter. The text interpreter is in compile
                   6354: state, so subsequent text @code{+ -} is compiled into the definition of
                   6355: @code{foo} and the @code{;} terminates the definition as always.
                   6356: @end itemize
                   6357: 
                   6358: You can use @code{see} to decompile a word that was defined using
                   6359: @code{my:} and see how it is different from a normal @code{:}
                   6360: definition. For example:
                   6361: 
                   6362: @example
                   6363: : bar + - ;  \ like foo but using : rather than my:
                   6364: see bar
                   6365: : bar
                   6366:   + - ;
                   6367: see foo
                   6368: : foo
                   6369:   107645672 stats + - ;
                   6370: 
1.140     anton    6371: \ use ' foo . to show that 107645672 is the xt for foo
1.29      crook    6372: @end example
                   6373: 
                   6374: You can use techniques like this to make new defining words in terms of
                   6375: @i{any} existing defining word.
1.1       anton    6376: 
                   6377: 
1.29      crook    6378: @cindex defining defining words
1.26      crook    6379: @cindex @code{CREATE} ... @code{DOES>}
                   6380: If you want the words defined with your defining words to behave
                   6381: differently from words defined with standard defining words, you can
                   6382: write your defining word like this:
1.1       anton    6383: 
                   6384: @example
1.26      crook    6385: : def-word ( "name" -- )
1.29      crook    6386:     CREATE @i{code1}
1.26      crook    6387: DOES> ( ... -- ... )
1.29      crook    6388:     @i{code2} ;
1.26      crook    6389: 
                   6390: def-word name
1.1       anton    6391: @end example
                   6392: 
1.29      crook    6393: @cindex child words
                   6394: This fragment defines a @dfn{defining word} @code{def-word} and then
                   6395: executes it.  When @code{def-word} executes, it @code{CREATE}s a new
                   6396: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
                   6397: is not executed at this time. The word @code{name} is sometimes called a
                   6398: @dfn{child} of @code{def-word}.
                   6399: 
                   6400: When you execute @code{name}, the address of the body of @code{name} is
                   6401: put on the data stack and @i{code2} is executed (the address of the body
                   6402: of @code{name} is the address @code{HERE} returns immediately after the
1.69      anton    6403: @code{CREATE}, i.e., the address a @code{create}d word returns by
                   6404: default).
                   6405: 
                   6406: @c anton:
                   6407: @c www.dictionary.com says:
                   6408: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
                   6409: @c several generations of absence, usually caused by the chance
                   6410: @c recombination of genes.  2.An individual or a part that exhibits
                   6411: @c atavism. Also called throwback.  3.The return of a trait or recurrence
                   6412: @c of previous behavior after a period of absence.
                   6413: @c
                   6414: @c Doesn't seem to fit.
1.29      crook    6415: 
1.69      anton    6416: @c @cindex atavism in child words
1.33      anton    6417: You can use @code{def-word} to define a set of child words that behave
1.69      anton    6418: similarly; they all have a common run-time behaviour determined by
                   6419: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
                   6420: body of the child word. The structure of the data is common to all
                   6421: children of @code{def-word}, but the data values are specific -- and
                   6422: private -- to each child word. When a child word is executed, the
                   6423: address of its private data area is passed as a parameter on TOS to be
                   6424: used and manipulated@footnote{It is legitimate both to read and write to
                   6425: this data area.} by @i{code2}.
1.29      crook    6426: 
                   6427: The two fragments of code that make up the defining words act (are
                   6428: executed) at two completely separate times:
1.1       anton    6429: 
1.29      crook    6430: @itemize @bullet
                   6431: @item
                   6432: At @i{define time}, the defining word executes @i{code1} to generate a
                   6433: child word
                   6434: @item
                   6435: At @i{child execution time}, when a child word is invoked, @i{code2}
                   6436: is executed, using parameters (data) that are private and specific to
                   6437: the child word.
                   6438: @end itemize
                   6439: 
1.44      crook    6440: Another way of understanding the behaviour of @code{def-word} and
                   6441: @code{name} is to say that, if you make the following definitions:
1.33      anton    6442: @example
                   6443: : def-word1 ( "name" -- )
                   6444:     CREATE @i{code1} ;
                   6445: 
                   6446: : action1 ( ... -- ... )
                   6447:     @i{code2} ;
                   6448: 
                   6449: def-word1 name1
                   6450: @end example
                   6451: 
1.44      crook    6452: @noindent
                   6453: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1       anton    6454: 
1.29      crook    6455: The classic example is that you can define @code{CONSTANT} in this way:
1.26      crook    6456: 
1.1       anton    6457: @example
1.29      crook    6458: : CONSTANT ( w "name" -- )
                   6459:     CREATE ,
1.26      crook    6460: DOES> ( -- w )
                   6461:     @@ ;
1.1       anton    6462: @end example
                   6463: 
1.29      crook    6464: @comment There is a beautiful description of how this works and what
                   6465: @comment it does in the Forthwrite 100th edition.. as well as an elegant
                   6466: @comment commentary on the Counting Fruits problem.
                   6467: 
                   6468: When you create a constant with @code{5 CONSTANT five}, a set of
                   6469: define-time actions take place; first a new word @code{five} is created,
                   6470: then the value 5 is laid down in the body of @code{five} with
1.44      crook    6471: @code{,}. When @code{five} is executed, the address of the body is put on
1.29      crook    6472: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
                   6473: no code of its own; it simply contains a data field and a pointer to the
                   6474: code that follows @code{DOES>} in its defining word. That makes words
                   6475: created in this way very compact.
                   6476: 
                   6477: The final example in this section is intended to remind you that space
                   6478: reserved in @code{CREATE}d words is @i{data} space and therefore can be
                   6479: both read and written by a Standard program@footnote{Exercise: use this
                   6480: example as a starting point for your own implementation of @code{Value}
                   6481: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
                   6482: @code{[']}.}:
                   6483: 
                   6484: @example
                   6485: : foo ( "name" -- )
                   6486:     CREATE -1 ,
                   6487: DOES> ( -- )
1.33      anton    6488:     @@ . ;
1.29      crook    6489: 
                   6490: foo first-word
                   6491: foo second-word
                   6492: 
                   6493: 123 ' first-word >BODY !
                   6494: @end example
                   6495: 
                   6496: If @code{first-word} had been a @code{CREATE}d word, we could simply
                   6497: have executed it to get the address of its data field. However, since it
                   6498: was defined to have @code{DOES>} actions, its execution semantics are to
                   6499: perform those @code{DOES>} actions. To get the address of its data field
                   6500: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
                   6501: translate the xt into the address of the data field.  When you execute
                   6502: @code{first-word}, it will display @code{123}. When you execute
                   6503: @code{second-word} it will display @code{-1}.
1.26      crook    6504: 
                   6505: @cindex stack effect of @code{DOES>}-parts
                   6506: @cindex @code{DOES>}-parts, stack effect
1.29      crook    6507: In the examples above the stack comment after the @code{DOES>} specifies
1.26      crook    6508: the stack effect of the defined words, not the stack effect of the
                   6509: following code (the following code expects the address of the body on
                   6510: the top of stack, which is not reflected in the stack comment). This is
                   6511: the convention that I use and recommend (it clashes a bit with using
                   6512: locals declarations for stack effect specification, though).
1.1       anton    6513: 
1.53      anton    6514: @menu
                   6515: * CREATE..DOES> applications::  
                   6516: * CREATE..DOES> details::       
1.63      anton    6517: * Advanced does> usage example::  
1.155     anton    6518: * Const-does>::                 
1.53      anton    6519: @end menu
                   6520: 
                   6521: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26      crook    6522: @subsubsection Applications of @code{CREATE..DOES>}
                   6523: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1       anton    6524: 
1.26      crook    6525: You may wonder how to use this feature. Here are some usage patterns:
1.1       anton    6526: 
1.26      crook    6527: @cindex factoring similar colon definitions
                   6528: When you see a sequence of code occurring several times, and you can
                   6529: identify a meaning, you will factor it out as a colon definition. When
                   6530: you see similar colon definitions, you can factor them using
                   6531: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
                   6532: that look very similar:
1.1       anton    6533: @example
1.26      crook    6534: : ori, ( reg-target reg-source n -- )
                   6535:     0 asm-reg-reg-imm ;
                   6536: : andi, ( reg-target reg-source n -- )
                   6537:     1 asm-reg-reg-imm ;
1.1       anton    6538: @end example
                   6539: 
1.26      crook    6540: @noindent
                   6541: This could be factored with:
                   6542: @example
                   6543: : reg-reg-imm ( op-code -- )
                   6544:     CREATE ,
                   6545: DOES> ( reg-target reg-source n -- )
                   6546:     @@ asm-reg-reg-imm ;
                   6547: 
                   6548: 0 reg-reg-imm ori,
                   6549: 1 reg-reg-imm andi,
                   6550: @end example
1.1       anton    6551: 
1.26      crook    6552: @cindex currying
                   6553: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
                   6554: supply a part of the parameters for a word (known as @dfn{currying} in
                   6555: the functional language community). E.g., @code{+} needs two
                   6556: parameters. Creating versions of @code{+} with one parameter fixed can
                   6557: be done like this:
1.82      anton    6558: 
1.1       anton    6559: @example
1.82      anton    6560: : curry+ ( n1 "name" -- )
1.26      crook    6561:     CREATE ,
                   6562: DOES> ( n2 -- n1+n2 )
                   6563:     @@ + ;
                   6564: 
                   6565:  3 curry+ 3+
                   6566: -2 curry+ 2-
1.1       anton    6567: @end example
                   6568: 
1.91      anton    6569: 
1.63      anton    6570: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26      crook    6571: @subsubsection The gory details of @code{CREATE..DOES>}
                   6572: @cindex @code{CREATE} ... @code{DOES>}, details
1.1       anton    6573: 
1.26      crook    6574: doc-does>
1.1       anton    6575: 
1.26      crook    6576: @cindex @code{DOES>} in a separate definition
                   6577: This means that you need not use @code{CREATE} and @code{DOES>} in the
                   6578: same definition; you can put the @code{DOES>}-part in a separate
1.29      crook    6579: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26      crook    6580: @example
                   6581: : does1 
                   6582: DOES> ( ... -- ... )
1.44      crook    6583:     ... ;
                   6584: 
                   6585: : does2
                   6586: DOES> ( ... -- ... )
                   6587:     ... ;
                   6588: 
                   6589: : def-word ( ... -- ... )
                   6590:     create ...
                   6591:     IF
                   6592:        does1
                   6593:     ELSE
                   6594:        does2
                   6595:     ENDIF ;
                   6596: @end example
                   6597: 
                   6598: In this example, the selection of whether to use @code{does1} or
1.69      anton    6599: @code{does2} is made at definition-time; at the time that the child word is
1.44      crook    6600: @code{CREATE}d.
                   6601: 
                   6602: @cindex @code{DOES>} in interpretation state
                   6603: In a standard program you can apply a @code{DOES>}-part only if the last
                   6604: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
                   6605: will override the behaviour of the last word defined in any case. In a
                   6606: standard program, you can use @code{DOES>} only in a colon
                   6607: definition. In Gforth, you can also use it in interpretation state, in a
                   6608: kind of one-shot mode; for example:
                   6609: @example
                   6610: CREATE name ( ... -- ... )
                   6611:   @i{initialization}
                   6612: DOES>
                   6613:   @i{code} ;
                   6614: @end example
                   6615: 
                   6616: @noindent
                   6617: is equivalent to the standard:
                   6618: @example
                   6619: :noname
                   6620: DOES>
                   6621:     @i{code} ;
                   6622: CREATE name EXECUTE ( ... -- ... )
                   6623:     @i{initialization}
                   6624: @end example
                   6625: 
1.53      anton    6626: doc->body
                   6627: 
1.152     pazsan   6628: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63      anton    6629: @subsubsection Advanced does> usage example
                   6630: 
                   6631: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
                   6632: for disassembling instructions, that follow a very repetetive scheme:
                   6633: 
                   6634: @example
                   6635: :noname @var{disasm-operands} s" @var{inst-name}" type ;
                   6636: @var{entry-num} cells @var{table} + !
                   6637: @end example
                   6638: 
                   6639: Of course, this inspires the idea to factor out the commonalities to
                   6640: allow a definition like
                   6641: 
                   6642: @example
                   6643: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
                   6644: @end example
                   6645: 
                   6646: The parameters @var{disasm-operands} and @var{table} are usually
1.69      anton    6647: correlated.  Moreover, before I wrote the disassembler, there already
                   6648: existed code that defines instructions like this:
1.63      anton    6649: 
                   6650: @example
                   6651: @var{entry-num} @var{inst-format} @var{inst-name}
                   6652: @end example
                   6653: 
                   6654: This code comes from the assembler and resides in
                   6655: @file{arch/mips/insts.fs}.
                   6656: 
                   6657: So I had to define the @var{inst-format} words that performed the scheme
                   6658: above when executed.  At first I chose to use run-time code-generation:
                   6659: 
                   6660: @example
                   6661: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
                   6662:   :noname Postpone @var{disasm-operands}
                   6663:   name Postpone sliteral Postpone type Postpone ;
                   6664:   swap cells @var{table} + ! ;
                   6665: @end example
                   6666: 
                   6667: Note that this supplies the other two parameters of the scheme above.
1.44      crook    6668: 
1.63      anton    6669: An alternative would have been to write this using
                   6670: @code{create}/@code{does>}:
                   6671: 
                   6672: @example
                   6673: : @var{inst-format} ( entry-num "name" -- )
                   6674:   here name string, ( entry-num c-addr ) \ parse and save "name"
                   6675:   noname create , ( entry-num )
1.116     anton    6676:   latestxt swap cells @var{table} + !
1.63      anton    6677: does> ( addr w -- )
                   6678:   \ disassemble instruction w at addr
                   6679:   @@ >r 
                   6680:   @var{disasm-operands}
                   6681:   r> count type ;
                   6682: @end example
                   6683: 
                   6684: Somehow the first solution is simpler, mainly because it's simpler to
                   6685: shift a string from definition-time to use-time with @code{sliteral}
                   6686: than with @code{string,} and friends.
                   6687: 
                   6688: I wrote a lot of words following this scheme and soon thought about
                   6689: factoring out the commonalities among them.  Note that this uses a
                   6690: two-level defining word, i.e., a word that defines ordinary defining
                   6691: words.
                   6692: 
                   6693: This time a solution involving @code{postpone} and friends seemed more
                   6694: difficult (try it as an exercise), so I decided to use a
                   6695: @code{create}/@code{does>} word; since I was already at it, I also used
                   6696: @code{create}/@code{does>} for the lower level (try using
                   6697: @code{postpone} etc. as an exercise), resulting in the following
                   6698: definition:
                   6699: 
                   6700: @example
                   6701: : define-format ( disasm-xt table-xt -- )
                   6702:     \ define an instruction format that uses disasm-xt for
                   6703:     \ disassembling and enters the defined instructions into table
                   6704:     \ table-xt
                   6705:     create 2,
                   6706: does> ( u "inst" -- )
                   6707:     \ defines an anonymous word for disassembling instruction inst,
                   6708:     \ and enters it as u-th entry into table-xt
                   6709:     2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
                   6710:     noname create 2,      \ define anonymous word
1.116     anton    6711:     execute latestxt swap ! \ enter xt of defined word into table-xt
1.63      anton    6712: does> ( addr w -- )
                   6713:     \ disassemble instruction w at addr
                   6714:     2@@ >r ( addr w disasm-xt R: c-addr )
                   6715:     execute ( R: c-addr ) \ disassemble operands
                   6716:     r> count type ; \ print name 
                   6717: @end example
                   6718: 
                   6719: Note that the tables here (in contrast to above) do the @code{cells +}
                   6720: by themselves (that's why you have to pass an xt).  This word is used in
                   6721: the following way:
                   6722: 
                   6723: @example
                   6724: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
                   6725: @end example
                   6726: 
1.71      anton    6727: As shown above, the defined instruction format is then used like this:
                   6728: 
                   6729: @example
                   6730: @var{entry-num} @var{inst-format} @var{inst-name}
                   6731: @end example
                   6732: 
1.63      anton    6733: In terms of currying, this kind of two-level defining word provides the
                   6734: parameters in three stages: first @var{disasm-operands} and @var{table},
                   6735: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
                   6736: the instruction to be disassembled.  
                   6737: 
                   6738: Of course this did not quite fit all the instruction format names used
                   6739: in @file{insts.fs}, so I had to define a few wrappers that conditioned
                   6740: the parameters into the right form.
                   6741: 
                   6742: If you have trouble following this section, don't worry.  First, this is
                   6743: involved and takes time (and probably some playing around) to
                   6744: understand; second, this is the first two-level
                   6745: @code{create}/@code{does>} word I have written in seventeen years of
                   6746: Forth; and if I did not have @file{insts.fs} to start with, I may well
                   6747: have elected to use just a one-level defining word (with some repeating
                   6748: of parameters when using the defining word). So it is not necessary to
                   6749: understand this, but it may improve your understanding of Forth.
1.44      crook    6750: 
                   6751: 
1.152     pazsan   6752: @node Const-does>,  , Advanced does> usage example, User-defined Defining Words
1.91      anton    6753: @subsubsection @code{Const-does>}
                   6754: 
                   6755: A frequent use of @code{create}...@code{does>} is for transferring some
                   6756: values from definition-time to run-time.  Gforth supports this use with
                   6757: 
                   6758: doc-const-does>
                   6759: 
                   6760: A typical use of this word is:
                   6761: 
                   6762: @example
                   6763: : curry+ ( n1 "name" -- )
                   6764: 1 0 CONST-DOES> ( n2 -- n1+n2 )
                   6765:     + ;
                   6766: 
                   6767: 3 curry+ 3+
                   6768: @end example
                   6769: 
                   6770: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
                   6771: definition to run-time.
                   6772: 
                   6773: The advantages of using @code{const-does>} are:
                   6774: 
                   6775: @itemize
                   6776: 
                   6777: @item
                   6778: You don't have to deal with storing and retrieving the values, i.e.,
                   6779: your program becomes more writable and readable.
                   6780: 
                   6781: @item
                   6782: When using @code{does>}, you have to introduce a @code{@@} that cannot
                   6783: be optimized away (because you could change the data using
                   6784: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
                   6785: 
                   6786: @end itemize
                   6787: 
                   6788: An ANS Forth implementation of @code{const-does>} is available in
                   6789: @file{compat/const-does.fs}.
                   6790: 
                   6791: 
1.170     pazsan   6792: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
                   6793: @subsection Deferred Words
1.44      crook    6794: @cindex deferred words
                   6795: 
                   6796: The defining word @code{Defer} allows you to define a word by name
                   6797: without defining its behaviour; the definition of its behaviour is
                   6798: deferred. Here are two situation where this can be useful:
                   6799: 
                   6800: @itemize @bullet
                   6801: @item
                   6802: Where you want to allow the behaviour of a word to be altered later, and
                   6803: for all precompiled references to the word to change when its behaviour
                   6804: is changed.
                   6805: @item
                   6806: For mutual recursion; @xref{Calls and returns}.
                   6807: @end itemize
                   6808: 
                   6809: In the following example, @code{foo} always invokes the version of
                   6810: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
                   6811: always invokes the version that prints ``@code{Hello}''. There is no way
                   6812: of getting @code{foo} to use the later version without re-ordering the
                   6813: source code and recompiling it.
                   6814: 
                   6815: @example
                   6816: : greet ." Good morning" ;
                   6817: : foo ... greet ... ;
                   6818: : greet ." Hello" ;
                   6819: : bar ... greet ... ;
                   6820: @end example
                   6821: 
                   6822: This problem can be solved by defining @code{greet} as a @code{Defer}red
                   6823: word. The behaviour of a @code{Defer}red word can be defined and
                   6824: redefined at any time by using @code{IS} to associate the xt of a
                   6825: previously-defined word with it. The previous example becomes:
                   6826: 
                   6827: @example
1.69      anton    6828: Defer greet ( -- )
1.44      crook    6829: : foo ... greet ... ;
                   6830: : bar ... greet ... ;
1.69      anton    6831: : greet1 ( -- ) ." Good morning" ;
                   6832: : greet2 ( -- ) ." Hello" ;
1.132     anton    6833: ' greet2 IS greet  \ make greet behave like greet2
1.44      crook    6834: @end example
                   6835: 
1.69      anton    6836: @progstyle
                   6837: You should write a stack comment for every deferred word, and put only
                   6838: XTs into deferred words that conform to this stack effect.  Otherwise
                   6839: it's too difficult to use the deferred word.
                   6840: 
1.44      crook    6841: A deferred word can be used to improve the statistics-gathering example
                   6842: from @ref{User-defined Defining Words}; rather than edit the
                   6843: application's source code to change every @code{:} to a @code{my:}, do
                   6844: this:
                   6845: 
                   6846: @example
                   6847: : real: : ;     \ retain access to the original
                   6848: defer :         \ redefine as a deferred word
1.132     anton    6849: ' my: IS :      \ use special version of :
1.44      crook    6850: \
                   6851: \ load application here
                   6852: \
1.132     anton    6853: ' real: IS :    \ go back to the original
1.44      crook    6854: @end example
                   6855: 
                   6856: 
1.132     anton    6857: One thing to note is that @code{IS} has special compilation semantics,
                   6858: such that it parses the name at compile time (like @code{TO}):
1.44      crook    6859: 
                   6860: @example
                   6861: : set-greet ( xt -- )
1.132     anton    6862:   IS greet ;
1.44      crook    6863: 
                   6864: ' greet1 set-greet
                   6865: @end example
                   6866: 
1.132     anton    6867: In situations where @code{IS} does not fit, use @code{defer!} instead.
                   6868: 
1.69      anton    6869: A deferred word can only inherit execution semantics from the xt
                   6870: (because that is all that an xt can represent -- for more discussion of
                   6871: this @pxref{Tokens for Words}); by default it will have default
                   6872: interpretation and compilation semantics deriving from this execution
                   6873: semantics.  However, you can change the interpretation and compilation
                   6874: semantics of the deferred word in the usual ways:
1.44      crook    6875: 
                   6876: @example
1.132     anton    6877: : bar .... ; immediate
1.44      crook    6878: Defer fred immediate
                   6879: Defer jim
                   6880: 
1.132     anton    6881: ' bar IS jim  \ jim has default semantics
                   6882: ' bar IS fred \ fred is immediate
1.44      crook    6883: @end example
                   6884: 
                   6885: doc-defer
1.132     anton    6886: doc-defer!
1.44      crook    6887: doc-is
1.132     anton    6888: doc-defer@
                   6889: doc-action-of
1.44      crook    6890: @comment TODO document these: what's defers [is]
                   6891: doc-defers
                   6892: 
                   6893: @c Use @code{words-deferred} to see a list of deferred words.
                   6894: 
1.132     anton    6895: Definitions of these words (except @code{defers}) in ANS Forth are
                   6896: provided in @file{compat/defer.fs}.
1.44      crook    6897: 
                   6898: 
1.170     pazsan   6899: @node Aliases,  , Deferred Words, Defining Words
1.44      crook    6900: @subsection Aliases
                   6901: @cindex aliases
1.1       anton    6902: 
1.44      crook    6903: The defining word @code{Alias} allows you to define a word by name that
                   6904: has the same behaviour as some other word. Here are two situation where
                   6905: this can be useful:
1.1       anton    6906: 
1.44      crook    6907: @itemize @bullet
                   6908: @item
                   6909: When you want access to a word's definition from a different word list
                   6910: (for an example of this, see the definition of the @code{Root} word list
                   6911: in the Gforth source).
                   6912: @item
                   6913: When you want to create a synonym; a definition that can be known by
                   6914: either of two names (for example, @code{THEN} and @code{ENDIF} are
                   6915: aliases).
                   6916: @end itemize
1.1       anton    6917: 
1.69      anton    6918: Like deferred words, an alias has default compilation and interpretation
                   6919: semantics at the beginning (not the modifications of the other word),
                   6920: but you can change them in the usual ways (@code{immediate},
                   6921: @code{compile-only}). For example:
1.1       anton    6922: 
                   6923: @example
1.44      crook    6924: : foo ... ; immediate
                   6925: 
                   6926: ' foo Alias bar \ bar is not an immediate word
                   6927: ' foo Alias fooby immediate \ fooby is an immediate word
1.1       anton    6928: @end example
                   6929: 
1.44      crook    6930: Words that are aliases have the same xt, different headers in the
                   6931: dictionary, and consequently different name tokens (@pxref{Tokens for
                   6932: Words}) and possibly different immediate flags.  An alias can only have
                   6933: default or immediate compilation semantics; you can define aliases for
                   6934: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1       anton    6935: 
1.44      crook    6936: doc-alias
1.1       anton    6937: 
                   6938: 
1.47      crook    6939: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
                   6940: @section Interpretation and Compilation Semantics
1.26      crook    6941: @cindex semantics, interpretation and compilation
1.1       anton    6942: 
1.71      anton    6943: @c !! state and ' are used without explanation
                   6944: @c example for immediate/compile-only? or is the tutorial enough
                   6945: 
1.26      crook    6946: @cindex interpretation semantics
1.71      anton    6947: The @dfn{interpretation semantics} of a (named) word are what the text
1.26      crook    6948: interpreter does when it encounters the word in interpret state. It also
                   6949: appears in some other contexts, e.g., the execution token returned by
1.71      anton    6950: @code{' @i{word}} identifies the interpretation semantics of @i{word}
                   6951: (in other words, @code{' @i{word} execute} is equivalent to
1.29      crook    6952: interpret-state text interpretation of @code{@i{word}}).
1.1       anton    6953: 
1.26      crook    6954: @cindex compilation semantics
1.71      anton    6955: The @dfn{compilation semantics} of a (named) word are what the text
                   6956: interpreter does when it encounters the word in compile state. It also
                   6957: appears in other contexts, e.g, @code{POSTPONE @i{word}}
                   6958: compiles@footnote{In standard terminology, ``appends to the current
                   6959: definition''.} the compilation semantics of @i{word}.
1.1       anton    6960: 
1.26      crook    6961: @cindex execution semantics
                   6962: The standard also talks about @dfn{execution semantics}. They are used
                   6963: only for defining the interpretation and compilation semantics of many
                   6964: words. By default, the interpretation semantics of a word are to
                   6965: @code{execute} its execution semantics, and the compilation semantics of
                   6966: a word are to @code{compile,} its execution semantics.@footnote{In
                   6967: standard terminology: The default interpretation semantics are its
                   6968: execution semantics; the default compilation semantics are to append its
                   6969: execution semantics to the execution semantics of the current
                   6970: definition.}
                   6971: 
1.71      anton    6972: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
                   6973: the text interpreter, ticked, or @code{postpone}d, so they have no
                   6974: interpretation or compilation semantics.  Their behaviour is represented
                   6975: by their XT (@pxref{Tokens for Words}), and we call it execution
                   6976: semantics, too.
                   6977: 
1.26      crook    6978: @comment TODO expand, make it co-operate with new sections on text interpreter.
                   6979: 
                   6980: @cindex immediate words
                   6981: @cindex compile-only words
                   6982: You can change the semantics of the most-recently defined word:
                   6983: 
1.44      crook    6984: 
1.26      crook    6985: doc-immediate
                   6986: doc-compile-only
                   6987: doc-restrict
                   6988: 
1.82      anton    6989: By convention, words with non-default compilation semantics (e.g.,
                   6990: immediate words) often have names surrounded with brackets (e.g.,
                   6991: @code{[']}, @pxref{Execution token}).
1.44      crook    6992: 
1.26      crook    6993: Note that ticking (@code{'}) a compile-only word gives an error
                   6994: (``Interpreting a compile-only word'').
1.1       anton    6995: 
1.47      crook    6996: @menu
1.67      anton    6997: * Combined words::              
1.47      crook    6998: @end menu
1.44      crook    6999: 
1.71      anton    7000: 
1.48      anton    7001: @node Combined words,  , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44      crook    7002: @subsection Combined Words
                   7003: @cindex combined words
                   7004: 
                   7005: Gforth allows you to define @dfn{combined words} -- words that have an
                   7006: arbitrary combination of interpretation and compilation semantics.
                   7007: 
1.26      crook    7008: doc-interpret/compile:
1.1       anton    7009: 
1.26      crook    7010: This feature was introduced for implementing @code{TO} and @code{S"}. I
                   7011: recommend that you do not define such words, as cute as they may be:
                   7012: they make it hard to get at both parts of the word in some contexts.
                   7013: E.g., assume you want to get an execution token for the compilation
                   7014: part. Instead, define two words, one that embodies the interpretation
                   7015: part, and one that embodies the compilation part.  Once you have done
                   7016: that, you can define a combined word with @code{interpret/compile:} for
                   7017: the convenience of your users.
1.1       anton    7018: 
1.26      crook    7019: You might try to use this feature to provide an optimizing
                   7020: implementation of the default compilation semantics of a word. For
                   7021: example, by defining:
1.1       anton    7022: @example
1.26      crook    7023: :noname
                   7024:    foo bar ;
                   7025: :noname
                   7026:    POSTPONE foo POSTPONE bar ;
1.29      crook    7027: interpret/compile: opti-foobar
1.1       anton    7028: @end example
1.26      crook    7029: 
1.23      crook    7030: @noindent
1.26      crook    7031: as an optimizing version of:
                   7032: 
1.1       anton    7033: @example
1.26      crook    7034: : foobar
                   7035:     foo bar ;
1.1       anton    7036: @end example
                   7037: 
1.26      crook    7038: Unfortunately, this does not work correctly with @code{[compile]},
                   7039: because @code{[compile]} assumes that the compilation semantics of all
                   7040: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29      crook    7041: opti-foobar} would compile compilation semantics, whereas
                   7042: @code{[compile] foobar} would compile interpretation semantics.
1.1       anton    7043: 
1.26      crook    7044: @cindex state-smart words (are a bad idea)
1.82      anton    7045: @anchor{state-smartness}
1.29      crook    7046: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26      crook    7047: by @code{interpret/compile:} (words are state-smart if they check
                   7048: @code{STATE} during execution). E.g., they would try to code
                   7049: @code{foobar} like this:
1.1       anton    7050: 
1.26      crook    7051: @example
                   7052: : foobar
                   7053:   STATE @@
                   7054:   IF ( compilation state )
                   7055:     POSTPONE foo POSTPONE bar
                   7056:   ELSE
                   7057:     foo bar
                   7058:   ENDIF ; immediate
                   7059: @end example
1.1       anton    7060: 
1.26      crook    7061: Although this works if @code{foobar} is only processed by the text
                   7062: interpreter, it does not work in other contexts (like @code{'} or
                   7063: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
                   7064: for a state-smart word, not for the interpretation semantics of the
                   7065: original @code{foobar}; when you execute this execution token (directly
                   7066: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
                   7067: state, the result will not be what you expected (i.e., it will not
                   7068: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
                   7069: write them@footnote{For a more detailed discussion of this topic, see
1.66      anton    7070: M. Anton Ertl,
                   7071: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
                   7072: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1       anton    7073: 
1.26      crook    7074: @cindex defining words with arbitrary semantics combinations
                   7075: It is also possible to write defining words that define words with
                   7076: arbitrary combinations of interpretation and compilation semantics. In
                   7077: general, they look like this:
1.1       anton    7078: 
1.26      crook    7079: @example
                   7080: : def-word
                   7081:     create-interpret/compile
1.29      crook    7082:     @i{code1}
1.26      crook    7083: interpretation>
1.29      crook    7084:     @i{code2}
1.26      crook    7085: <interpretation
                   7086: compilation>
1.29      crook    7087:     @i{code3}
1.26      crook    7088: <compilation ;
                   7089: @end example
1.1       anton    7090: 
1.29      crook    7091: For a @i{word} defined with @code{def-word}, the interpretation
                   7092: semantics are to push the address of the body of @i{word} and perform
                   7093: @i{code2}, and the compilation semantics are to push the address of
                   7094: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26      crook    7095: can also be defined like this (except that the defined constants don't
                   7096: behave correctly when @code{[compile]}d):
1.1       anton    7097: 
1.26      crook    7098: @example
                   7099: : constant ( n "name" -- )
                   7100:     create-interpret/compile
                   7101:     ,
                   7102: interpretation> ( -- n )
                   7103:     @@
                   7104: <interpretation
                   7105: compilation> ( compilation. -- ; run-time. -- n )
                   7106:     @@ postpone literal
                   7107: <compilation ;
                   7108: @end example
1.1       anton    7109: 
1.44      crook    7110: 
1.26      crook    7111: doc-create-interpret/compile
                   7112: doc-interpretation>
                   7113: doc-<interpretation
                   7114: doc-compilation>
                   7115: doc-<compilation
1.1       anton    7116: 
1.44      crook    7117: 
1.29      crook    7118: Words defined with @code{interpret/compile:} and
1.26      crook    7119: @code{create-interpret/compile} have an extended header structure that
                   7120: differs from other words; however, unless you try to access them with
                   7121: plain address arithmetic, you should not notice this. Words for
                   7122: accessing the header structure usually know how to deal with this; e.g.,
1.29      crook    7123: @code{'} @i{word} @code{>body} also gives you the body of a word created
                   7124: with @code{create-interpret/compile}.
1.1       anton    7125: 
1.44      crook    7126: 
1.47      crook    7127: @c -------------------------------------------------------------
1.81      anton    7128: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47      crook    7129: @section Tokens for Words
                   7130: @cindex tokens for words
                   7131: 
                   7132: This section describes the creation and use of tokens that represent
                   7133: words.
                   7134: 
1.71      anton    7135: @menu
                   7136: * Execution token::             represents execution/interpretation semantics
                   7137: * Compilation token::           represents compilation semantics
                   7138: * Name token::                  represents named words
                   7139: @end menu
1.47      crook    7140: 
1.71      anton    7141: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
                   7142: @subsection Execution token
1.47      crook    7143: 
                   7144: @cindex xt
                   7145: @cindex execution token
1.71      anton    7146: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
                   7147: You can use @code{execute} to invoke this behaviour.
1.47      crook    7148: 
1.71      anton    7149: @cindex tick (')
                   7150: You can use @code{'} to get an execution token that represents the
                   7151: interpretation semantics of a named word:
1.47      crook    7152: 
                   7153: @example
1.97      anton    7154: 5 ' .   ( n xt ) 
                   7155: execute ( )      \ execute the xt (i.e., ".")
1.71      anton    7156: @end example
1.47      crook    7157: 
1.71      anton    7158: doc-'
                   7159: 
                   7160: @code{'} parses at run-time; there is also a word @code{[']} that parses
                   7161: when it is compiled, and compiles the resulting XT:
                   7162: 
                   7163: @example
                   7164: : foo ['] . execute ;
                   7165: 5 foo
                   7166: : bar ' execute ; \ by contrast,
                   7167: 5 bar .           \ ' parses "." when bar executes
                   7168: @end example
                   7169: 
                   7170: doc-[']
                   7171: 
                   7172: If you want the execution token of @i{word}, write @code{['] @i{word}}
                   7173: in compiled code and @code{' @i{word}} in interpreted code.  Gforth's
                   7174: @code{'} and @code{[']} behave somewhat unusually by complaining about
                   7175: compile-only words (because these words have no interpretation
                   7176: semantics).  You might get what you want by using @code{COMP' @i{word}
                   7177: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
                   7178: token}).
                   7179: 
1.116     anton    7180: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71      anton    7181: (@pxref{Anonymous Definitions}).  For anonymous words this gives an xt
                   7182: for the only behaviour the word has (the execution semantics).  For
1.116     anton    7183: named words, @code{latestxt} produces an XT for the same behaviour it
1.71      anton    7184: would produce if the word was defined anonymously.
                   7185: 
                   7186: @example
                   7187: :noname ." hello" ;
                   7188: execute
1.47      crook    7189: @end example
                   7190: 
1.71      anton    7191: An XT occupies one cell and can be manipulated like any other cell.
                   7192: 
1.47      crook    7193: @cindex code field address
                   7194: @cindex CFA
1.71      anton    7195: In ANS Forth the XT is just an abstract data type (i.e., defined by the
                   7196: operations that produce or consume it).  For old hands: In Gforth, the
                   7197: XT is implemented as a code field address (CFA).
                   7198: 
                   7199: doc-execute
                   7200: doc-perform
                   7201: 
                   7202: @node Compilation token, Name token, Execution token, Tokens for Words
                   7203: @subsection Compilation token
1.47      crook    7204: 
                   7205: @cindex compilation token
1.71      anton    7206: @cindex CT (compilation token)
                   7207: Gforth represents the compilation semantics of a named word by a
1.47      crook    7208: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
                   7209: @i{xt} is an execution token. The compilation semantics represented by
                   7210: the compilation token can be performed with @code{execute}, which
                   7211: consumes the whole compilation token, with an additional stack effect
                   7212: determined by the represented compilation semantics.
                   7213: 
                   7214: At present, the @i{w} part of a compilation token is an execution token,
                   7215: and the @i{xt} part represents either @code{execute} or
                   7216: @code{compile,}@footnote{Depending upon the compilation semantics of the
                   7217: word. If the word has default compilation semantics, the @i{xt} will
                   7218: represent @code{compile,}. Otherwise (e.g., for immediate words), the
                   7219: @i{xt} will represent @code{execute}.}. However, don't rely on that
                   7220: knowledge, unless necessary; future versions of Gforth may introduce
                   7221: unusual compilation tokens (e.g., a compilation token that represents
                   7222: the compilation semantics of a literal).
                   7223: 
1.71      anton    7224: You can perform the compilation semantics represented by the compilation
                   7225: token with @code{execute}.  You can compile the compilation semantics
                   7226: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
                   7227: equivalent to @code{postpone @i{word}}.
                   7228: 
                   7229: doc-[comp']
                   7230: doc-comp'
                   7231: doc-postpone,
                   7232: 
                   7233: @node Name token,  , Compilation token, Tokens for Words
                   7234: @subsection Name token
1.47      crook    7235: 
                   7236: @cindex name token
1.116     anton    7237: Gforth represents named words by the @dfn{name token}, (@i{nt}).  Name
                   7238: token is an abstract data type that occurs as argument or result of the
                   7239: words below.
                   7240: 
                   7241: @c !! put this elswhere?
1.47      crook    7242: @cindex name field address
                   7243: @cindex NFA
1.116     anton    7244: The closest thing to the nt in older Forth systems is the name field
                   7245: address (NFA), but there are significant differences: in older Forth
                   7246: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
                   7247: LFA, NFA, CFA, PFA) and there were words for getting from one to the
                   7248: next.  In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
                   7249: is a link field in the structure identified by the name token, but
                   7250: searching usually uses a hash table external to these structures; the
                   7251: name in Gforth has a cell-wide count-and-flags field, and the nt is not
                   7252: implemented as the address of that count field.
1.47      crook    7253: 
                   7254: doc-find-name
1.116     anton    7255: doc-latest
                   7256: doc->name
1.47      crook    7257: doc-name>int
                   7258: doc-name?int
                   7259: doc-name>comp
                   7260: doc-name>string
1.109     anton    7261: doc-id.
                   7262: doc-.name
                   7263: doc-.id
1.47      crook    7264: 
1.81      anton    7265: @c ----------------------------------------------------------
                   7266: @node Compiling words, The Text Interpreter, Tokens for Words, Words
                   7267: @section Compiling words
                   7268: @cindex compiling words
                   7269: @cindex macros
                   7270: 
                   7271: In contrast to most other languages, Forth has no strict boundary
1.82      anton    7272: between compilation and run-time.  E.g., you can run arbitrary code
                   7273: between defining words (or for computing data used by defining words
                   7274: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
                   7275: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
                   7276: running arbitrary code while compiling a colon definition (exception:
                   7277: you must not allot dictionary space).
                   7278: 
                   7279: @menu
                   7280: * Literals::                    Compiling data values
                   7281: * Macros::                      Compiling words
                   7282: @end menu
                   7283: 
                   7284: @node Literals, Macros, Compiling words, Compiling words
                   7285: @subsection Literals
                   7286: @cindex Literals
                   7287: 
                   7288: The simplest and most frequent example is to compute a literal during
                   7289: compilation.  E.g., the following definition prints an array of strings,
                   7290: one string per line:
                   7291: 
                   7292: @example
                   7293: : .strings ( addr u -- ) \ gforth
                   7294:     2* cells bounds U+DO
                   7295:        cr i 2@@ type
                   7296:     2 cells +LOOP ;  
                   7297: @end example
1.81      anton    7298: 
1.82      anton    7299: With a simple-minded compiler like Gforth's, this computes @code{2
                   7300: cells} on every loop iteration.  You can compute this value once and for
                   7301: all at compile time and compile it into the definition like this:
                   7302: 
                   7303: @example
                   7304: : .strings ( addr u -- ) \ gforth
                   7305:     2* cells bounds U+DO
                   7306:        cr i 2@@ type
                   7307:     [ 2 cells ] literal +LOOP ;  
                   7308: @end example
                   7309: 
                   7310: @code{[} switches the text interpreter to interpret state (you will get
                   7311: an @code{ok} prompt if you type this example interactively and insert a
                   7312: newline between @code{[} and @code{]}), so it performs the
                   7313: interpretation semantics of @code{2 cells}; this computes a number.
                   7314: @code{]} switches the text interpreter back into compile state.  It then
                   7315: performs @code{Literal}'s compilation semantics, which are to compile
                   7316: this number into the current word.  You can decompile the word with
                   7317: @code{see .strings} to see the effect on the compiled code.
1.81      anton    7318: 
1.82      anton    7319: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
                   7320: *} in this way.
1.81      anton    7321: 
1.82      anton    7322: doc-[
                   7323: doc-]
1.81      anton    7324: doc-literal
                   7325: doc-]L
1.82      anton    7326: 
                   7327: There are also words for compiling other data types than single cells as
                   7328: literals:
                   7329: 
1.81      anton    7330: doc-2literal
                   7331: doc-fliteral
1.82      anton    7332: doc-sliteral
                   7333: 
                   7334: @cindex colon-sys, passing data across @code{:}
                   7335: @cindex @code{:}, passing data across
                   7336: You might be tempted to pass data from outside a colon definition to the
                   7337: inside on the data stack.  This does not work, because @code{:} puhes a
                   7338: colon-sys, making stuff below unaccessible.  E.g., this does not work:
                   7339: 
                   7340: @example
                   7341: 5 : foo literal ; \ error: "unstructured"
                   7342: @end example
                   7343: 
                   7344: Instead, you have to pass the value in some other way, e.g., through a
                   7345: variable:
                   7346: 
                   7347: @example
                   7348: variable temp
                   7349: 5 temp !
                   7350: : foo [ temp @@ ] literal ;
                   7351: @end example
                   7352: 
                   7353: 
                   7354: @node Macros,  , Literals, Compiling words
                   7355: @subsection Macros
                   7356: @cindex Macros
                   7357: @cindex compiling compilation semantics
                   7358: 
                   7359: @code{Literal} and friends compile data values into the current
                   7360: definition.  You can also write words that compile other words into the
                   7361: current definition.  E.g.,
                   7362: 
                   7363: @example
                   7364: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
                   7365:   POSTPONE + ;
                   7366: 
                   7367: : foo ( n1 n2 -- n )
                   7368:   [ compile-+ ] ;
                   7369: 1 2 foo .
                   7370: @end example
                   7371: 
                   7372: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
                   7373: What happens in this example?  @code{Postpone} compiles the compilation
                   7374: semantics of @code{+} into @code{compile-+}; later the text interpreter
                   7375: executes @code{compile-+} and thus the compilation semantics of +, which
                   7376: compile (the execution semantics of) @code{+} into
                   7377: @code{foo}.@footnote{A recent RFI answer requires that compiling words
                   7378: should only be executed in compile state, so this example is not
                   7379: guaranteed to work on all standard systems, but on any decent system it
                   7380: will work.}
                   7381: 
                   7382: doc-postpone
                   7383: doc-[compile]
                   7384: 
                   7385: Compiling words like @code{compile-+} are usually immediate (or similar)
                   7386: so you do not have to switch to interpret state to execute them;
                   7387: mopifying the last example accordingly produces:
                   7388: 
                   7389: @example
                   7390: : [compile-+] ( compilation: --; interpretation: -- )
                   7391:   \ compiled code: ( n1 n2 -- n )
                   7392:   POSTPONE + ; immediate
                   7393: 
                   7394: : foo ( n1 n2 -- n )
                   7395:   [compile-+] ;
                   7396: 1 2 foo .
                   7397: @end example
                   7398: 
                   7399: Immediate compiling words are similar to macros in other languages (in
                   7400: particular, Lisp).  The important differences to macros in, e.g., C are:
                   7401: 
                   7402: @itemize @bullet
                   7403: 
                   7404: @item
                   7405: You use the same language for defining and processing macros, not a
                   7406: separate preprocessing language and processor.
                   7407: 
                   7408: @item
                   7409: Consequently, the full power of Forth is available in macro definitions.
                   7410: E.g., you can perform arbitrarily complex computations, or generate
                   7411: different code conditionally or in a loop (e.g., @pxref{Advanced macros
                   7412: Tutorial}).  This power is very useful when writing a parser generators
                   7413: or other code-generating software.
                   7414: 
                   7415: @item
                   7416: Macros defined using @code{postpone} etc. deal with the language at a
                   7417: higher level than strings; name binding happens at macro definition
                   7418: time, so you can avoid the pitfalls of name collisions that can happen
                   7419: in C macros.  Of course, Forth is a liberal language and also allows to
                   7420: shoot yourself in the foot with text-interpreted macros like
                   7421: 
                   7422: @example
                   7423: : [compile-+] s" +" evaluate ; immediate
                   7424: @end example
                   7425: 
                   7426: Apart from binding the name at macro use time, using @code{evaluate}
                   7427: also makes your definition @code{state}-smart (@pxref{state-smartness}).
                   7428: @end itemize
                   7429: 
                   7430: You may want the macro to compile a number into a word.  The word to do
                   7431: it is @code{literal}, but you have to @code{postpone} it, so its
                   7432: compilation semantics take effect when the macro is executed, not when
                   7433: it is compiled:
                   7434: 
                   7435: @example
                   7436: : [compile-5] ( -- ) \ compiled code: ( -- n )
                   7437:   5 POSTPONE literal ; immediate
                   7438: 
                   7439: : foo [compile-5] ;
                   7440: foo .
                   7441: @end example
                   7442: 
                   7443: You may want to pass parameters to a macro, that the macro should
                   7444: compile into the current definition.  If the parameter is a number, then
                   7445: you can use @code{postpone literal} (similar for other values).
                   7446: 
                   7447: If you want to pass a word that is to be compiled, the usual way is to
                   7448: pass an execution token and @code{compile,} it:
                   7449: 
                   7450: @example
                   7451: : twice1 ( xt -- ) \ compiled code: ... -- ...
                   7452:   dup compile, compile, ;
                   7453: 
                   7454: : 2+ ( n1 -- n2 )
                   7455:   [ ' 1+ twice1 ] ;
                   7456: @end example
                   7457: 
                   7458: doc-compile,
                   7459: 
                   7460: An alternative available in Gforth, that allows you to pass compile-only
                   7461: words as parameters is to use the compilation token (@pxref{Compilation
                   7462: token}).  The same example in this technique:
                   7463: 
                   7464: @example
                   7465: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
                   7466:   2dup 2>r execute 2r> execute ;
                   7467: 
                   7468: : 2+ ( n1 -- n2 )
                   7469:   [ comp' 1+ twice ] ;
                   7470: @end example
                   7471: 
                   7472: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
                   7473: works even if the executed compilation semantics has an effect on the
                   7474: data stack.
                   7475: 
                   7476: You can also define complete definitions with these words; this provides
                   7477: an alternative to using @code{does>} (@pxref{User-defined Defining
                   7478: Words}).  E.g., instead of
                   7479: 
                   7480: @example
                   7481: : curry+ ( n1 "name" -- )
                   7482:     CREATE ,
                   7483: DOES> ( n2 -- n1+n2 )
                   7484:     @@ + ;
                   7485: @end example
                   7486: 
                   7487: you could define
                   7488: 
                   7489: @example
                   7490: : curry+ ( n1 "name" -- )
                   7491:   \ name execution: ( n2 -- n1+n2 )
                   7492:   >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81      anton    7493: 
1.82      anton    7494: -3 curry+ 3-
                   7495: see 3-
                   7496: @end example
1.81      anton    7497: 
1.82      anton    7498: The sequence @code{>r : r>} is necessary, because @code{:} puts a
                   7499: colon-sys on the data stack that makes everything below it unaccessible.
1.81      anton    7500: 
1.82      anton    7501: This way of writing defining words is sometimes more, sometimes less
                   7502: convenient than using @code{does>} (@pxref{Advanced does> usage
                   7503: example}).  One advantage of this method is that it can be optimized
                   7504: better, because the compiler knows that the value compiled with
                   7505: @code{literal} is fixed, whereas the data associated with a
                   7506: @code{create}d word can be changed.
1.47      crook    7507: 
1.26      crook    7508: @c ----------------------------------------------------------
1.111     anton    7509: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26      crook    7510: @section  The Text Interpreter
                   7511: @cindex interpreter - outer
                   7512: @cindex text interpreter
                   7513: @cindex outer interpreter
1.1       anton    7514: 
1.34      anton    7515: @c Should we really describe all these ugly details?  IMO the text
                   7516: @c interpreter should be much cleaner, but that may not be possible within
                   7517: @c ANS Forth. - anton
1.44      crook    7518: @c nac-> I wanted to explain how it works to show how you can exploit
                   7519: @c it in your own programs. When I was writing a cross-compiler, figuring out
                   7520: @c some of these gory details was very helpful to me. None of the textbooks
                   7521: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
                   7522: @c seems to positively avoid going into too much detail for some of
                   7523: @c the internals.
1.34      anton    7524: 
1.71      anton    7525: @c anton: ok.  I wonder, though, if this is the right place; for some stuff
                   7526: @c it is; for the ugly details, I would prefer another place.  I wonder
                   7527: @c whether we should have a chapter before "Words" that describes some
                   7528: @c basic concepts referred to in words, and a chapter after "Words" that
                   7529: @c describes implementation details.
                   7530: 
1.29      crook    7531: The text interpreter@footnote{This is an expanded version of the
                   7532: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34      anton    7533: that processes input from the current input device. It is also called
                   7534: the outer interpreter, in contrast to the inner interpreter
                   7535: (@pxref{Engine}) which executes the compiled Forth code on interpretive
                   7536: implementations.
1.27      crook    7537: 
1.29      crook    7538: @cindex interpret state
                   7539: @cindex compile state
                   7540: The text interpreter operates in one of two states: @dfn{interpret
                   7541: state} and @dfn{compile state}. The current state is defined by the
1.71      anton    7542: aptly-named variable @code{state}.
1.29      crook    7543: 
                   7544: This section starts by describing how the text interpreter behaves when
                   7545: it is in interpret state, processing input from the user input device --
                   7546: the keyboard. This is the mode that a Forth system is in after it starts
                   7547: up.
                   7548: 
                   7549: @cindex input buffer
                   7550: @cindex terminal input buffer
                   7551: The text interpreter works from an area of memory called the @dfn{input
                   7552: buffer}@footnote{When the text interpreter is processing input from the
                   7553: keyboard, this area of memory is called the @dfn{terminal input buffer}
                   7554: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
                   7555: @code{#TIB}.}, which stores your keyboard input when you press the
1.30      anton    7556: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29      crook    7557: leading spaces (called @dfn{delimiters}) then parses a string (a
                   7558: sequence of non-space characters) until it reaches either a space
                   7559: character or the end of the buffer. Having parsed a string, it makes two
                   7560: attempts to process it:
1.27      crook    7561: 
1.29      crook    7562: @cindex dictionary
1.27      crook    7563: @itemize @bullet
                   7564: @item
1.29      crook    7565: It looks for the string in a @dfn{dictionary} of definitions. If the
                   7566: string is found, the string names a @dfn{definition} (also known as a
                   7567: @dfn{word}) and the dictionary search returns information that allows
                   7568: the text interpreter to perform the word's @dfn{interpretation
                   7569: semantics}. In most cases, this simply means that the word will be
                   7570: executed.
1.27      crook    7571: @item
                   7572: If the string is not found in the dictionary, the text interpreter
1.29      crook    7573: attempts to treat it as a number, using the rules described in
                   7574: @ref{Number Conversion}. If the string represents a legal number in the
                   7575: current radix, the number is pushed onto a parameter stack (the data
                   7576: stack for integers, the floating-point stack for floating-point
                   7577: numbers).
                   7578: @end itemize
                   7579: 
                   7580: If both attempts fail, or if the word is found in the dictionary but has
                   7581: no interpretation semantics@footnote{This happens if the word was
                   7582: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
                   7583: remainder of the input buffer, issues an error message and waits for
                   7584: more input. If one of the attempts succeeds, the text interpreter
                   7585: repeats the parsing process until the whole of the input buffer has been
                   7586: processed, at which point it prints the status message ``@code{ ok}''
                   7587: and waits for more input.
                   7588: 
1.71      anton    7589: @c anton: this should be in the input stream subsection (or below it)
                   7590: 
1.29      crook    7591: @cindex parse area
                   7592: The text interpreter keeps track of its position in the input buffer by
                   7593: updating a variable called @code{>IN} (pronounced ``to-in''). The value
                   7594: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
                   7595: of the input buffer. The region from offset @code{>IN @@} to the end of
                   7596: the input buffer is called the @dfn{parse area}@footnote{In other words,
                   7597: the text interpreter processes the contents of the input buffer by
                   7598: parsing strings from the parse area until the parse area is empty.}.
                   7599: This example shows how @code{>IN} changes as the text interpreter parses
                   7600: the input buffer:
                   7601: 
                   7602: @example
                   7603: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
                   7604:   CR ." ->" TYPE ." <-" ; IMMEDIATE 
                   7605: 
                   7606: 1 2 3 remaining + remaining . 
                   7607: 
                   7608: : foo 1 2 3 remaining SWAP remaining ;
                   7609: @end example
                   7610: 
                   7611: @noindent
                   7612: The result is:
                   7613: 
                   7614: @example
                   7615: ->+ remaining .<-
                   7616: ->.<-5  ok
                   7617: 
                   7618: ->SWAP remaining ;-<
                   7619: ->;<-  ok
                   7620: @end example
                   7621: 
                   7622: @cindex parsing words
                   7623: The value of @code{>IN} can also be modified by a word in the input
                   7624: buffer that is executed by the text interpreter.  This means that a word
                   7625: can ``trick'' the text interpreter into either skipping a section of the
                   7626: input buffer@footnote{This is how parsing words work.} or into parsing a
                   7627: section twice. For example:
1.27      crook    7628: 
1.29      crook    7629: @example
1.71      anton    7630: : lat ." <<foo>>" ;
                   7631: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29      crook    7632: @end example
                   7633: 
                   7634: @noindent
                   7635: When @code{flat} is executed, this output is produced@footnote{Exercise
                   7636: for the reader: what would happen if the @code{3} were replaced with
                   7637: @code{4}?}:
                   7638: 
                   7639: @example
1.71      anton    7640: <<bar>><<foo>>
1.29      crook    7641: @end example
                   7642: 
1.71      anton    7643: This technique can be used to work around some of the interoperability
                   7644: problems of parsing words.  Of course, it's better to avoid parsing
                   7645: words where possible.
                   7646: 
1.29      crook    7647: @noindent
                   7648: Two important notes about the behaviour of the text interpreter:
1.27      crook    7649: 
                   7650: @itemize @bullet
                   7651: @item
                   7652: It processes each input string to completion before parsing additional
1.29      crook    7653: characters from the input buffer.
                   7654: @item
                   7655: It treats the input buffer as a read-only region (and so must your code).
                   7656: @end itemize
                   7657: 
                   7658: @noindent
                   7659: When the text interpreter is in compile state, its behaviour changes in
                   7660: these ways:
                   7661: 
                   7662: @itemize @bullet
                   7663: @item
                   7664: If a parsed string is found in the dictionary, the text interpreter will
                   7665: perform the word's @dfn{compilation semantics}. In most cases, this
                   7666: simply means that the execution semantics of the word will be appended
                   7667: to the current definition.
1.27      crook    7668: @item
1.29      crook    7669: When a number is encountered, it is compiled into the current definition
                   7670: (as a literal) rather than being pushed onto a parameter stack.
                   7671: @item
                   7672: If an error occurs, @code{state} is modified to put the text interpreter
                   7673: back into interpret state.
                   7674: @item
                   7675: Each time a line is entered from the keyboard, Gforth prints
                   7676: ``@code{ compiled}'' rather than `` @code{ok}''.
                   7677: @end itemize
                   7678: 
                   7679: @cindex text interpreter - input sources
                   7680: When the text interpreter is using an input device other than the
                   7681: keyboard, its behaviour changes in these ways:
                   7682: 
                   7683: @itemize @bullet
                   7684: @item
                   7685: When the parse area is empty, the text interpreter attempts to refill
                   7686: the input buffer from the input source. When the input source is
1.71      anton    7687: exhausted, the input source is set back to the previous input source.
1.29      crook    7688: @item
                   7689: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
                   7690: time the parse area is emptied.
                   7691: @item
                   7692: If an error occurs, the input source is set back to the user input
                   7693: device.
1.27      crook    7694: @end itemize
1.21      crook    7695: 
1.49      anton    7696: You can read about this in more detail in @ref{Input Sources}.
1.44      crook    7697: 
1.26      crook    7698: doc->in
1.27      crook    7699: doc-source
                   7700: 
1.26      crook    7701: doc-tib
                   7702: doc-#tib
1.1       anton    7703: 
1.44      crook    7704: 
1.26      crook    7705: @menu
1.67      anton    7706: * Input Sources::               
                   7707: * Number Conversion::           
                   7708: * Interpret/Compile states::    
                   7709: * Interpreter Directives::      
1.26      crook    7710: @end menu
1.1       anton    7711: 
1.29      crook    7712: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
                   7713: @subsection Input Sources
                   7714: @cindex input sources
                   7715: @cindex text interpreter - input sources
                   7716: 
1.44      crook    7717: By default, the text interpreter processes input from the user input
1.29      crook    7718: device (the keyboard) when Forth starts up. The text interpreter can
                   7719: process input from any of these sources:
                   7720: 
                   7721: @itemize @bullet
                   7722: @item
                   7723: The user input device -- the keyboard.
                   7724: @item
                   7725: A file, using the words described in @ref{Forth source files}.
                   7726: @item
                   7727: A block, using the words described in @ref{Blocks}.
                   7728: @item
                   7729: A text string, using @code{evaluate}.
                   7730: @end itemize
                   7731: 
                   7732: A program can identify the current input device from the values of
                   7733: @code{source-id} and @code{blk}.
                   7734: 
1.44      crook    7735: 
1.29      crook    7736: doc-source-id
                   7737: doc-blk
                   7738: 
                   7739: doc-save-input
                   7740: doc-restore-input
                   7741: 
                   7742: doc-evaluate
1.111     anton    7743: doc-query
1.1       anton    7744: 
1.29      crook    7745: 
1.44      crook    7746: 
1.29      crook    7747: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26      crook    7748: @subsection Number Conversion
                   7749: @cindex number conversion
                   7750: @cindex double-cell numbers, input format
                   7751: @cindex input format for double-cell numbers
                   7752: @cindex single-cell numbers, input format
                   7753: @cindex input format for single-cell numbers
                   7754: @cindex floating-point numbers, input format
                   7755: @cindex input format for floating-point numbers
1.1       anton    7756: 
1.29      crook    7757: This section describes the rules that the text interpreter uses when it
                   7758: tries to convert a string into a number.
1.1       anton    7759: 
1.26      crook    7760: Let <digit> represent any character that is a legal digit in the current
1.29      crook    7761: number base@footnote{For example, 0-9 when the number base is decimal or
                   7762: 0-9, A-F when the number base is hexadecimal.}.
1.1       anton    7763: 
1.26      crook    7764: Let <decimal digit> represent any character in the range 0-9.
1.1       anton    7765: 
1.29      crook    7766: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
                   7767: in the braces (@i{a} or @i{b} or neither).
1.1       anton    7768: 
1.26      crook    7769: Let * represent any number of instances of the previous character
                   7770: (including none).
1.1       anton    7771: 
1.26      crook    7772: Let any other character represent itself.
1.1       anton    7773: 
1.29      crook    7774: @noindent
1.26      crook    7775: Now, the conversion rules are:
1.21      crook    7776: 
1.26      crook    7777: @itemize @bullet
                   7778: @item
                   7779: A string of the form <digit><digit>* is treated as a single-precision
1.29      crook    7780: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26      crook    7781: @item
                   7782: A string of the form -<digit><digit>* is treated as a single-precision
1.29      crook    7783: (cell-sized) negative integer, and is represented using 2's-complement
1.26      crook    7784: arithmetic. Examples are -45 -5681 -0
                   7785: @item
                   7786: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29      crook    7787: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
                   7788: (all three of these represent the same number).
1.26      crook    7789: @item
                   7790: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29      crook    7791: double-precision (double-cell-sized) negative integer, and is
1.26      crook    7792: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29      crook    7793: -34.65 (all three of these represent the same number).
1.26      crook    7794: @item
1.29      crook    7795: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
                   7796: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35      anton    7797: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29      crook    7798: number) +12.E-4
1.26      crook    7799: @end itemize
1.1       anton    7800: 
1.174     anton    7801: By default, the number base used for integer number conversion is
                   7802: given by the contents of the variable @code{base}.  Note that a lot of
1.35      anton    7803: confusion can result from unexpected values of @code{base}.  If you
1.174     anton    7804: change @code{base} anywhere, make sure to save the old value and
                   7805: restore it afterwards; better yet, use @code{base-execute}, which does
                   7806: this for you.  In general I recommend keeping @code{base} decimal, and
1.35      anton    7807: using the prefixes described below for the popular non-decimal bases.
1.1       anton    7808: 
1.29      crook    7809: doc-dpl
1.174     anton    7810: doc-base-execute
1.26      crook    7811: doc-base
                   7812: doc-hex
                   7813: doc-decimal
1.1       anton    7814: 
1.26      crook    7815: @cindex '-prefix for character strings
                   7816: @cindex &-prefix for decimal numbers
1.133     anton    7817: @cindex #-prefix for decimal numbers
1.26      crook    7818: @cindex %-prefix for binary numbers
                   7819: @cindex $-prefix for hexadecimal numbers
1.133     anton    7820: @cindex 0x-prefix for hexadecimal numbers
1.35      anton    7821: Gforth allows you to override the value of @code{base} by using a
1.29      crook    7822: prefix@footnote{Some Forth implementations provide a similar scheme by
                   7823: implementing @code{$} etc. as parsing words that process the subsequent
                   7824: number in the input stream and push it onto the stack. For example, see
                   7825: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
                   7826: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
                   7827: is required between the prefix and the number.} before the first digit
1.133     anton    7828: of an (integer) number. The following prefixes are supported:
1.1       anton    7829: 
1.26      crook    7830: @itemize @bullet
                   7831: @item
1.35      anton    7832: @code{&} -- decimal
1.26      crook    7833: @item
1.133     anton    7834: @code{#} -- decimal
                   7835: @item
1.35      anton    7836: @code{%} -- binary
1.26      crook    7837: @item
1.35      anton    7838: @code{$} -- hexadecimal
1.26      crook    7839: @item
1.133     anton    7840: @code{0x} -- hexadecimal, if base<33.
                   7841: @item
                   7842: @code{'} -- numeric value (e.g., ASCII code) of next character; an
                   7843: optional @code{'} may be present after the character.
1.26      crook    7844: @end itemize
1.1       anton    7845: 
1.26      crook    7846: Here are some examples, with the equivalent decimal number shown after
                   7847: in braces:
1.1       anton    7848: 
1.26      crook    7849: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133     anton    7850: 'A (65),
                   7851: -'a' (-97),
1.26      crook    7852: &905 (905), $abc (2478), $ABC (2478).
1.1       anton    7853: 
1.26      crook    7854: @cindex number conversion - traps for the unwary
1.29      crook    7855: @noindent
1.26      crook    7856: Number conversion has a number of traps for the unwary:
1.1       anton    7857: 
1.26      crook    7858: @itemize @bullet
                   7859: @item
                   7860: You cannot determine the current number base using the code sequence
1.35      anton    7861: @code{base @@ .} -- the number base is always 10 in the current number
                   7862: base. Instead, use something like @code{base @@ dec.}
1.26      crook    7863: @item
                   7864: If the number base is set to a value greater than 14 (for example,
                   7865: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
                   7866: it to be intepreted as either a single-precision integer or a
                   7867: floating-point number (Gforth treats it as an integer). The ambiguity
                   7868: can be resolved by explicitly stating the sign of the mantissa and/or
                   7869: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
                   7870: ambiguity arises; either representation will be treated as a
                   7871: floating-point number.
                   7872: @item
1.29      crook    7873: There is a word @code{bin} but it does @i{not} set the number base!
1.26      crook    7874: It is used to specify file types.
                   7875: @item
1.72      anton    7876: ANS Forth requires the @code{.} of a double-precision number to be the
                   7877: final character in the string.  Gforth allows the @code{.} to be
                   7878: anywhere after the first digit.
1.26      crook    7879: @item
                   7880: The number conversion process does not check for overflow.
                   7881: @item
1.72      anton    7882: In an ANS Forth program @code{base} is required to be decimal when
                   7883: converting floating-point numbers.  In Gforth, number conversion to
                   7884: floating-point numbers always uses base &10, irrespective of the value
                   7885: of @code{base}.
1.26      crook    7886: @end itemize
1.1       anton    7887: 
1.49      anton    7888: You can read numbers into your programs with the words described in
1.181     anton    7889: @ref{Line input and conversion}.
1.1       anton    7890: 
1.82      anton    7891: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26      crook    7892: @subsection Interpret/Compile states
                   7893: @cindex Interpret/Compile states
1.1       anton    7894: 
1.29      crook    7895: A standard program is not permitted to change @code{state}
                   7896: explicitly. However, it can change @code{state} implicitly, using the
                   7897: words @code{[} and @code{]}. When @code{[} is executed it switches
                   7898: @code{state} to interpret state, and therefore the text interpreter
                   7899: starts interpreting. When @code{]} is executed it switches @code{state}
                   7900: to compile state and therefore the text interpreter starts
1.44      crook    7901: compiling. The most common usage for these words is for switching into
                   7902: interpret state and back from within a colon definition; this technique
1.49      anton    7903: can be used to compile a literal (for an example, @pxref{Literals}) or
                   7904: for conditional compilation (for an example, @pxref{Interpreter
                   7905: Directives}).
1.44      crook    7906: 
1.35      anton    7907: 
                   7908: @c This is a bad example: It's non-standard, and it's not necessary.
                   7909: @c However, I can't think of a good example for switching into compile
                   7910: @c state when there is no current word (@code{state}-smart words are not a
                   7911: @c good reason).  So maybe we should use an example for switching into
                   7912: @c interpret @code{state} in a colon def. - anton
1.44      crook    7913: @c nac-> I agree. I started out by putting in the example, then realised
                   7914: @c that it was non-ANS, so wrote more words around it. I hope this
                   7915: @c re-written version is acceptable to you. I do want to keep the example
                   7916: @c as it is helpful for showing what is and what is not portable, particularly
                   7917: @c where it outlaws a style in common use.
                   7918: 
1.72      anton    7919: @c anton: it's more important to show what's portable.  After we have done
1.83      anton    7920: @c that, we can also show what's not.  In any case, I have written a
                   7921: @c section Compiling Words which also deals with [ ].
1.35      anton    7922: 
1.95      anton    7923: @c  !! The following example does not work in Gforth 0.5.9 or later.
1.29      crook    7924: 
1.95      anton    7925: @c  @code{[} and @code{]} also give you the ability to switch into compile
                   7926: @c  state and back, but we cannot think of any useful Standard application
                   7927: @c  for this ability. Pre-ANS Forth textbooks have examples like this:
                   7928: 
                   7929: @c  @example
                   7930: @c  : AA ." this is A" ;
                   7931: @c  : BB ." this is B" ;
                   7932: @c  : CC ." this is C" ;
                   7933: 
                   7934: @c  create table ] aa bb cc [
                   7935: 
                   7936: @c  : go ( n -- ) \ n is offset into table.. 0 for 1st entry
                   7937: @c    cells table + @@ execute ;
                   7938: @c  @end example
                   7939: 
                   7940: @c  This example builds a jump table; @code{0 go} will display ``@code{this
                   7941: @c  is A}''. Using @code{[} and @code{]} in this example is equivalent to
                   7942: @c  defining @code{table} like this:
                   7943: 
                   7944: @c  @example
                   7945: @c  create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
                   7946: @c  @end example
                   7947: 
                   7948: @c  The problem with this code is that the definition of @code{table} is not
                   7949: @c  portable -- it @i{compile}s execution tokens into code space. Whilst it
                   7950: @c  @i{may} work on systems where code space and data space co-incide, the
                   7951: @c  Standard only allows data space to be assigned for a @code{CREATE}d
                   7952: @c  word. In addition, the Standard only allows @code{@@} to access data
                   7953: @c  space, whilst this example is using it to access code space. The only
                   7954: @c  portable, Standard way to build this table is to build it in data space,
                   7955: @c  like this:
                   7956: 
                   7957: @c  @example
                   7958: @c  create table ' aa , ' bb , ' cc ,
                   7959: @c  @end example
1.29      crook    7960: 
1.95      anton    7961: @c  doc-state
1.44      crook    7962: 
1.29      crook    7963: 
1.82      anton    7964: @node Interpreter Directives,  , Interpret/Compile states, The Text Interpreter
1.26      crook    7965: @subsection Interpreter Directives
                   7966: @cindex interpreter directives
1.72      anton    7967: @cindex conditional compilation
1.1       anton    7968: 
1.29      crook    7969: These words are usually used in interpret state; typically to control
                   7970: which parts of a source file are processed by the text
1.26      crook    7971: interpreter. There are only a few ANS Forth Standard words, but Gforth
                   7972: supplements these with a rich set of immediate control structure words
                   7973: to compensate for the fact that the non-immediate versions can only be
1.29      crook    7974: used in compile state (@pxref{Control Structures}). Typical usages:
                   7975: 
                   7976: @example
1.72      anton    7977: FALSE Constant HAVE-ASSEMBLER
1.29      crook    7978: .
                   7979: .
1.72      anton    7980: HAVE-ASSEMBLER [IF]
1.29      crook    7981: : ASSEMBLER-FEATURE
                   7982:   ...
                   7983: ;
                   7984: [ENDIF]
                   7985: .
                   7986: .
                   7987: : SEE
                   7988:   ... \ general-purpose SEE code
1.72      anton    7989:   [ HAVE-ASSEMBLER [IF] ]
1.29      crook    7990:   ... \ assembler-specific SEE code
                   7991:   [ [ENDIF] ]
                   7992: ;
                   7993: @end example
1.1       anton    7994: 
1.44      crook    7995: 
1.26      crook    7996: doc-[IF]
                   7997: doc-[ELSE]
                   7998: doc-[THEN]
                   7999: doc-[ENDIF]
1.1       anton    8000: 
1.26      crook    8001: doc-[IFDEF]
                   8002: doc-[IFUNDEF]
1.1       anton    8003: 
1.26      crook    8004: doc-[?DO]
                   8005: doc-[DO]
                   8006: doc-[FOR]
                   8007: doc-[LOOP]
                   8008: doc-[+LOOP]
                   8009: doc-[NEXT]
1.1       anton    8010: 
1.26      crook    8011: doc-[BEGIN]
                   8012: doc-[UNTIL]
                   8013: doc-[AGAIN]
                   8014: doc-[WHILE]
                   8015: doc-[REPEAT]
1.1       anton    8016: 
1.27      crook    8017: 
1.26      crook    8018: @c -------------------------------------------------------------
1.111     anton    8019: @node The Input Stream, Word Lists, The Text Interpreter, Words
                   8020: @section The Input Stream
                   8021: @cindex input stream
                   8022: 
                   8023: @c !! integrate this better with the "Text Interpreter" section
                   8024: The text interpreter reads from the input stream, which can come from
                   8025: several sources (@pxref{Input Sources}).  Some words, in particular
                   8026: defining words, but also words like @code{'}, read parameters from the
                   8027: input stream instead of from the stack.
                   8028: 
                   8029: Such words are called parsing words, because they parse the input
                   8030: stream.  Parsing words are hard to use in other words, because it is
                   8031: hard to pass program-generated parameters through the input stream.
                   8032: They also usually have an unintuitive combination of interpretation and
                   8033: compilation semantics when implemented naively, leading to various
                   8034: approaches that try to produce a more intuitive behaviour
                   8035: (@pxref{Combined words}).
                   8036: 
                   8037: It should be obvious by now that parsing words are a bad idea.  If you
                   8038: want to implement a parsing word for convenience, also provide a factor
                   8039: of the word that does not parse, but takes the parameters on the stack.
                   8040: To implement the parsing word on top if it, you can use the following
                   8041: words:
                   8042: 
                   8043: @c anton: these belong in the input stream section
                   8044: doc-parse
1.138     anton    8045: doc-parse-name
1.111     anton    8046: doc-parse-word
                   8047: doc-name
                   8048: doc-word
                   8049: doc-refill
                   8050: 
                   8051: Conversely, if you have the bad luck (or lack of foresight) to have to
                   8052: deal with parsing words without having such factors, how do you pass a
                   8053: string that is not in the input stream to it?
                   8054: 
                   8055: doc-execute-parsing
                   8056: 
1.146     anton    8057: A definition of this word in ANS Forth is provided in
                   8058: @file{compat/execute-parsing.fs}.
                   8059: 
1.111     anton    8060: If you want to run a parsing word on a file, the following word should
                   8061: help:
                   8062: 
                   8063: doc-execute-parsing-file
                   8064: 
                   8065: @c -------------------------------------------------------------
                   8066: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26      crook    8067: @section Word Lists
                   8068: @cindex word lists
1.32      anton    8069: @cindex header space
1.1       anton    8070: 
1.36      anton    8071: A wordlist is a list of named words; you can add new words and look up
                   8072: words by name (and you can remove words in a restricted way with
                   8073: markers).  Every named (and @code{reveal}ed) word is in one wordlist.
                   8074: 
                   8075: @cindex search order stack
                   8076: The text interpreter searches the wordlists present in the search order
                   8077: (a stack of wordlists), from the top to the bottom.  Within each
                   8078: wordlist, the search starts conceptually at the newest word; i.e., if
                   8079: two words in a wordlist have the same name, the newer word is found.
1.1       anton    8080: 
1.26      crook    8081: @cindex compilation word list
1.36      anton    8082: New words are added to the @dfn{compilation wordlist} (aka current
                   8083: wordlist).
1.1       anton    8084: 
1.36      anton    8085: @cindex wid
                   8086: A word list is identified by a cell-sized word list identifier (@i{wid})
                   8087: in much the same way as a file is identified by a file handle. The
                   8088: numerical value of the wid has no (portable) meaning, and might change
                   8089: from session to session.
1.1       anton    8090: 
1.29      crook    8091: The ANS Forth ``Search order'' word set is intended to provide a set of
                   8092: low-level tools that allow various different schemes to be
1.74      anton    8093: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26      crook    8094: word.  @file{compat/vocabulary.fs} provides an implementation in ANS
1.45      crook    8095: Forth.
1.1       anton    8096: 
1.27      crook    8097: @comment TODO: locals section refers to here, saying that every word list (aka
                   8098: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78      anton    8099: @c anton: but better in a separate subsection on wordlist internals
1.1       anton    8100: 
1.45      crook    8101: @comment TODO: document markers, reveal, tables, mappedwordlist
                   8102: 
                   8103: @comment the gforthman- prefix is used to pick out the true definition of a
1.27      crook    8104: @comment word from the source files, rather than some alias.
1.44      crook    8105: 
1.26      crook    8106: doc-forth-wordlist
                   8107: doc-definitions
                   8108: doc-get-current
                   8109: doc-set-current
                   8110: doc-get-order
1.185     anton    8111: doc-set-order
1.26      crook    8112: doc-wordlist
1.30      anton    8113: doc-table
1.79      anton    8114: doc->order
1.36      anton    8115: doc-previous
1.26      crook    8116: doc-also
1.185     anton    8117: doc-forth
1.26      crook    8118: doc-only
1.185     anton    8119: doc-order
1.15      anton    8120: 
1.26      crook    8121: doc-find
                   8122: doc-search-wordlist
1.15      anton    8123: 
1.26      crook    8124: doc-words
                   8125: doc-vlist
1.44      crook    8126: @c doc-words-deferred
1.1       anton    8127: 
1.74      anton    8128: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26      crook    8129: doc-root
                   8130: doc-vocabulary
                   8131: doc-seal
                   8132: doc-vocs
                   8133: doc-current
                   8134: doc-context
1.1       anton    8135: 
1.44      crook    8136: 
1.26      crook    8137: @menu
1.75      anton    8138: * Vocabularies::                
1.67      anton    8139: * Why use word lists?::         
1.75      anton    8140: * Word list example::           
1.26      crook    8141: @end menu
                   8142: 
1.75      anton    8143: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
                   8144: @subsection Vocabularies
                   8145: @cindex Vocabularies, detailed explanation
                   8146: 
                   8147: Here is an example of creating and using a new wordlist using ANS
                   8148: Forth words:
                   8149: 
                   8150: @example
                   8151: wordlist constant my-new-words-wordlist
                   8152: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
                   8153: 
                   8154: \ add it to the search order
                   8155: also my-new-words
                   8156: 
                   8157: \ alternatively, add it to the search order and make it
                   8158: \ the compilation word list
                   8159: also my-new-words definitions
                   8160: \ type "order" to see the problem
                   8161: @end example
                   8162: 
                   8163: The problem with this example is that @code{order} has no way to
                   8164: associate the name @code{my-new-words} with the wid of the word list (in
                   8165: Gforth, @code{order} and @code{vocs} will display @code{???}  for a wid
                   8166: that has no associated name). There is no Standard way of associating a
                   8167: name with a wid.
                   8168: 
                   8169: In Gforth, this example can be re-coded using @code{vocabulary}, which
                   8170: associates a name with a wid:
                   8171: 
                   8172: @example
                   8173: vocabulary my-new-words
                   8174: 
                   8175: \ add it to the search order
                   8176: also my-new-words
                   8177: 
                   8178: \ alternatively, add it to the search order and make it
                   8179: \ the compilation word list
                   8180: my-new-words definitions
                   8181: \ type "order" to see that the problem is solved
                   8182: @end example
                   8183: 
                   8184: 
                   8185: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26      crook    8186: @subsection Why use word lists?
                   8187: @cindex word lists - why use them?
                   8188: 
1.74      anton    8189: Here are some reasons why people use wordlists:
1.26      crook    8190: 
                   8191: @itemize @bullet
1.74      anton    8192: 
                   8193: @c anton: Gforth's hashing implementation makes the search speed
                   8194: @c independent from the number of words.  But it is linear with the number
                   8195: @c of wordlists that have to be searched, so in effect using more wordlists
                   8196: @c actually slows down compilation.
                   8197: 
                   8198: @c @item
                   8199: @c To improve compilation speed by reducing the number of header space
                   8200: @c entries that must be searched. This is achieved by creating a new
                   8201: @c word list that contains all of the definitions that are used in the
                   8202: @c definition of a Forth system but which would not usually be used by
                   8203: @c programs running on that system. That word list would be on the search
                   8204: @c list when the Forth system was compiled but would be removed from the
                   8205: @c search list for normal operation. This can be a useful technique for
                   8206: @c low-performance systems (for example, 8-bit processors in embedded
                   8207: @c systems) but is unlikely to be necessary in high-performance desktop
                   8208: @c systems.
                   8209: 
1.26      crook    8210: @item
                   8211: To prevent a set of words from being used outside the context in which
                   8212: they are valid. Two classic examples of this are an integrated editor
                   8213: (all of the edit commands are defined in a separate word list; the
                   8214: search order is set to the editor word list when the editor is invoked;
                   8215: the old search order is restored when the editor is terminated) and an
                   8216: integrated assembler (the op-codes for the machine are defined in a
                   8217: separate word list which is used when a @code{CODE} word is defined).
1.74      anton    8218: 
                   8219: @item
                   8220: To organize the words of an application or library into a user-visible
                   8221: set (in @code{forth-wordlist} or some other common wordlist) and a set
                   8222: of helper words used just for the implementation (hidden in a separate
1.75      anton    8223: wordlist).  This keeps @code{words}' output smaller, separates
                   8224: implementation and interface, and reduces the chance of name conflicts
                   8225: within the common wordlist.
1.74      anton    8226: 
1.26      crook    8227: @item
                   8228: To prevent a name-space clash between multiple definitions with the same
                   8229: name. For example, when building a cross-compiler you might have a word
                   8230: @code{IF} that generates conditional code for your target system. By
                   8231: placing this definition in a different word list you can control whether
                   8232: the host system's @code{IF} or the target system's @code{IF} get used in
                   8233: any particular context by controlling the order of the word lists on the
                   8234: search order stack.
1.74      anton    8235: 
1.26      crook    8236: @end itemize
1.1       anton    8237: 
1.74      anton    8238: The downsides of using wordlists are:
                   8239: 
                   8240: @itemize
                   8241: 
                   8242: @item
                   8243: Debugging becomes more cumbersome.
                   8244: 
                   8245: @item
                   8246: Name conflicts worked around with wordlists are still there, and you
                   8247: have to arrange the search order carefully to get the desired results;
                   8248: if you forget to do that, you get hard-to-find errors (as in any case
                   8249: where you read the code differently from the compiler; @code{see} can
1.75      anton    8250: help seeing which of several possible words the name resolves to in such
                   8251: cases).  @code{See} displays just the name of the words, not what
                   8252: wordlist they belong to, so it might be misleading.  Using unique names
                   8253: is a better approach to avoid name conflicts.
1.74      anton    8254: 
                   8255: @item
                   8256: You have to explicitly undo any changes to the search order.  In many
                   8257: cases it would be more convenient if this happened implicitly.  Gforth
                   8258: currently does not provide such a feature, but it may do so in the
                   8259: future.
                   8260: @end itemize
                   8261: 
                   8262: 
1.75      anton    8263: @node Word list example,  , Why use word lists?, Word Lists
                   8264: @subsection Word list example
                   8265: @cindex word lists - example
1.1       anton    8266: 
1.74      anton    8267: The following example is from the
                   8268: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
                   8269: garbage collector} and uses wordlists to separate public words from
                   8270: helper words:
                   8271: 
                   8272: @example
                   8273: get-current ( wid )
                   8274: vocabulary garbage-collector also garbage-collector definitions
                   8275: ... \ define helper words
                   8276: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
                   8277: ... \ define the public (i.e., API) words
                   8278:     \ they can refer to the helper words
                   8279: previous \ restore original search order (helper words become invisible)
                   8280: @end example
                   8281: 
1.26      crook    8282: @c -------------------------------------------------------------
                   8283: @node Environmental Queries, Files, Word Lists, Words
                   8284: @section Environmental Queries
                   8285: @cindex environmental queries
1.21      crook    8286: 
1.26      crook    8287: ANS Forth introduced the idea of ``environmental queries'' as a way
                   8288: for a program running on a system to determine certain characteristics of the system.
                   8289: The Standard specifies a number of strings that might be recognised by a system.
1.21      crook    8290: 
1.32      anton    8291: The Standard requires that the header space used for environmental queries
                   8292: be distinct from the header space used for definitions.
1.21      crook    8293: 
1.26      crook    8294: Typically, environmental queries are supported by creating a set of
1.29      crook    8295: definitions in a word list that is @i{only} used during environmental
1.26      crook    8296: queries; that is what Gforth does. There is no Standard way of adding
                   8297: definitions to the set of recognised environmental queries, but any
                   8298: implementation that supports the loading of optional word sets must have
                   8299: some mechanism for doing this (after loading the word set, the
                   8300: associated environmental query string must return @code{true}). In
                   8301: Gforth, the word list used to honour environmental queries can be
                   8302: manipulated just like any other word list.
1.21      crook    8303: 
1.44      crook    8304: 
1.26      crook    8305: doc-environment?
                   8306: doc-environment-wordlist
1.21      crook    8307: 
1.26      crook    8308: doc-gforth
                   8309: doc-os-class
1.21      crook    8310: 
1.44      crook    8311: 
1.26      crook    8312: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
                   8313: returning two items on the stack, querying it using @code{environment?}
                   8314: will return an additional item; the @code{true} flag that shows that the
                   8315: string was recognised.
1.21      crook    8316: 
1.26      crook    8317: @comment TODO Document the standard strings or note where they are documented herein
1.21      crook    8318: 
1.26      crook    8319: Here are some examples of using environmental queries:
1.21      crook    8320: 
1.26      crook    8321: @example
                   8322: s" address-unit-bits" environment? 0=
                   8323: [IF]
                   8324:      cr .( environmental attribute address-units-bits unknown... ) cr
1.75      anton    8325: [ELSE]
                   8326:      drop \ ensure balanced stack effect
1.26      crook    8327: [THEN]
1.21      crook    8328: 
1.75      anton    8329: \ this might occur in the prelude of a standard program that uses THROW
                   8330: s" exception" environment? [IF]
                   8331:    0= [IF]
                   8332:       : throw abort" exception thrown" ;
                   8333:    [THEN]
                   8334: [ELSE] \ we don't know, so make sure
                   8335:    : throw abort" exception thrown" ;
                   8336: [THEN]
1.21      crook    8337: 
1.26      crook    8338: s" gforth" environment? [IF] .( Gforth version ) TYPE
                   8339:                         [ELSE] .( Not Gforth..) [THEN]
1.75      anton    8340: 
                   8341: \ a program using v*
                   8342: s" gforth" environment? [IF]
                   8343:   s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
                   8344:    : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8345:      >r swap 2swap swap 0e r> 0 ?DO
1.190     anton    8346:        dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75      anton    8347:      LOOP
                   8348:      2drop 2drop ; 
                   8349:   [THEN]
                   8350: [ELSE] \ 
                   8351:   : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
                   8352:   ...
                   8353: [THEN]
1.26      crook    8354: @end example
1.21      crook    8355: 
1.26      crook    8356: Here is an example of adding a definition to the environment word list:
1.21      crook    8357: 
1.26      crook    8358: @example
                   8359: get-current environment-wordlist set-current
                   8360: true constant block
                   8361: true constant block-ext
                   8362: set-current
                   8363: @end example
1.21      crook    8364: 
1.26      crook    8365: You can see what definitions are in the environment word list like this:
1.21      crook    8366: 
1.26      crook    8367: @example
1.79      anton    8368: environment-wordlist >order words previous
1.26      crook    8369: @end example
1.21      crook    8370: 
                   8371: 
1.26      crook    8372: @c -------------------------------------------------------------
                   8373: @node Files, Blocks, Environmental Queries, Words
                   8374: @section Files
1.28      crook    8375: @cindex files
                   8376: @cindex I/O - file-handling
1.21      crook    8377: 
1.26      crook    8378: Gforth provides facilities for accessing files that are stored in the
                   8379: host operating system's file-system. Files that are processed by Gforth
                   8380: can be divided into two categories:
1.21      crook    8381: 
1.23      crook    8382: @itemize @bullet
                   8383: @item
1.29      crook    8384: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23      crook    8385: @item
1.29      crook    8386: Files that are processed by some other program (@dfn{general files}).
1.26      crook    8387: @end itemize
                   8388: 
                   8389: @menu
1.48      anton    8390: * Forth source files::          
                   8391: * General files::               
1.167     anton    8392: * Redirection::                 
1.48      anton    8393: * Search Paths::                
1.26      crook    8394: @end menu
                   8395: 
                   8396: @c -------------------------------------------------------------
                   8397: @node Forth source files, General files, Files, Files
                   8398: @subsection Forth source files
                   8399: @cindex including files
                   8400: @cindex Forth source files
1.21      crook    8401: 
1.26      crook    8402: The simplest way to interpret the contents of a file is to use one of
                   8403: these two formats:
1.21      crook    8404: 
1.26      crook    8405: @example
                   8406: include mysource.fs
                   8407: s" mysource.fs" included
                   8408: @end example
1.21      crook    8409: 
1.75      anton    8410: You usually want to include a file only if it is not included already
1.26      crook    8411: (by, say, another source file). In that case, you can use one of these
1.45      crook    8412: three formats:
1.21      crook    8413: 
1.26      crook    8414: @example
                   8415: require mysource.fs
                   8416: needs mysource.fs
                   8417: s" mysource.fs" required
                   8418: @end example
1.21      crook    8419: 
1.26      crook    8420: @cindex stack effect of included files
                   8421: @cindex including files, stack effect
1.45      crook    8422: It is good practice to write your source files such that interpreting them
                   8423: does not change the stack. Source files designed in this way can be used with
1.26      crook    8424: @code{required} and friends without complications. For example:
1.21      crook    8425: 
1.26      crook    8426: @example
1.75      anton    8427: 1024 require foo.fs drop
1.26      crook    8428: @end example
1.21      crook    8429: 
1.75      anton    8430: Here you want to pass the argument 1024 (e.g., a buffer size) to
                   8431: @file{foo.fs}.  Interpreting @file{foo.fs} has the stack effect ( n -- n
                   8432: ), which allows its use with @code{require}.  Of course with such
                   8433: parameters to required files, you have to ensure that the first
                   8434: @code{require} fits for all uses (i.e., @code{require} it early in the
                   8435: master load file).
1.44      crook    8436: 
1.26      crook    8437: doc-include-file
                   8438: doc-included
1.28      crook    8439: doc-included?
1.26      crook    8440: doc-include
                   8441: doc-required
                   8442: doc-require
                   8443: doc-needs
1.75      anton    8444: @c doc-init-included-files @c internal
                   8445: doc-sourcefilename
                   8446: doc-sourceline#
1.44      crook    8447: 
1.26      crook    8448: A definition in ANS Forth for @code{required} is provided in
                   8449: @file{compat/required.fs}.
1.21      crook    8450: 
1.26      crook    8451: @c -------------------------------------------------------------
1.167     anton    8452: @node General files, Redirection, Forth source files, Files
1.26      crook    8453: @subsection General files
                   8454: @cindex general files
                   8455: @cindex file-handling
1.21      crook    8456: 
1.75      anton    8457: Files are opened/created by name and type. The following file access
                   8458: methods (FAMs) are recognised:
1.44      crook    8459: 
1.75      anton    8460: @cindex fam (file access method)
1.26      crook    8461: doc-r/o
                   8462: doc-r/w
                   8463: doc-w/o
                   8464: doc-bin
1.1       anton    8465: 
1.44      crook    8466: 
1.26      crook    8467: When a file is opened/created, it returns a file identifier,
1.29      crook    8468: @i{wfileid} that is used for all other file commands. All file
                   8469: commands also return a status value, @i{wior}, that is 0 for a
1.26      crook    8470: successful operation and an implementation-defined non-zero value in the
                   8471: case of an error.
1.21      crook    8472: 
1.44      crook    8473: 
1.26      crook    8474: doc-open-file
                   8475: doc-create-file
1.21      crook    8476: 
1.26      crook    8477: doc-close-file
                   8478: doc-delete-file
                   8479: doc-rename-file
                   8480: doc-read-file
                   8481: doc-read-line
1.154     anton    8482: doc-key-file
                   8483: doc-key?-file
1.26      crook    8484: doc-write-file
                   8485: doc-write-line
                   8486: doc-emit-file
                   8487: doc-flush-file
1.21      crook    8488: 
1.26      crook    8489: doc-file-status
                   8490: doc-file-position
                   8491: doc-reposition-file
                   8492: doc-file-size
                   8493: doc-resize-file
1.21      crook    8494: 
1.93      anton    8495: doc-slurp-file
                   8496: doc-slurp-fid
1.112     anton    8497: doc-stdin
                   8498: doc-stdout
                   8499: doc-stderr
1.44      crook    8500: 
1.26      crook    8501: @c ---------------------------------------------------------
1.167     anton    8502: @node Redirection, Search Paths, General files, Files
                   8503: @subsection Redirection
                   8504: @cindex Redirection
                   8505: @cindex Input Redirection
                   8506: @cindex Output Redirection
                   8507: 
                   8508: You can redirect the output of @code{type} and @code{emit} and all the
                   8509: words that use them (all output words that don't have an explicit
1.174     anton    8510: target file) to an arbitrary file with the @code{outfile-execute},
                   8511: used like this:
1.167     anton    8512: 
                   8513: @example
1.174     anton    8514: : some-warning ( n -- )
                   8515:     cr ." warning# " . ;
                   8516: 
1.167     anton    8517: : print-some-warning ( n -- )
1.174     anton    8518:     ['] some-warning stderr outfile-execute ;
1.167     anton    8519: @end example
                   8520: 
1.174     anton    8521: After @code{some-warning} is executed, the original output direction
                   8522: is restored; this construct is safe against exceptions.  Similarly,
                   8523: there is @code{infile-execute} for redirecting the input of @code{key}
                   8524: and its users (any input word that does not take a file explicitly).
                   8525: 
                   8526: doc-outfile-execute
                   8527: doc-infile-execute
1.167     anton    8528: 
                   8529: If you do not want to redirect the input or output to a file, you can
                   8530: also make use of the fact that @code{key}, @code{emit} and @code{type}
                   8531: are deferred words (@pxref{Deferred Words}).  However, in that case
                   8532: you have to worry about the restoration and the protection against
                   8533: exceptions yourself; also, note that for redirecting the output in
                   8534: this way, you have to redirect both @code{emit} and @code{type}.
                   8535: 
                   8536: @c ---------------------------------------------------------
                   8537: @node Search Paths,  , Redirection, Files
1.26      crook    8538: @subsection Search Paths
                   8539: @cindex path for @code{included}
                   8540: @cindex file search path
                   8541: @cindex @code{include} search path
                   8542: @cindex search path for files
1.21      crook    8543: 
1.26      crook    8544: If you specify an absolute filename (i.e., a filename starting with
                   8545: @file{/} or @file{~}, or with @file{:} in the second position (as in
                   8546: @samp{C:...})) for @code{included} and friends, that file is included
                   8547: just as you would expect.
1.21      crook    8548: 
1.75      anton    8549: If the filename starts with @file{./}, this refers to the directory that
                   8550: the present file was @code{included} from.  This allows files to include
                   8551: other files relative to their own position (irrespective of the current
                   8552: working directory or the absolute position).  This feature is essential
                   8553: for libraries consisting of several files, where a file may include
                   8554: other files from the library.  It corresponds to @code{#include "..."}
                   8555: in C. If the current input source is not a file, @file{.} refers to the
                   8556: directory of the innermost file being included, or, if there is no file
                   8557: being included, to the current working directory.
                   8558: 
                   8559: For relative filenames (not starting with @file{./}), Gforth uses a
                   8560: search path similar to Forth's search order (@pxref{Word Lists}). It
                   8561: tries to find the given filename in the directories present in the path,
                   8562: and includes the first one it finds. There are separate search paths for
                   8563: Forth source files and general files.  If the search path contains the
                   8564: directory @file{.}, this refers to the directory of the current file, or
                   8565: the working directory, as if the file had been specified with @file{./}.
1.21      crook    8566: 
1.26      crook    8567: Use @file{~+} to refer to the current working directory (as in the
                   8568: @code{bash}).
1.1       anton    8569: 
1.75      anton    8570: @c anton: fold the following subsubsections into this subsection?
1.1       anton    8571: 
1.48      anton    8572: @menu
1.75      anton    8573: * Source Search Paths::         
1.48      anton    8574: * General Search Paths::        
                   8575: @end menu
                   8576: 
1.26      crook    8577: @c ---------------------------------------------------------
1.75      anton    8578: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
                   8579: @subsubsection Source Search Paths
                   8580: @cindex search path control, source files
1.5       anton    8581: 
1.26      crook    8582: The search path is initialized when you start Gforth (@pxref{Invoking
1.75      anton    8583: Gforth}). You can display it and change it using @code{fpath} in
                   8584: combination with the general path handling words.
1.5       anton    8585: 
1.75      anton    8586: doc-fpath
                   8587: @c the functionality of the following words is easily available through
                   8588: @c   fpath and the general path words.  The may go away.
                   8589: @c doc-.fpath
                   8590: @c doc-fpath+
                   8591: @c doc-fpath=
                   8592: @c doc-open-fpath-file
1.44      crook    8593: 
                   8594: @noindent
1.26      crook    8595: Here is an example of using @code{fpath} and @code{require}:
1.5       anton    8596: 
1.26      crook    8597: @example
1.75      anton    8598: fpath path= /usr/lib/forth/|./
1.26      crook    8599: require timer.fs
                   8600: @end example
1.5       anton    8601: 
1.75      anton    8602: 
1.26      crook    8603: @c ---------------------------------------------------------
1.75      anton    8604: @node General Search Paths,  , Source Search Paths, Search Paths
1.26      crook    8605: @subsubsection General Search Paths
1.75      anton    8606: @cindex search path control, source files
1.5       anton    8607: 
1.26      crook    8608: Your application may need to search files in several directories, like
                   8609: @code{included} does. To facilitate this, Gforth allows you to define
                   8610: and use your own search paths, by providing generic equivalents of the
                   8611: Forth search path words:
1.5       anton    8612: 
1.75      anton    8613: doc-open-path-file
                   8614: doc-path-allot
                   8615: doc-clear-path
                   8616: doc-also-path
1.26      crook    8617: doc-.path
                   8618: doc-path+
                   8619: doc-path=
1.5       anton    8620: 
1.75      anton    8621: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44      crook    8622: 
1.75      anton    8623: Here's an example of creating an empty search path:
                   8624: @c
1.26      crook    8625: @example
1.75      anton    8626: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26      crook    8627: @end example
1.5       anton    8628: 
1.26      crook    8629: @c -------------------------------------------------------------
                   8630: @node Blocks, Other I/O, Files, Words
                   8631: @section Blocks
1.28      crook    8632: @cindex I/O - blocks
                   8633: @cindex blocks
                   8634: 
                   8635: When you run Gforth on a modern desk-top computer, it runs under the
                   8636: control of an operating system which provides certain services.  One of
                   8637: these services is @var{file services}, which allows Forth source code
                   8638: and data to be stored in files and read into Gforth (@pxref{Files}).
                   8639: 
                   8640: Traditionally, Forth has been an important programming language on
                   8641: systems where it has interfaced directly to the underlying hardware with
                   8642: no intervening operating system. Forth provides a mechanism, called
1.29      crook    8643: @dfn{blocks}, for accessing mass storage on such systems.
1.28      crook    8644: 
                   8645: A block is a 1024-byte data area, which can be used to hold data or
                   8646: Forth source code. No structure is imposed on the contents of the
                   8647: block. A block is identified by its number; blocks are numbered
                   8648: contiguously from 1 to an implementation-defined maximum.
                   8649: 
                   8650: A typical system that used blocks but no operating system might use a
                   8651: single floppy-disk drive for mass storage, with the disks formatted to
                   8652: provide 256-byte sectors. Blocks would be implemented by assigning the
                   8653: first four sectors of the disk to block 1, the second four sectors to
                   8654: block 2 and so on, up to the limit of the capacity of the disk. The disk
                   8655: would not contain any file system information, just the set of blocks.
                   8656: 
1.29      crook    8657: @cindex blocks file
1.28      crook    8658: On systems that do provide file services, blocks are typically
1.29      crook    8659: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28      crook    8660: file}.  The size of the blocks file will be an exact multiple of 1024
                   8661: bytes, corresponding to the number of blocks it contains. This is the
                   8662: mechanism that Gforth uses.
                   8663: 
1.29      crook    8664: @cindex @file{blocks.fb}
1.75      anton    8665: Only one blocks file can be open at a time. If you use block words without
1.28      crook    8666: having specified a blocks file, Gforth defaults to the blocks file
                   8667: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75      anton    8668: locate a blocks file (@pxref{Source Search Paths}).
1.28      crook    8669: 
1.29      crook    8670: @cindex block buffers
1.28      crook    8671: When you read and write blocks under program control, Gforth uses a
1.29      crook    8672: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28      crook    8673: not used when you use @code{load} to interpret the contents of a block.
                   8674: 
1.75      anton    8675: The behaviour of the block buffers is analagous to that of a cache.
                   8676: Each block buffer has three states:
1.28      crook    8677: 
                   8678: @itemize @bullet
                   8679: @item
                   8680: Unassigned
                   8681: @item
                   8682: Assigned-clean
                   8683: @item
                   8684: Assigned-dirty
                   8685: @end itemize
                   8686: 
1.29      crook    8687: Initially, all block buffers are @i{unassigned}. In order to access a
1.28      crook    8688: block, the block (specified by its block number) must be assigned to a
                   8689: block buffer.
                   8690: 
                   8691: The assignment of a block to a block buffer is performed by @code{block}
                   8692: or @code{buffer}. Use @code{block} when you wish to modify the existing
                   8693: contents of a block. Use @code{buffer} when you don't care about the
                   8694: existing contents of the block@footnote{The ANS Forth definition of
1.35      anton    8695: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28      crook    8696: with the particular block is already stored in a block buffer due to an
                   8697: earlier @code{block} command, @code{buffer} will return that block
                   8698: buffer and the existing contents of the block will be
                   8699: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29      crook    8700: block buffer for the block.}.
1.28      crook    8701: 
1.47      crook    8702: Once a block has been assigned to a block buffer using @code{block} or
1.75      anton    8703: @code{buffer}, that block buffer becomes the @i{current block
                   8704: buffer}. Data may only be manipulated (read or written) within the
                   8705: current block buffer.
1.47      crook    8706: 
                   8707: When the contents of the current block buffer has been modified it is
1.48      anton    8708: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75      anton    8709: either abandon the changes (by doing nothing) or mark the block as
                   8710: changed (assigned-dirty), using @code{update}. Using @code{update} does
                   8711: not change the blocks file; it simply changes a block buffer's state to
                   8712: @i{assigned-dirty}.  The block will be written implicitly when it's
                   8713: buffer is needed for another block, or explicitly by @code{flush} or
                   8714: @code{save-buffers}.
                   8715: 
                   8716: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
                   8717: blocks file on disk. Leaving Gforth with @code{bye} also performs a
                   8718: @code{flush}.
1.28      crook    8719: 
1.29      crook    8720: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28      crook    8721: algorithm to assign a block buffer to a block. That means that any
                   8722: particular block can only be assigned to one specific block buffer,
1.29      crook    8723: called (for the particular operation) the @i{victim buffer}. If the
1.47      crook    8724: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
                   8725: the new block immediately. If it is @i{assigned-dirty} its current
                   8726: contents are written back to the blocks file on disk before it is
1.28      crook    8727: allocated to the new block.
                   8728: 
                   8729: Although no structure is imposed on the contents of a block, it is
                   8730: traditional to display the contents as 16 lines each of 64 characters.  A
                   8731: block provides a single, continuous stream of input (for example, it
                   8732: acts as a single parse area) -- there are no end-of-line characters
                   8733: within a block, and no end-of-file character at the end of a
                   8734: block. There are two consequences of this:
1.26      crook    8735: 
1.28      crook    8736: @itemize @bullet
                   8737: @item
                   8738: The last character of one line wraps straight into the first character
                   8739: of the following line
                   8740: @item
                   8741: The word @code{\} -- comment to end of line -- requires special
                   8742: treatment; in the context of a block it causes all characters until the
                   8743: end of the current 64-character ``line'' to be ignored.
                   8744: @end itemize
                   8745: 
                   8746: In Gforth, when you use @code{block} with a non-existent block number,
1.45      crook    8747: the current blocks file will be extended to the appropriate size and the
1.28      crook    8748: block buffer will be initialised with spaces.
                   8749: 
1.47      crook    8750: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
                   8751: for details) but doesn't encourage the use of blocks; the mechanism is
                   8752: only provided for backward compatibility -- ANS Forth requires blocks to
                   8753: be available when files are.
1.28      crook    8754: 
                   8755: Common techniques that are used when working with blocks include:
                   8756: 
                   8757: @itemize @bullet
                   8758: @item
                   8759: A screen editor that allows you to edit blocks without leaving the Forth
                   8760: environment.
                   8761: @item
                   8762: Shadow screens; where every code block has an associated block
                   8763: containing comments (for example: code in odd block numbers, comments in
                   8764: even block numbers). Typically, the block editor provides a convenient
                   8765: mechanism to toggle between code and comments.
                   8766: @item
                   8767: Load blocks; a single block (typically block 1) contains a number of
                   8768: @code{thru} commands which @code{load} the whole of the application.
                   8769: @end itemize
1.26      crook    8770: 
1.29      crook    8771: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
                   8772: integrated into a Forth programming environment.
1.26      crook    8773: 
                   8774: @comment TODO what about errors on open-blocks?
1.44      crook    8775: 
1.26      crook    8776: doc-open-blocks
                   8777: doc-use
1.75      anton    8778: doc-block-offset
1.26      crook    8779: doc-get-block-fid
                   8780: doc-block-position
1.28      crook    8781: 
1.75      anton    8782: doc-list
1.28      crook    8783: doc-scr
                   8784: 
1.184     anton    8785: doc-block
1.28      crook    8786: doc-buffer
                   8787: 
1.75      anton    8788: doc-empty-buffers
                   8789: doc-empty-buffer
1.26      crook    8790: doc-update
1.28      crook    8791: doc-updated?
1.26      crook    8792: doc-save-buffers
1.75      anton    8793: doc-save-buffer
1.26      crook    8794: doc-flush
1.28      crook    8795: 
1.26      crook    8796: doc-load
                   8797: doc-thru
                   8798: doc-+load
                   8799: doc-+thru
1.45      crook    8800: doc---gforthman--->
1.26      crook    8801: doc-block-included
                   8802: 
1.44      crook    8803: 
1.26      crook    8804: @c -------------------------------------------------------------
1.126     pazsan   8805: @node Other I/O, OS command line arguments, Blocks, Words
1.26      crook    8806: @section Other I/O
1.28      crook    8807: @cindex I/O - keyboard and display
1.26      crook    8808: 
                   8809: @menu
                   8810: * Simple numeric output::       Predefined formats
                   8811: * Formatted numeric output::    Formatted (pictured) output
                   8812: * String Formats::              How Forth stores strings in memory
1.67      anton    8813: * Displaying characters and strings::  Other stuff
1.175     anton    8814: * Terminal output::             Cursor positioning etc.
1.181     anton    8815: * Single-key input::            
                   8816: * Line input and conversion::   
1.112     anton    8817: * Pipes::                       How to create your own pipes
1.149     pazsan   8818: * Xchars and Unicode::          Non-ASCII characters
1.26      crook    8819: @end menu
                   8820: 
                   8821: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
                   8822: @subsection Simple numeric output
1.28      crook    8823: @cindex numeric output - simple/free-format
1.5       anton    8824: 
1.26      crook    8825: The simplest output functions are those that display numbers from the
                   8826: data or floating-point stacks. Floating-point output is always displayed
                   8827: using base 10. Numbers displayed from the data stack use the value stored
                   8828: in @code{base}.
1.5       anton    8829: 
1.44      crook    8830: 
1.26      crook    8831: doc-.
                   8832: doc-dec.
                   8833: doc-hex.
                   8834: doc-u.
                   8835: doc-.r
                   8836: doc-u.r
                   8837: doc-d.
                   8838: doc-ud.
                   8839: doc-d.r
                   8840: doc-ud.r
                   8841: doc-f.
                   8842: doc-fe.
                   8843: doc-fs.
1.111     anton    8844: doc-f.rdp
1.44      crook    8845: 
1.26      crook    8846: Examples of printing the number 1234.5678E23 in the different floating-point output
                   8847: formats are shown below:
1.5       anton    8848: 
                   8849: @example
1.26      crook    8850: f. 123456779999999000000000000.
                   8851: fe. 123.456779999999E24
                   8852: fs. 1.23456779999999E26
1.5       anton    8853: @end example
                   8854: 
                   8855: 
1.26      crook    8856: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
                   8857: @subsection Formatted numeric output
1.28      crook    8858: @cindex formatted numeric output
1.26      crook    8859: @cindex pictured numeric output
1.28      crook    8860: @cindex numeric output - formatted
1.26      crook    8861: 
1.29      crook    8862: Forth traditionally uses a technique called @dfn{pictured numeric
1.26      crook    8863: output} for formatted printing of integers.  In this technique, digits
                   8864: are extracted from the number (using the current output radix defined by
                   8865: @code{base}), converted to ASCII codes and appended to a string that is
                   8866: built in a scratch-pad area of memory (@pxref{core-idef,
                   8867: Implementation-defined options, Implementation-defined
                   8868: options}). Arbitrary characters can be appended to the string during the
                   8869: extraction process. The completed string is specified by an address
                   8870: and length and can be manipulated (@code{TYPE}ed, copied, modified)
                   8871: under program control.
1.5       anton    8872: 
1.75      anton    8873: All of the integer output words described in the previous section
                   8874: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
                   8875: numeric output.
1.5       anton    8876: 
1.47      crook    8877: Three important things to remember about pictured numeric output:
1.5       anton    8878: 
1.26      crook    8879: @itemize @bullet
                   8880: @item
1.28      crook    8881: It always operates on double-precision numbers; to display a
1.49      anton    8882: single-precision number, convert it first (for ways of doing this
                   8883: @pxref{Double precision}).
1.26      crook    8884: @item
1.28      crook    8885: It always treats the double-precision number as though it were
                   8886: unsigned. The examples below show ways of printing signed numbers.
1.26      crook    8887: @item
                   8888: The string is built up from right to left; least significant digit first.
                   8889: @end itemize
1.5       anton    8890: 
1.44      crook    8891: 
1.26      crook    8892: doc-<#
1.47      crook    8893: doc-<<#
1.26      crook    8894: doc-#
                   8895: doc-#s
                   8896: doc-hold
                   8897: doc-sign
                   8898: doc-#>
1.47      crook    8899: doc-#>>
1.5       anton    8900: 
1.26      crook    8901: doc-represent
1.111     anton    8902: doc-f>str-rdp
                   8903: doc-f>buf-rdp
1.5       anton    8904: 
1.44      crook    8905: 
                   8906: @noindent
1.26      crook    8907: Here are some examples of using pictured numeric output:
1.5       anton    8908: 
                   8909: @example
1.26      crook    8910: : my-u. ( u -- )
                   8911:   \ Simplest use of pns.. behaves like Standard u. 
                   8912:   0              \ convert to unsigned double
1.75      anton    8913:   <<#            \ start conversion
1.26      crook    8914:   #s             \ convert all digits
                   8915:   #>             \ complete conversion
1.75      anton    8916:   TYPE SPACE     \ display, with trailing space
                   8917:   #>> ;          \ release hold area
1.5       anton    8918: 
1.26      crook    8919: : cents-only ( u -- )
                   8920:   0              \ convert to unsigned double
1.75      anton    8921:   <<#            \ start conversion
1.26      crook    8922:   # #            \ convert two least-significant digits
                   8923:   #>             \ complete conversion, discard other digits
1.75      anton    8924:   TYPE SPACE     \ display, with trailing space
                   8925:   #>> ;          \ release hold area
1.5       anton    8926: 
1.26      crook    8927: : dollars-and-cents ( u -- )
                   8928:   0              \ convert to unsigned double
1.75      anton    8929:   <<#            \ start conversion
1.26      crook    8930:   # #            \ convert two least-significant digits
                   8931:   [char] . hold  \ insert decimal point
                   8932:   #s             \ convert remaining digits
                   8933:   [char] $ hold  \ append currency symbol
                   8934:   #>             \ complete conversion
1.75      anton    8935:   TYPE SPACE     \ display, with trailing space
                   8936:   #>> ;          \ release hold area
1.5       anton    8937: 
1.26      crook    8938: : my-. ( n -- )
                   8939:   \ handling negatives.. behaves like Standard .
                   8940:   s>d            \ convert to signed double
                   8941:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8942:   <<#            \ start conversion
1.26      crook    8943:   #s             \ convert all digits
                   8944:   rot sign       \ get at sign byte, append "-" if needed
                   8945:   #>             \ complete conversion
1.75      anton    8946:   TYPE SPACE     \ display, with trailing space
                   8947:   #>> ;          \ release hold area
1.5       anton    8948: 
1.26      crook    8949: : account. ( n -- )
1.75      anton    8950:   \ accountants don't like minus signs, they use parentheses
1.26      crook    8951:   \ for negative numbers
                   8952:   s>d            \ convert to signed double
                   8953:   swap over dabs \ leave sign byte followed by unsigned double
1.75      anton    8954:   <<#            \ start conversion
1.26      crook    8955:   2 pick         \ get copy of sign byte
                   8956:   0< IF [char] ) hold THEN \ right-most character of output
                   8957:   #s             \ convert all digits
                   8958:   rot            \ get at sign byte
                   8959:   0< IF [char] ( hold THEN
                   8960:   #>             \ complete conversion
1.75      anton    8961:   TYPE SPACE     \ display, with trailing space
                   8962:   #>> ;          \ release hold area
                   8963: 
1.5       anton    8964: @end example
                   8965: 
1.26      crook    8966: Here are some examples of using these words:
1.5       anton    8967: 
                   8968: @example
1.26      crook    8969: 1 my-u. 1
                   8970: hex -1 my-u. decimal FFFFFFFF
                   8971: 1 cents-only 01
                   8972: 1234 cents-only 34
                   8973: 2 dollars-and-cents $0.02
                   8974: 1234 dollars-and-cents $12.34
                   8975: 123 my-. 123
                   8976: -123 my. -123
                   8977: 123 account. 123
                   8978: -456 account. (456)
1.5       anton    8979: @end example
                   8980: 
                   8981: 
1.26      crook    8982: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
                   8983: @subsection String Formats
1.27      crook    8984: @cindex strings - see character strings
                   8985: @cindex character strings - formats
1.28      crook    8986: @cindex I/O - see character strings
1.75      anton    8987: @cindex counted strings
                   8988: 
                   8989: @c anton: this does not really belong here; maybe the memory section,
                   8990: @c  or the principles chapter
1.26      crook    8991: 
1.27      crook    8992: Forth commonly uses two different methods for representing character
                   8993: strings:
1.26      crook    8994: 
                   8995: @itemize @bullet
                   8996: @item
                   8997: @cindex address of counted string
1.45      crook    8998: @cindex counted string
1.29      crook    8999: As a @dfn{counted string}, represented by a @i{c-addr}. The char
                   9000: addressed by @i{c-addr} contains a character-count, @i{n}, of the
                   9001: string and the string occupies the subsequent @i{n} char addresses in
1.26      crook    9002: memory.
                   9003: @item
1.29      crook    9004: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
                   9005: of the string in characters, and @i{c-addr} is the address of the
1.26      crook    9006: first byte of the string.
                   9007: @end itemize
                   9008: 
                   9009: ANS Forth encourages the use of the second format when representing
1.75      anton    9010: strings.
1.26      crook    9011: 
1.44      crook    9012: 
1.26      crook    9013: doc-count
                   9014: 
1.44      crook    9015: 
1.49      anton    9016: For words that move, copy and search for strings see @ref{Memory
                   9017: Blocks}. For words that display characters and strings see
                   9018: @ref{Displaying characters and strings}.
1.26      crook    9019: 
1.175     anton    9020: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26      crook    9021: @subsection Displaying characters and strings
1.27      crook    9022: @cindex characters - compiling and displaying
                   9023: @cindex character strings - compiling and displaying
1.26      crook    9024: 
                   9025: This section starts with a glossary of Forth words and ends with a set
                   9026: of examples.
                   9027: 
                   9028: doc-bl
                   9029: doc-space
                   9030: doc-spaces
                   9031: doc-emit
                   9032: doc-toupper
                   9033: doc-."
                   9034: doc-.(
1.98      anton    9035: doc-.\"
1.26      crook    9036: doc-type
1.44      crook    9037: doc-typewhite
1.26      crook    9038: doc-cr
1.27      crook    9039: @cindex cursor control
1.26      crook    9040: doc-s"
1.98      anton    9041: doc-s\"
1.26      crook    9042: doc-c"
                   9043: doc-char
                   9044: doc-[char]
                   9045: 
1.44      crook    9046: 
                   9047: @noindent
1.26      crook    9048: As an example, consider the following text, stored in a file @file{test.fs}:
1.5       anton    9049: 
                   9050: @example
1.26      crook    9051: .( text-1)
                   9052: : my-word
                   9053:   ." text-2" cr
                   9054:   .( text-3)
                   9055: ;
                   9056: 
                   9057: ." text-4"
                   9058: 
                   9059: : my-char
                   9060:   [char] ALPHABET emit
                   9061:   char emit
                   9062: ;
1.5       anton    9063: @end example
                   9064: 
1.26      crook    9065: When you load this code into Gforth, the following output is generated:
1.5       anton    9066: 
1.26      crook    9067: @example
1.30      anton    9068: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26      crook    9069: @end example
1.5       anton    9070: 
1.26      crook    9071: @itemize @bullet
                   9072: @item
                   9073: Messages @code{text-1} and @code{text-3} are displayed because @code{.(} 
                   9074: is an immediate word; it behaves in the same way whether it is used inside
                   9075: or outside a colon definition.
                   9076: @item
                   9077: Message @code{text-4} is displayed because of Gforth's added interpretation
                   9078: semantics for @code{."}.
                   9079: @item
1.29      crook    9080: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26      crook    9081: performs the compilation semantics for @code{."} within the definition of
                   9082: @code{my-word}.
                   9083: @end itemize
1.5       anton    9084: 
1.26      crook    9085: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5       anton    9086: 
1.26      crook    9087: @example
1.30      anton    9088: @kbd{my-word @key{RET}} text-2
1.26      crook    9089:  ok
1.30      anton    9090: @kbd{my-char fred @key{RET}} Af ok
                   9091: @kbd{my-char jim @key{RET}} Aj ok
1.26      crook    9092: @end example
1.5       anton    9093: 
                   9094: @itemize @bullet
                   9095: @item
1.26      crook    9096: Message @code{text-2} is displayed because of the run-time behaviour of
                   9097: @code{."}.
                   9098: @item
                   9099: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
                   9100: on the stack at run-time. @code{emit} always displays the character
                   9101: when @code{my-char} is executed.
                   9102: @item
                   9103: @code{char} parses a string at run-time and the second @code{emit} displays
                   9104: the first character of the string.
1.5       anton    9105: @item
1.26      crook    9106: If you type @code{see my-char} you can see that @code{[char]} discarded
                   9107: the text ``LPHABET'' and only compiled the display code for ``A'' into the
                   9108: definition of @code{my-char}.
1.5       anton    9109: @end itemize
                   9110: 
                   9111: 
1.181     anton    9112: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175     anton    9113: @subsection Terminal output
                   9114: @cindex output to terminal
                   9115: @cindex terminal output
                   9116: 
                   9117: If you are outputting to a terminal, you may want to control the
                   9118: positioning of the cursor:
                   9119: @cindex cursor positioning
                   9120: 
                   9121: doc-at-xy
                   9122: 
                   9123: In order to know where to position the cursor, it is often helpful to
                   9124: know the size of the screen:
                   9125: @cindex terminal size 
                   9126: 
                   9127: doc-form
                   9128: 
                   9129: And sometimes you want to use:
                   9130: @cindex clear screen
                   9131: 
                   9132: doc-page
                   9133: 
                   9134: Note that on non-terminals you should use @code{12 emit}, not
                   9135: @code{page}, to get a form feed.
                   9136: 
1.5       anton    9137: 
1.181     anton    9138: @node Single-key input, Line input and conversion, Terminal output, Other I/O
                   9139: @subsection Single-key input
                   9140: @cindex single-key input
                   9141: @cindex input, single-key
                   9142: 
                   9143: If you want to get a single printable character, you can use
                   9144: @code{key}; to check whether a character is available for @code{key},
                   9145: you can use @code{key?}.
1.5       anton    9146: 
1.181     anton    9147: doc-key
                   9148: doc-key?
1.27      crook    9149: 
1.181     anton    9150: If you want to process a mix of printable and non-printable
                   9151: characters, you can do that with @code{ekey} and friends.  @code{Ekey}
                   9152: produces a keyboard event that you have to convert into a character
                   9153: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
                   9154: 
                   9155: Typical code for using EKEY looks like this:
                   9156: 
                   9157: @example
                   9158: ekey ekey>char if ( c )
                   9159:   ... \ do something with the character
                   9160: else ekey>fkey if ( key-id )
                   9161:   case
                   9162:     k-up                                  of ... endof
                   9163:     k-f1                                  of ... endof
                   9164:     k-left k-shift-mask or k-ctrl-mask or of ... endof
                   9165:     ...
                   9166:   endcase
                   9167: else ( keyboard-event )
                   9168:   drop \ just ignore an unknown keyboard event type
                   9169: then then
                   9170: @end example
1.44      crook    9171: 
1.45      crook    9172: doc-ekey
1.141     anton    9173: doc-ekey>char
1.181     anton    9174: doc-ekey>fkey
1.45      crook    9175: doc-ekey?
1.141     anton    9176: 
1.181     anton    9177: The key identifiers for cursor keys are:
1.141     anton    9178: 
                   9179: doc-k-left
                   9180: doc-k-right
1.185     anton    9181: doc-k-up
                   9182: doc-k-down
                   9183: doc-k-home
                   9184: doc-k-end
1.141     anton    9185: doc-k-prior
                   9186: doc-k-next
                   9187: doc-k-insert
                   9188: doc-k-delete
                   9189: 
1.181     anton    9190: The key identifiers for function keys (aka keypad keys) are:
1.141     anton    9191: 
1.181     anton    9192: doc-k-f1
                   9193: doc-k-f2
                   9194: doc-k-f3
                   9195: doc-k-f4
                   9196: doc-k-f5
                   9197: doc-k-f6
                   9198: doc-k-f7
                   9199: doc-k-f8
                   9200: doc-k-f9
                   9201: doc-k-f10
                   9202: doc-k-f11
                   9203: doc-k-f12
                   9204: 
                   9205: Note that @code{k-f11} and @code{k-f12} are not as widely available.
                   9206: 
                   9207: You can combine these key identifiers with masks for various shift keys:
                   9208: 
                   9209: doc-k-shift-mask
                   9210: doc-k-ctrl-mask
                   9211: doc-k-alt-mask
                   9212: 
                   9213: Note that, even if a Forth system has @code{ekey>fkey} and the key
                   9214: identifier words, the keys are not necessarily available or it may not
                   9215: necessarily be able to report all the keys and all the possible
                   9216: combinations with shift masks.  Therefore, write your programs in such
                   9217: a way that they are still useful even if the keys and key combinations
                   9218: cannot be pressed or are not recognized.
                   9219: 
                   9220: Examples: Older keyboards often do not have an F11 and F12 key.  If
                   9221: you run Gforth in an xterm, the xterm catches a number of combinations
                   9222: (e.g., @key{Shift-Up}), and never passes it to Gforth.  Finally,
                   9223: Gforth currently does not recognize and report combinations with
                   9224: multiple shift keys (so the @key{shift-ctrl-left} case in the example
                   9225: above would never be entered).
                   9226: 
                   9227: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
                   9228: you need the ANSI.SYS driver to get that behaviour); it works by
                   9229: recognizing the escape sequences that ANSI terminals send when such a
                   9230: key is pressed.  If you have a terminal that sends other escape
                   9231: sequences, you will not get useful results on Gforth.  Other Forth
                   9232: systems may work in a different way.
                   9233: 
                   9234: 
                   9235: @node  Line input and conversion, Pipes, Single-key input, Other I/O
                   9236: @subsection Line input and conversion
                   9237: @cindex line input from terminal
                   9238: @cindex input, linewise from terminal
                   9239: @cindex convertin strings to numbers
                   9240: @cindex I/O - see input
                   9241: 
                   9242: For ways of storing character strings in memory see @ref{String Formats}.
                   9243: 
                   9244: @comment TODO examples for >number >float accept key key? pad parse word refill
                   9245: @comment then index them
1.141     anton    9246: 
                   9247: Words for inputting one line from the keyboard:
                   9248: 
                   9249: doc-accept
                   9250: doc-edit-line
                   9251: 
                   9252: Conversion words:
                   9253: 
1.143     anton    9254: doc-s>number?
                   9255: doc-s>unumber?
1.26      crook    9256: doc->number
                   9257: doc->float
1.143     anton    9258: 
1.141     anton    9259: 
1.27      crook    9260: @comment obsolescent words..
1.141     anton    9261: Obsolescent input and conversion words:
                   9262: 
1.27      crook    9263: doc-convert
1.26      crook    9264: doc-expect
1.27      crook    9265: doc-span
1.5       anton    9266: 
                   9267: 
1.181     anton    9268: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112     anton    9269: @subsection Pipes
                   9270: @cindex pipes, creating your own
                   9271: 
                   9272: In addition to using Gforth in pipes created by other processes
                   9273: (@pxref{Gforth in pipes}), you can create your own pipe with
                   9274: @code{open-pipe}, and read from or write to it.
                   9275: 
                   9276: doc-open-pipe
                   9277: doc-close-pipe
                   9278: 
                   9279: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
                   9280: you don't catch this exception, Gforth will catch it and exit, usually
                   9281: silently (@pxref{Gforth in pipes}).  Since you probably do not want
                   9282: this, you should wrap a @code{catch} or @code{try} block around the code
                   9283: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
                   9284: problem yourself, and then return to regular processing.
                   9285: 
                   9286: doc-broken-pipe-error
                   9287: 
1.155     anton    9288: @node Xchars and Unicode,  , Pipes, Other I/O
                   9289: @subsection Xchars and Unicode
1.149     pazsan   9290: 
1.188     pazsan   9291: ASCII is only appropriate for the English language. Most western
                   9292: languages however fit somewhat into the Forth frame, since a byte is
                   9293: sufficient to encode the few special characters in each (though not
                   9294: always the same encoding can be used; latin-1 is most widely used,
                   9295: though). For other languages, different char-sets have to be used,
                   9296: several of them variable-width. Most prominent representant is
                   9297: UTF-8. Let's call these extended characters xchars. The primitive
                   9298: fixed-size characters stored as bytes are called pchars in this
                   9299: section.
                   9300: 
                   9301: The xchar words add a few data types:
                   9302: 
                   9303: @itemize
                   9304: 
                   9305: @item
                   9306: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
                   9307: and is a subset of unsigned cell. Note: UTF-8 can not store more that
                   9308: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
                   9309: character set can be used.
                   9310: 
                   9311: @item
                   9312: @var{xc-addr} is the address of an xchar in memory. Alignment
                   9313: requirements are the same as @var{c-addr}. The memory representation of an
                   9314: xchar differs from the stack representation, and depends on the
                   9315: encoding used. An xchar may use a variable number of pchars in memory.
                   9316: 
                   9317: @item
                   9318: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
                   9319: @var{xc-addr}, @var{u} pchars long.
                   9320: 
                   9321: @end itemize
                   9322: 
                   9323: doc-xc-size
                   9324: doc-x-size
                   9325: doc-xc@+
                   9326: doc-xc!+?
                   9327: doc-xchar+
                   9328: doc-xchar-
                   9329: doc-+x/string
                   9330: doc-x\string-
                   9331: doc--trailing-garbage
                   9332: doc-x-width
                   9333: doc-xkey
                   9334: doc-xemit
                   9335: 
                   9336: There's a new environment query
                   9337: 
                   9338: doc-xchar-encoding
1.112     anton    9339: 
1.121     anton    9340: @node OS command line arguments, Locals, Other I/O, Words
                   9341: @section OS command line arguments
                   9342: @cindex OS command line arguments
                   9343: @cindex command line arguments, OS
                   9344: @cindex arguments, OS command line
                   9345: 
                   9346: The usual way to pass arguments to Gforth programs on the command line
                   9347: is via the @option{-e} option, e.g.
                   9348: 
                   9349: @example
                   9350: gforth -e "123 456" foo.fs -e bye
                   9351: @end example
                   9352: 
                   9353: However, you may want to interpret the command-line arguments directly.
                   9354: In that case, you can access the (image-specific) command-line arguments
1.123     anton    9355: through @code{next-arg}:
1.121     anton    9356: 
1.123     anton    9357: doc-next-arg
1.121     anton    9358: 
1.123     anton    9359: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121     anton    9360: 
                   9361: @example
                   9362: : echo ( -- )
1.122     anton    9363:     begin
1.123     anton    9364:        next-arg 2dup 0 0 d<> while
                   9365:            type space
                   9366:     repeat
                   9367:     2drop ;
1.121     anton    9368: 
                   9369: echo cr bye
                   9370: @end example
                   9371: 
                   9372: This can be invoked with
                   9373: 
                   9374: @example
                   9375: gforth echo.fs hello world
                   9376: @end example
1.123     anton    9377: 
                   9378: and it will print
                   9379: 
                   9380: @example
                   9381: hello world
                   9382: @end example
                   9383: 
                   9384: The next lower level of dealing with the OS command line are the
                   9385: following words:
                   9386: 
                   9387: doc-arg
                   9388: doc-shift-args
                   9389: 
                   9390: Finally, at the lowest level Gforth provides the following words:
                   9391: 
                   9392: doc-argc
                   9393: doc-argv
1.121     anton    9394: 
1.78      anton    9395: @c -------------------------------------------------------------
1.126     pazsan   9396: @node Locals, Structures, OS command line arguments, Words
1.78      anton    9397: @section Locals
                   9398: @cindex locals
                   9399: 
                   9400: Local variables can make Forth programming more enjoyable and Forth
                   9401: programs easier to read. Unfortunately, the locals of ANS Forth are
                   9402: laden with restrictions. Therefore, we provide not only the ANS Forth
                   9403: locals wordset, but also our own, more powerful locals wordset (we
                   9404: implemented the ANS Forth locals wordset through our locals wordset).
1.44      crook    9405: 
1.78      anton    9406: The ideas in this section have also been published in M. Anton Ertl,
                   9407: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
                   9408: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12      anton    9409: 
                   9410: @menu
1.78      anton    9411: * Gforth locals::               
                   9412: * ANS Forth locals::            
1.5       anton    9413: @end menu
                   9414: 
1.78      anton    9415: @node Gforth locals, ANS Forth locals, Locals, Locals
                   9416: @subsection Gforth locals
                   9417: @cindex Gforth locals
                   9418: @cindex locals, Gforth style
1.5       anton    9419: 
1.78      anton    9420: Locals can be defined with
1.44      crook    9421: 
1.78      anton    9422: @example
                   9423: @{ local1 local2 ... -- comment @}
                   9424: @end example
                   9425: or
                   9426: @example
                   9427: @{ local1 local2 ... @}
                   9428: @end example
1.5       anton    9429: 
1.78      anton    9430: E.g.,
                   9431: @example
                   9432: : max @{ n1 n2 -- n3 @}
                   9433:  n1 n2 > if
                   9434:    n1
                   9435:  else
                   9436:    n2
                   9437:  endif ;
                   9438: @end example
1.44      crook    9439: 
1.78      anton    9440: The similarity of locals definitions with stack comments is intended. A
                   9441: locals definition often replaces the stack comment of a word. The order
                   9442: of the locals corresponds to the order in a stack comment and everything
                   9443: after the @code{--} is really a comment.
1.77      anton    9444: 
1.78      anton    9445: This similarity has one disadvantage: It is too easy to confuse locals
                   9446: declarations with stack comments, causing bugs and making them hard to
                   9447: find. However, this problem can be avoided by appropriate coding
                   9448: conventions: Do not use both notations in the same program. If you do,
                   9449: they should be distinguished using additional means, e.g. by position.
1.77      anton    9450: 
1.78      anton    9451: @cindex types of locals
                   9452: @cindex locals types
                   9453: The name of the local may be preceded by a type specifier, e.g.,
                   9454: @code{F:} for a floating point value:
1.5       anton    9455: 
1.78      anton    9456: @example
                   9457: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
                   9458: \ complex multiplication
                   9459:  Ar Br f* Ai Bi f* f-
                   9460:  Ar Bi f* Ai Br f* f+ ;
                   9461: @end example
1.44      crook    9462: 
1.78      anton    9463: @cindex flavours of locals
                   9464: @cindex locals flavours
                   9465: @cindex value-flavoured locals
                   9466: @cindex variable-flavoured locals
                   9467: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
                   9468: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
                   9469: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
                   9470: with @code{W:}, @code{D:} etc.) produces its value and can be changed
                   9471: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
                   9472: produces its address (which becomes invalid when the variable's scope is
                   9473: left). E.g., the standard word @code{emit} can be defined in terms of
                   9474: @code{type} like this:
1.5       anton    9475: 
1.78      anton    9476: @example
                   9477: : emit @{ C^ char* -- @}
                   9478:     char* 1 type ;
                   9479: @end example
1.5       anton    9480: 
1.78      anton    9481: @cindex default type of locals
                   9482: @cindex locals, default type
                   9483: A local without type specifier is a @code{W:} local. Both flavours of
                   9484: locals are initialized with values from the data or FP stack.
1.44      crook    9485: 
1.78      anton    9486: Currently there is no way to define locals with user-defined data
                   9487: structures, but we are working on it.
1.5       anton    9488: 
1.78      anton    9489: Gforth allows defining locals everywhere in a colon definition. This
                   9490: poses the following questions:
1.5       anton    9491: 
1.78      anton    9492: @menu
                   9493: * Where are locals visible by name?::  
                   9494: * How long do locals live?::    
                   9495: * Locals programming style::    
                   9496: * Locals implementation::       
                   9497: @end menu
1.44      crook    9498: 
1.78      anton    9499: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
                   9500: @subsubsection Where are locals visible by name?
                   9501: @cindex locals visibility
                   9502: @cindex visibility of locals
                   9503: @cindex scope of locals
1.5       anton    9504: 
1.78      anton    9505: Basically, the answer is that locals are visible where you would expect
                   9506: it in block-structured languages, and sometimes a little longer. If you
                   9507: want to restrict the scope of a local, enclose its definition in
                   9508: @code{SCOPE}...@code{ENDSCOPE}.
1.5       anton    9509: 
                   9510: 
1.78      anton    9511: doc-scope
                   9512: doc-endscope
1.5       anton    9513: 
                   9514: 
1.78      anton    9515: These words behave like control structure words, so you can use them
                   9516: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
                   9517: arbitrary ways.
1.77      anton    9518: 
1.78      anton    9519: If you want a more exact answer to the visibility question, here's the
                   9520: basic principle: A local is visible in all places that can only be
                   9521: reached through the definition of the local@footnote{In compiler
                   9522: construction terminology, all places dominated by the definition of the
                   9523: local.}. In other words, it is not visible in places that can be reached
                   9524: without going through the definition of the local. E.g., locals defined
                   9525: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
                   9526: defined in @code{BEGIN}...@code{UNTIL} are visible after the
                   9527: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77      anton    9528: 
1.78      anton    9529: The reasoning behind this solution is: We want to have the locals
                   9530: visible as long as it is meaningful. The user can always make the
                   9531: visibility shorter by using explicit scoping. In a place that can
                   9532: only be reached through the definition of a local, the meaning of a
                   9533: local name is clear. In other places it is not: How is the local
                   9534: initialized at the control flow path that does not contain the
                   9535: definition? Which local is meant, if the same name is defined twice in
                   9536: two independent control flow paths?
1.77      anton    9537: 
1.78      anton    9538: This should be enough detail for nearly all users, so you can skip the
                   9539: rest of this section. If you really must know all the gory details and
                   9540: options, read on.
1.77      anton    9541: 
1.78      anton    9542: In order to implement this rule, the compiler has to know which places
                   9543: are unreachable. It knows this automatically after @code{AHEAD},
                   9544: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
                   9545: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
                   9546: compiler that the control flow never reaches that place. If
                   9547: @code{UNREACHABLE} is not used where it could, the only consequence is
                   9548: that the visibility of some locals is more limited than the rule above
                   9549: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
                   9550: lie to the compiler), buggy code will be produced.
1.77      anton    9551: 
1.5       anton    9552: 
1.78      anton    9553: doc-unreachable
1.5       anton    9554: 
1.23      crook    9555: 
1.78      anton    9556: Another problem with this rule is that at @code{BEGIN}, the compiler
                   9557: does not know which locals will be visible on the incoming
                   9558: back-edge. All problems discussed in the following are due to this
                   9559: ignorance of the compiler (we discuss the problems using @code{BEGIN}
                   9560: loops as examples; the discussion also applies to @code{?DO} and other
                   9561: loops). Perhaps the most insidious example is:
1.26      crook    9562: @example
1.78      anton    9563: AHEAD
                   9564: BEGIN
                   9565:   x
                   9566: [ 1 CS-ROLL ] THEN
                   9567:   @{ x @}
                   9568:   ...
                   9569: UNTIL
1.26      crook    9570: @end example
1.23      crook    9571: 
1.78      anton    9572: This should be legal according to the visibility rule. The use of
                   9573: @code{x} can only be reached through the definition; but that appears
                   9574: textually below the use.
                   9575: 
                   9576: From this example it is clear that the visibility rules cannot be fully
                   9577: implemented without major headaches. Our implementation treats common
                   9578: cases as advertised and the exceptions are treated in a safe way: The
                   9579: compiler makes a reasonable guess about the locals visible after a
                   9580: @code{BEGIN}; if it is too pessimistic, the
                   9581: user will get a spurious error about the local not being defined; if the
                   9582: compiler is too optimistic, it will notice this later and issue a
                   9583: warning. In the case above the compiler would complain about @code{x}
                   9584: being undefined at its use. You can see from the obscure examples in
                   9585: this section that it takes quite unusual control structures to get the
                   9586: compiler into trouble, and even then it will often do fine.
1.23      crook    9587: 
1.78      anton    9588: If the @code{BEGIN} is reachable from above, the most optimistic guess
                   9589: is that all locals visible before the @code{BEGIN} will also be
                   9590: visible after the @code{BEGIN}. This guess is valid for all loops that
                   9591: are entered only through the @code{BEGIN}, in particular, for normal
                   9592: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
                   9593: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
                   9594: compiler. When the branch to the @code{BEGIN} is finally generated by
                   9595: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
                   9596: warns the user if it was too optimistic:
1.26      crook    9597: @example
1.78      anton    9598: IF
                   9599:   @{ x @}
                   9600: BEGIN
                   9601:   \ x ? 
                   9602: [ 1 cs-roll ] THEN
                   9603:   ...
                   9604: UNTIL
1.26      crook    9605: @end example
1.23      crook    9606: 
1.78      anton    9607: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
                   9608: optimistically assumes that it lives until the @code{THEN}. It notices
                   9609: this difference when it compiles the @code{UNTIL} and issues a
                   9610: warning. The user can avoid the warning, and make sure that @code{x}
                   9611: is not used in the wrong area by using explicit scoping:
                   9612: @example
                   9613: IF
                   9614:   SCOPE
                   9615:   @{ x @}
                   9616:   ENDSCOPE
                   9617: BEGIN
                   9618: [ 1 cs-roll ] THEN
                   9619:   ...
                   9620: UNTIL
                   9621: @end example
1.23      crook    9622: 
1.78      anton    9623: Since the guess is optimistic, there will be no spurious error messages
                   9624: about undefined locals.
1.44      crook    9625: 
1.78      anton    9626: If the @code{BEGIN} is not reachable from above (e.g., after
                   9627: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
                   9628: optimistic guess, as the locals visible after the @code{BEGIN} may be
                   9629: defined later. Therefore, the compiler assumes that no locals are
                   9630: visible after the @code{BEGIN}. However, the user can use
                   9631: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
                   9632: visible at the BEGIN as at the point where the top control-flow stack
                   9633: item was created.
1.23      crook    9634: 
1.44      crook    9635: 
1.78      anton    9636: doc-assume-live
1.26      crook    9637: 
1.23      crook    9638: 
1.78      anton    9639: @noindent
                   9640: E.g.,
                   9641: @example
                   9642: @{ x @}
                   9643: AHEAD
                   9644: ASSUME-LIVE
                   9645: BEGIN
                   9646:   x
                   9647: [ 1 CS-ROLL ] THEN
                   9648:   ...
                   9649: UNTIL
                   9650: @end example
1.44      crook    9651: 
1.78      anton    9652: Other cases where the locals are defined before the @code{BEGIN} can be
                   9653: handled by inserting an appropriate @code{CS-ROLL} before the
                   9654: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
                   9655: behind the @code{ASSUME-LIVE}).
1.23      crook    9656: 
1.78      anton    9657: Cases where locals are defined after the @code{BEGIN} (but should be
                   9658: visible immediately after the @code{BEGIN}) can only be handled by
                   9659: rearranging the loop. E.g., the ``most insidious'' example above can be
                   9660: arranged into:
                   9661: @example
                   9662: BEGIN
                   9663:   @{ x @}
                   9664:   ... 0=
                   9665: WHILE
                   9666:   x
                   9667: REPEAT
                   9668: @end example
1.44      crook    9669: 
1.78      anton    9670: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
                   9671: @subsubsection How long do locals live?
                   9672: @cindex locals lifetime
                   9673: @cindex lifetime of locals
1.23      crook    9674: 
1.78      anton    9675: The right answer for the lifetime question would be: A local lives at
                   9676: least as long as it can be accessed. For a value-flavoured local this
                   9677: means: until the end of its visibility. However, a variable-flavoured
                   9678: local could be accessed through its address far beyond its visibility
                   9679: scope. Ultimately, this would mean that such locals would have to be
                   9680: garbage collected. Since this entails un-Forth-like implementation
                   9681: complexities, I adopted the same cowardly solution as some other
                   9682: languages (e.g., C): The local lives only as long as it is visible;
                   9683: afterwards its address is invalid (and programs that access it
                   9684: afterwards are erroneous).
1.23      crook    9685: 
1.78      anton    9686: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
                   9687: @subsubsection Locals programming style
                   9688: @cindex locals programming style
                   9689: @cindex programming style, locals
1.23      crook    9690: 
1.78      anton    9691: The freedom to define locals anywhere has the potential to change
                   9692: programming styles dramatically. In particular, the need to use the
                   9693: return stack for intermediate storage vanishes. Moreover, all stack
                   9694: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
                   9695: determined arguments) can be eliminated: If the stack items are in the
                   9696: wrong order, just write a locals definition for all of them; then
                   9697: write the items in the order you want.
1.23      crook    9698: 
1.78      anton    9699: This seems a little far-fetched and eliminating stack manipulations is
                   9700: unlikely to become a conscious programming objective. Still, the number
                   9701: of stack manipulations will be reduced dramatically if local variables
                   9702: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
                   9703: a traditional implementation of @code{max}).
1.23      crook    9704: 
1.78      anton    9705: This shows one potential benefit of locals: making Forth programs more
                   9706: readable. Of course, this benefit will only be realized if the
                   9707: programmers continue to honour the principle of factoring instead of
                   9708: using the added latitude to make the words longer.
1.23      crook    9709: 
1.78      anton    9710: @cindex single-assignment style for locals
                   9711: Using @code{TO} can and should be avoided.  Without @code{TO},
                   9712: every value-flavoured local has only a single assignment and many
                   9713: advantages of functional languages apply to Forth. I.e., programs are
                   9714: easier to analyse, to optimize and to read: It is clear from the
                   9715: definition what the local stands for, it does not turn into something
                   9716: different later.
1.23      crook    9717: 
1.78      anton    9718: E.g., a definition using @code{TO} might look like this:
                   9719: @example
                   9720: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9721:  u1 u2 min 0
                   9722:  ?do
                   9723:    addr1 c@@ addr2 c@@ -
                   9724:    ?dup-if
                   9725:      unloop exit
                   9726:    then
                   9727:    addr1 char+ TO addr1
                   9728:    addr2 char+ TO addr2
                   9729:  loop
                   9730:  u1 u2 - ;
1.26      crook    9731: @end example
1.78      anton    9732: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
                   9733: every loop iteration. @code{strcmp} is a typical example of the
                   9734: readability problems of using @code{TO}. When you start reading
                   9735: @code{strcmp}, you think that @code{addr1} refers to the start of the
                   9736: string. Only near the end of the loop you realize that it is something
                   9737: else.
1.23      crook    9738: 
1.78      anton    9739: This can be avoided by defining two locals at the start of the loop that
                   9740: are initialized with the right value for the current iteration.
                   9741: @example
                   9742: : strcmp @{ addr1 u1 addr2 u2 -- n @}
                   9743:  addr1 addr2
                   9744:  u1 u2 min 0 
                   9745:  ?do @{ s1 s2 @}
                   9746:    s1 c@@ s2 c@@ -
                   9747:    ?dup-if
                   9748:      unloop exit
                   9749:    then
                   9750:    s1 char+ s2 char+
                   9751:  loop
                   9752:  2drop
                   9753:  u1 u2 - ;
                   9754: @end example
                   9755: Here it is clear from the start that @code{s1} has a different value
                   9756: in every loop iteration.
1.23      crook    9757: 
1.78      anton    9758: @node Locals implementation,  , Locals programming style, Gforth locals
                   9759: @subsubsection Locals implementation
                   9760: @cindex locals implementation
                   9761: @cindex implementation of locals
1.23      crook    9762: 
1.78      anton    9763: @cindex locals stack
                   9764: Gforth uses an extra locals stack. The most compelling reason for
                   9765: this is that the return stack is not float-aligned; using an extra stack
                   9766: also eliminates the problems and restrictions of using the return stack
                   9767: as locals stack. Like the other stacks, the locals stack grows toward
                   9768: lower addresses. A few primitives allow an efficient implementation:
                   9769: 
                   9770: 
                   9771: doc-@local#
                   9772: doc-f@local#
                   9773: doc-laddr#
                   9774: doc-lp+!#
                   9775: doc-lp!
                   9776: doc->l
                   9777: doc-f>l
                   9778: 
                   9779: 
                   9780: In addition to these primitives, some specializations of these
                   9781: primitives for commonly occurring inline arguments are provided for
                   9782: efficiency reasons, e.g., @code{@@local0} as specialization of
                   9783: @code{@@local#} for the inline argument 0. The following compiling words
                   9784: compile the right specialized version, or the general version, as
                   9785: appropriate:
1.23      crook    9786: 
1.5       anton    9787: 
1.107     dvdkhlng 9788: @c doc-compile-@local
                   9789: @c doc-compile-f@local
1.78      anton    9790: doc-compile-lp+!
1.5       anton    9791: 
                   9792: 
1.78      anton    9793: Combinations of conditional branches and @code{lp+!#} like
                   9794: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
                   9795: is taken) are provided for efficiency and correctness in loops.
1.5       anton    9796: 
1.78      anton    9797: A special area in the dictionary space is reserved for keeping the
                   9798: local variable names. @code{@{} switches the dictionary pointer to this
                   9799: area and @code{@}} switches it back and generates the locals
                   9800: initializing code. @code{W:} etc.@ are normal defining words. This
                   9801: special area is cleared at the start of every colon definition.
1.5       anton    9802: 
1.78      anton    9803: @cindex word list for defining locals
                   9804: A special feature of Gforth's dictionary is used to implement the
                   9805: definition of locals without type specifiers: every word list (aka
                   9806: vocabulary) has its own methods for searching
                   9807: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
                   9808: with a special search method: When it is searched for a word, it
                   9809: actually creates that word using @code{W:}. @code{@{} changes the search
                   9810: order to first search the word list containing @code{@}}, @code{W:} etc.,
                   9811: and then the word list for defining locals without type specifiers.
1.5       anton    9812: 
1.78      anton    9813: The lifetime rules support a stack discipline within a colon
                   9814: definition: The lifetime of a local is either nested with other locals
                   9815: lifetimes or it does not overlap them.
1.23      crook    9816: 
1.78      anton    9817: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
                   9818: pointer manipulation is generated. Between control structure words
                   9819: locals definitions can push locals onto the locals stack. @code{AGAIN}
                   9820: is the simplest of the other three control flow words. It has to
                   9821: restore the locals stack depth of the corresponding @code{BEGIN}
                   9822: before branching. The code looks like this:
                   9823: @format
                   9824: @code{lp+!#} current-locals-size @minus{} dest-locals-size
                   9825: @code{branch} <begin>
                   9826: @end format
1.26      crook    9827: 
1.78      anton    9828: @code{UNTIL} is a little more complicated: If it branches back, it
                   9829: must adjust the stack just like @code{AGAIN}. But if it falls through,
                   9830: the locals stack must not be changed. The compiler generates the
                   9831: following code:
                   9832: @format
                   9833: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
                   9834: @end format
                   9835: The locals stack pointer is only adjusted if the branch is taken.
1.44      crook    9836: 
1.78      anton    9837: @code{THEN} can produce somewhat inefficient code:
                   9838: @format
                   9839: @code{lp+!#} current-locals-size @minus{} orig-locals-size
                   9840: <orig target>:
                   9841: @code{lp+!#} orig-locals-size @minus{} new-locals-size
                   9842: @end format
                   9843: The second @code{lp+!#} adjusts the locals stack pointer from the
                   9844: level at the @i{orig} point to the level after the @code{THEN}. The
                   9845: first @code{lp+!#} adjusts the locals stack pointer from the current
                   9846: level to the level at the orig point, so the complete effect is an
                   9847: adjustment from the current level to the right level after the
                   9848: @code{THEN}.
1.26      crook    9849: 
1.78      anton    9850: @cindex locals information on the control-flow stack
                   9851: @cindex control-flow stack items, locals information
                   9852: In a conventional Forth implementation a dest control-flow stack entry
                   9853: is just the target address and an orig entry is just the address to be
                   9854: patched. Our locals implementation adds a word list to every orig or dest
                   9855: item. It is the list of locals visible (or assumed visible) at the point
                   9856: described by the entry. Our implementation also adds a tag to identify
                   9857: the kind of entry, in particular to differentiate between live and dead
                   9858: (reachable and unreachable) orig entries.
1.26      crook    9859: 
1.78      anton    9860: A few unusual operations have to be performed on locals word lists:
1.44      crook    9861: 
1.5       anton    9862: 
1.78      anton    9863: doc-common-list
                   9864: doc-sub-list?
                   9865: doc-list-size
1.52      anton    9866: 
                   9867: 
1.78      anton    9868: Several features of our locals word list implementation make these
                   9869: operations easy to implement: The locals word lists are organised as
                   9870: linked lists; the tails of these lists are shared, if the lists
                   9871: contain some of the same locals; and the address of a name is greater
                   9872: than the address of the names behind it in the list.
1.5       anton    9873: 
1.78      anton    9874: Another important implementation detail is the variable
                   9875: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
                   9876: determine if they can be reached directly or only through the branch
                   9877: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
                   9878: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
                   9879: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5       anton    9880: 
1.78      anton    9881: Counted loops are similar to other loops in most respects, but
                   9882: @code{LEAVE} requires special attention: It performs basically the same
                   9883: service as @code{AHEAD}, but it does not create a control-flow stack
                   9884: entry. Therefore the information has to be stored elsewhere;
                   9885: traditionally, the information was stored in the target fields of the
                   9886: branches created by the @code{LEAVE}s, by organizing these fields into a
                   9887: linked list. Unfortunately, this clever trick does not provide enough
                   9888: space for storing our extended control flow information. Therefore, we
                   9889: introduce another stack, the leave stack. It contains the control-flow
                   9890: stack entries for all unresolved @code{LEAVE}s.
1.44      crook    9891: 
1.78      anton    9892: Local names are kept until the end of the colon definition, even if
                   9893: they are no longer visible in any control-flow path. In a few cases
                   9894: this may lead to increased space needs for the locals name area, but
                   9895: usually less than reclaiming this space would cost in code size.
1.5       anton    9896: 
1.44      crook    9897: 
1.78      anton    9898: @node ANS Forth locals,  , Gforth locals, Locals
                   9899: @subsection ANS Forth locals
                   9900: @cindex locals, ANS Forth style
1.5       anton    9901: 
1.78      anton    9902: The ANS Forth locals wordset does not define a syntax for locals, but
                   9903: words that make it possible to define various syntaxes. One of the
                   9904: possible syntaxes is a subset of the syntax we used in the Gforth locals
                   9905: wordset, i.e.:
1.29      crook    9906: 
                   9907: @example
1.78      anton    9908: @{ local1 local2 ... -- comment @}
                   9909: @end example
                   9910: @noindent
                   9911: or
                   9912: @example
                   9913: @{ local1 local2 ... @}
1.29      crook    9914: @end example
                   9915: 
1.78      anton    9916: The order of the locals corresponds to the order in a stack comment. The
                   9917: restrictions are:
1.5       anton    9918: 
1.78      anton    9919: @itemize @bullet
                   9920: @item
                   9921: Locals can only be cell-sized values (no type specifiers are allowed).
                   9922: @item
                   9923: Locals can be defined only outside control structures.
                   9924: @item
                   9925: Locals can interfere with explicit usage of the return stack. For the
                   9926: exact (and long) rules, see the standard. If you don't use return stack
                   9927: accessing words in a definition using locals, you will be all right. The
                   9928: purpose of this rule is to make locals implementation on the return
                   9929: stack easier.
                   9930: @item
                   9931: The whole definition must be in one line.
                   9932: @end itemize
1.5       anton    9933: 
1.78      anton    9934: Locals defined in ANS Forth behave like @code{VALUE}s
                   9935: (@pxref{Values}). I.e., they are initialized from the stack. Using their
                   9936: name produces their value. Their value can be changed using @code{TO}.
1.77      anton    9937: 
1.78      anton    9938: Since the syntax above is supported by Gforth directly, you need not do
                   9939: anything to use it. If you want to port a program using this syntax to
                   9940: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
                   9941: syntax on the other system.
1.5       anton    9942: 
1.78      anton    9943: Note that a syntax shown in the standard, section A.13 looks
                   9944: similar, but is quite different in having the order of locals
                   9945: reversed. Beware!
1.5       anton    9946: 
1.78      anton    9947: The ANS Forth locals wordset itself consists of one word:
1.5       anton    9948: 
1.78      anton    9949: doc-(local)
1.5       anton    9950: 
1.78      anton    9951: The ANS Forth locals extension wordset defines a syntax using
                   9952: @code{locals|}, but it is so awful that we strongly recommend not to use
                   9953: it. We have implemented this syntax to make porting to Gforth easy, but
                   9954: do not document it here. The problem with this syntax is that the locals
                   9955: are defined in an order reversed with respect to the standard stack
                   9956: comment notation, making programs harder to read, and easier to misread
                   9957: and miswrite. The only merit of this syntax is that it is easy to
                   9958: implement using the ANS Forth locals wordset.
1.53      anton    9959: 
                   9960: 
1.78      anton    9961: @c ----------------------------------------------------------
                   9962: @node Structures, Object-oriented Forth, Locals, Words
                   9963: @section  Structures
                   9964: @cindex structures
                   9965: @cindex records
1.53      anton    9966: 
1.78      anton    9967: This section presents the structure package that comes with Gforth. A
                   9968: version of the package implemented in ANS Forth is available in
                   9969: @file{compat/struct.fs}. This package was inspired by a posting on
                   9970: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
                   9971: possibly John Hayes). A version of this section has been published in
                   9972: M. Anton Ertl,
                   9973: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
                   9974: Another Forth Structures Package}, Forth Dimensions 19(3), pages
                   9975: 13--16. Marcel Hendrix provided helpful comments.
1.53      anton    9976: 
1.78      anton    9977: @menu
                   9978: * Why explicit structure support?::  
                   9979: * Structure Usage::             
                   9980: * Structure Naming Convention::  
                   9981: * Structure Implementation::    
                   9982: * Structure Glossary::          
1.183     anton    9983: * Forth200x Structures::        
1.78      anton    9984: @end menu
1.55      anton    9985: 
1.78      anton    9986: @node Why explicit structure support?, Structure Usage, Structures, Structures
                   9987: @subsection Why explicit structure support?
1.53      anton    9988: 
1.78      anton    9989: @cindex address arithmetic for structures
                   9990: @cindex structures using address arithmetic
                   9991: If we want to use a structure containing several fields, we could simply
                   9992: reserve memory for it, and access the fields using address arithmetic
                   9993: (@pxref{Address arithmetic}). As an example, consider a structure with
                   9994: the following fields
1.57      anton    9995: 
1.78      anton    9996: @table @code
                   9997: @item a
                   9998: is a float
                   9999: @item b
                   10000: is a cell
                   10001: @item c
                   10002: is a float
                   10003: @end table
1.57      anton    10004: 
1.78      anton    10005: Given the (float-aligned) base address of the structure we get the
                   10006: address of the field
1.52      anton    10007: 
1.78      anton    10008: @table @code
                   10009: @item a
                   10010: without doing anything further.
                   10011: @item b
                   10012: with @code{float+}
                   10013: @item c
                   10014: with @code{float+ cell+ faligned}
                   10015: @end table
1.52      anton    10016: 
1.78      anton    10017: It is easy to see that this can become quite tiring. 
1.52      anton    10018: 
1.78      anton    10019: Moreover, it is not very readable, because seeing a
                   10020: @code{cell+} tells us neither which kind of structure is
                   10021: accessed nor what field is accessed; we have to somehow infer the kind
                   10022: of structure, and then look up in the documentation, which field of
                   10023: that structure corresponds to that offset.
1.53      anton    10024: 
1.78      anton    10025: Finally, this kind of address arithmetic also causes maintenance
                   10026: troubles: If you add or delete a field somewhere in the middle of the
                   10027: structure, you have to find and change all computations for the fields
                   10028: afterwards.
1.52      anton    10029: 
1.78      anton    10030: So, instead of using @code{cell+} and friends directly, how
                   10031: about storing the offsets in constants:
1.52      anton    10032: 
1.78      anton    10033: @example
                   10034: 0 constant a-offset
                   10035: 0 float+ constant b-offset
                   10036: 0 float+ cell+ faligned c-offset
                   10037: @end example
1.64      pazsan   10038: 
1.78      anton    10039: Now we can get the address of field @code{x} with @code{x-offset
                   10040: +}. This is much better in all respects. Of course, you still
                   10041: have to change all later offset definitions if you add a field. You can
                   10042: fix this by declaring the offsets in the following way:
1.57      anton    10043: 
1.78      anton    10044: @example
                   10045: 0 constant a-offset
                   10046: a-offset float+ constant b-offset
                   10047: b-offset cell+ faligned constant c-offset
                   10048: @end example
1.57      anton    10049: 
1.78      anton    10050: Since we always use the offsets with @code{+}, we could use a defining
                   10051: word @code{cfield} that includes the @code{+} in the action of the
                   10052: defined word:
1.64      pazsan   10053: 
1.78      anton    10054: @example
                   10055: : cfield ( n "name" -- )
                   10056:     create ,
                   10057: does> ( name execution: addr1 -- addr2 )
                   10058:     @@ + ;
1.64      pazsan   10059: 
1.78      anton    10060: 0 cfield a
                   10061: 0 a float+ cfield b
                   10062: 0 b cell+ faligned cfield c
                   10063: @end example
1.64      pazsan   10064: 
1.78      anton    10065: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64      pazsan   10066: 
1.78      anton    10067: The structure field words now can be used quite nicely. However,
                   10068: their definition is still a bit cumbersome: We have to repeat the
                   10069: name, the information about size and alignment is distributed before
                   10070: and after the field definitions etc.  The structure package presented
                   10071: here addresses these problems.
1.64      pazsan   10072: 
1.78      anton    10073: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
                   10074: @subsection Structure Usage
                   10075: @cindex structure usage
1.57      anton    10076: 
1.78      anton    10077: @cindex @code{field} usage
                   10078: @cindex @code{struct} usage
                   10079: @cindex @code{end-struct} usage
                   10080: You can define a structure for a (data-less) linked list with:
1.57      anton    10081: @example
1.78      anton    10082: struct
                   10083:     cell% field list-next
                   10084: end-struct list%
1.57      anton    10085: @end example
                   10086: 
1.78      anton    10087: With the address of the list node on the stack, you can compute the
                   10088: address of the field that contains the address of the next node with
                   10089: @code{list-next}. E.g., you can determine the length of a list
                   10090: with:
1.57      anton    10091: 
                   10092: @example
1.78      anton    10093: : list-length ( list -- n )
                   10094: \ "list" is a pointer to the first element of a linked list
                   10095: \ "n" is the length of the list
                   10096:     0 BEGIN ( list1 n1 )
                   10097:         over
                   10098:     WHILE ( list1 n1 )
                   10099:         1+ swap list-next @@ swap
                   10100:     REPEAT
                   10101:     nip ;
1.57      anton    10102: @end example
                   10103: 
1.78      anton    10104: You can reserve memory for a list node in the dictionary with
                   10105: @code{list% %allot}, which leaves the address of the list node on the
                   10106: stack. For the equivalent allocation on the heap you can use @code{list%
                   10107: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
                   10108: use @code{list% %allocate}). You can get the the size of a list
                   10109: node with @code{list% %size} and its alignment with @code{list%
                   10110: %alignment}.
                   10111: 
                   10112: Note that in ANS Forth the body of a @code{create}d word is
                   10113: @code{aligned} but not necessarily @code{faligned};
                   10114: therefore, if you do a:
1.57      anton    10115: 
                   10116: @example
1.78      anton    10117: create @emph{name} foo% %allot drop
1.57      anton    10118: @end example
                   10119: 
1.78      anton    10120: @noindent
                   10121: then the memory alloted for @code{foo%} is guaranteed to start at the
                   10122: body of @code{@emph{name}} only if @code{foo%} contains only character,
                   10123: cell and double fields.  Therefore, if your structure contains floats,
                   10124: better use
1.57      anton    10125: 
                   10126: @example
1.78      anton    10127: foo% %allot constant @emph{name}
1.57      anton    10128: @end example
                   10129: 
1.78      anton    10130: @cindex structures containing structures
                   10131: You can include a structure @code{foo%} as a field of
                   10132: another structure, like this:
1.65      anton    10133: @example
1.78      anton    10134: struct
                   10135: ...
                   10136:     foo% field ...
                   10137: ...
                   10138: end-struct ...
1.65      anton    10139: @end example
1.52      anton    10140: 
1.78      anton    10141: @cindex structure extension
                   10142: @cindex extended records
                   10143: Instead of starting with an empty structure, you can extend an
                   10144: existing structure. E.g., a plain linked list without data, as defined
                   10145: above, is hardly useful; You can extend it to a linked list of integers,
                   10146: like this:@footnote{This feature is also known as @emph{extended
                   10147: records}. It is the main innovation in the Oberon language; in other
                   10148: words, adding this feature to Modula-2 led Wirth to create a new
                   10149: language, write a new compiler etc.  Adding this feature to Forth just
                   10150: required a few lines of code.}
1.52      anton    10151: 
1.78      anton    10152: @example
                   10153: list%
                   10154:     cell% field intlist-int
                   10155: end-struct intlist%
                   10156: @end example
1.55      anton    10157: 
1.78      anton    10158: @code{intlist%} is a structure with two fields:
                   10159: @code{list-next} and @code{intlist-int}.
1.55      anton    10160: 
1.78      anton    10161: @cindex structures containing arrays
                   10162: You can specify an array type containing @emph{n} elements of
                   10163: type @code{foo%} like this:
1.55      anton    10164: 
                   10165: @example
1.78      anton    10166: foo% @emph{n} *
1.56      anton    10167: @end example
1.55      anton    10168: 
1.78      anton    10169: You can use this array type in any place where you can use a normal
                   10170: type, e.g., when defining a @code{field}, or with
                   10171: @code{%allot}.
                   10172: 
                   10173: @cindex first field optimization
                   10174: The first field is at the base address of a structure and the word for
                   10175: this field (e.g., @code{list-next}) actually does not change the address
                   10176: on the stack. You may be tempted to leave it away in the interest of
                   10177: run-time and space efficiency. This is not necessary, because the
                   10178: structure package optimizes this case: If you compile a first-field
                   10179: words, no code is generated. So, in the interest of readability and
                   10180: maintainability you should include the word for the field when accessing
                   10181: the field.
1.52      anton    10182: 
                   10183: 
1.78      anton    10184: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
                   10185: @subsection Structure Naming Convention
                   10186: @cindex structure naming convention
1.52      anton    10187: 
1.78      anton    10188: The field names that come to (my) mind are often quite generic, and,
                   10189: if used, would cause frequent name clashes. E.g., many structures
                   10190: probably contain a @code{counter} field. The structure names
                   10191: that come to (my) mind are often also the logical choice for the names
                   10192: of words that create such a structure.
1.52      anton    10193: 
1.78      anton    10194: Therefore, I have adopted the following naming conventions: 
1.52      anton    10195: 
1.78      anton    10196: @itemize @bullet
                   10197: @cindex field naming convention
                   10198: @item
                   10199: The names of fields are of the form
                   10200: @code{@emph{struct}-@emph{field}}, where
                   10201: @code{@emph{struct}} is the basic name of the structure, and
                   10202: @code{@emph{field}} is the basic name of the field. You can
                   10203: think of field words as converting the (address of the)
                   10204: structure into the (address of the) field.
1.52      anton    10205: 
1.78      anton    10206: @cindex structure naming convention
                   10207: @item
                   10208: The names of structures are of the form
                   10209: @code{@emph{struct}%}, where
                   10210: @code{@emph{struct}} is the basic name of the structure.
                   10211: @end itemize
1.52      anton    10212: 
1.78      anton    10213: This naming convention does not work that well for fields of extended
                   10214: structures; e.g., the integer list structure has a field
                   10215: @code{intlist-int}, but has @code{list-next}, not
                   10216: @code{intlist-next}.
1.53      anton    10217: 
1.78      anton    10218: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
                   10219: @subsection Structure Implementation
                   10220: @cindex structure implementation
                   10221: @cindex implementation of structures
1.52      anton    10222: 
1.78      anton    10223: The central idea in the implementation is to pass the data about the
                   10224: structure being built on the stack, not in some global
                   10225: variable. Everything else falls into place naturally once this design
                   10226: decision is made.
1.53      anton    10227: 
1.78      anton    10228: The type description on the stack is of the form @emph{align
                   10229: size}. Keeping the size on the top-of-stack makes dealing with arrays
                   10230: very simple.
1.53      anton    10231: 
1.78      anton    10232: @code{field} is a defining word that uses @code{Create}
                   10233: and @code{DOES>}. The body of the field contains the offset
                   10234: of the field, and the normal @code{DOES>} action is simply:
1.53      anton    10235: 
                   10236: @example
1.78      anton    10237: @@ +
1.53      anton    10238: @end example
                   10239: 
1.78      anton    10240: @noindent
                   10241: i.e., add the offset to the address, giving the stack effect
                   10242: @i{addr1 -- addr2} for a field.
                   10243: 
                   10244: @cindex first field optimization, implementation
                   10245: This simple structure is slightly complicated by the optimization
                   10246: for fields with offset 0, which requires a different
                   10247: @code{DOES>}-part (because we cannot rely on there being
                   10248: something on the stack if such a field is invoked during
                   10249: compilation). Therefore, we put the different @code{DOES>}-parts
                   10250: in separate words, and decide which one to invoke based on the
                   10251: offset. For a zero offset, the field is basically a noop; it is
                   10252: immediate, and therefore no code is generated when it is compiled.
1.53      anton    10253: 
1.183     anton    10254: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78      anton    10255: @subsection Structure Glossary
                   10256: @cindex structure glossary
1.53      anton    10257: 
1.5       anton    10258: 
1.78      anton    10259: doc-%align
                   10260: doc-%alignment
                   10261: doc-%alloc
                   10262: doc-%allocate
                   10263: doc-%allot
                   10264: doc-cell%
                   10265: doc-char%
                   10266: doc-dfloat%
                   10267: doc-double%
                   10268: doc-end-struct
                   10269: doc-field
                   10270: doc-float%
                   10271: doc-naligned
                   10272: doc-sfloat%
                   10273: doc-%size
                   10274: doc-struct
1.54      anton    10275: 
                   10276: 
1.183     anton    10277: @node Forth200x Structures,  , Structure Glossary, Structures
                   10278: @subsection Forth200x Structures
                   10279: @cindex Structures in Forth200x
                   10280: 
                   10281: The Forth 200x standard defines a slightly less convenient form of
                   10282: structures.  In general (when using @code{field+}, you have to perform
                   10283: the alignment yourself, but there are a number of convenience words
                   10284: (e.g., @code{field:} that perform the alignment for you.
                   10285: 
                   10286: A typical usage example is:
                   10287: 
                   10288: @example
                   10289: 0
                   10290:   field:                   s-a
                   10291:   faligned 2 floats +field s-b
                   10292: constant s-struct
                   10293: @end example
                   10294: 
                   10295: An alternative way of writing this structure is:
                   10296: 
                   10297: @example
                   10298: begin-structure s-struct
                   10299:   field:                   s-a
                   10300:   faligned 2 floats +field s-b
                   10301: end-structure
                   10302: @end example
                   10303: 
                   10304: doc-begin-structure
                   10305: doc-end-structure
                   10306: doc-+field
                   10307: doc-cfield:
                   10308: doc-field:
                   10309: doc-2field:
                   10310: doc-ffield:
                   10311: doc-sffield:
                   10312: doc-dffield:
                   10313: 
1.26      crook    10314: @c -------------------------------------------------------------
1.78      anton    10315: @node Object-oriented Forth, Programming Tools, Structures, Words
                   10316: @section Object-oriented Forth
                   10317: 
                   10318: Gforth comes with three packages for object-oriented programming:
                   10319: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
                   10320: is preloaded, so you have to @code{include} them before use. The most
                   10321: important differences between these packages (and others) are discussed
                   10322: in @ref{Comparison with other object models}. All packages are written
                   10323: in ANS Forth and can be used with any other ANS Forth.
1.5       anton    10324: 
1.78      anton    10325: @menu
                   10326: * Why object-oriented programming?::  
                   10327: * Object-Oriented Terminology::  
                   10328: * Objects::                     
                   10329: * OOF::                         
                   10330: * Mini-OOF::                    
                   10331: * Comparison with other object models::  
                   10332: @end menu
1.5       anton    10333: 
1.78      anton    10334: @c ----------------------------------------------------------------
                   10335: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
                   10336: @subsection Why object-oriented programming?
                   10337: @cindex object-oriented programming motivation
                   10338: @cindex motivation for object-oriented programming
1.44      crook    10339: 
1.78      anton    10340: Often we have to deal with several data structures (@emph{objects}),
                   10341: that have to be treated similarly in some respects, but differently in
                   10342: others. Graphical objects are the textbook example: circles, triangles,
                   10343: dinosaurs, icons, and others, and we may want to add more during program
                   10344: development. We want to apply some operations to any graphical object,
                   10345: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
                   10346: has to do something different for every kind of object.
                   10347: @comment TODO add some other operations eg perimeter, area
                   10348: @comment and tie in to concrete examples later..
1.5       anton    10349: 
1.78      anton    10350: We could implement @code{draw} as a big @code{CASE}
                   10351: control structure that executes the appropriate code depending on the
                   10352: kind of object to be drawn. This would be not be very elegant, and,
                   10353: moreover, we would have to change @code{draw} every time we add
                   10354: a new kind of graphical object (say, a spaceship).
1.44      crook    10355: 
1.78      anton    10356: What we would rather do is: When defining spaceships, we would tell
                   10357: the system: ``Here's how you @code{draw} a spaceship; you figure
                   10358: out the rest''.
1.5       anton    10359: 
1.78      anton    10360: This is the problem that all systems solve that (rightfully) call
                   10361: themselves object-oriented; the object-oriented packages presented here
                   10362: solve this problem (and not much else).
                   10363: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44      crook    10364: 
1.78      anton    10365: @c ------------------------------------------------------------------------
                   10366: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
                   10367: @subsection Object-Oriented Terminology
                   10368: @cindex object-oriented terminology
                   10369: @cindex terminology for object-oriented programming
1.5       anton    10370: 
1.78      anton    10371: This section is mainly for reference, so you don't have to understand
                   10372: all of it right away.  The terminology is mainly Smalltalk-inspired.  In
                   10373: short:
1.44      crook    10374: 
1.78      anton    10375: @table @emph
                   10376: @cindex class
                   10377: @item class
                   10378: a data structure definition with some extras.
1.5       anton    10379: 
1.78      anton    10380: @cindex object
                   10381: @item object
                   10382: an instance of the data structure described by the class definition.
1.5       anton    10383: 
1.78      anton    10384: @cindex instance variables
                   10385: @item instance variables
                   10386: fields of the data structure.
1.5       anton    10387: 
1.78      anton    10388: @cindex selector
                   10389: @cindex method selector
                   10390: @cindex virtual function
                   10391: @item selector
                   10392: (or @emph{method selector}) a word (e.g.,
                   10393: @code{draw}) that performs an operation on a variety of data
                   10394: structures (classes). A selector describes @emph{what} operation to
                   10395: perform. In C++ terminology: a (pure) virtual function.
1.5       anton    10396: 
1.78      anton    10397: @cindex method
                   10398: @item method
                   10399: the concrete definition that performs the operation
                   10400: described by the selector for a specific class. A method specifies
                   10401: @emph{how} the operation is performed for a specific class.
1.5       anton    10402: 
1.78      anton    10403: @cindex selector invocation
                   10404: @cindex message send
                   10405: @cindex invoking a selector
                   10406: @item selector invocation
                   10407: a call of a selector. One argument of the call (the TOS (top-of-stack))
                   10408: is used for determining which method is used. In Smalltalk terminology:
                   10409: a message (consisting of the selector and the other arguments) is sent
                   10410: to the object.
1.5       anton    10411: 
1.78      anton    10412: @cindex receiving object
                   10413: @item receiving object
                   10414: the object used for determining the method executed by a selector
                   10415: invocation. In the @file{objects.fs} model, it is the object that is on
                   10416: the TOS when the selector is invoked. (@emph{Receiving} comes from
                   10417: the Smalltalk @emph{message} terminology.)
1.5       anton    10418: 
1.78      anton    10419: @cindex child class
                   10420: @cindex parent class
                   10421: @cindex inheritance
                   10422: @item child class
                   10423: a class that has (@emph{inherits}) all properties (instance variables,
                   10424: selectors, methods) from a @emph{parent class}. In Smalltalk
                   10425: terminology: The subclass inherits from the superclass. In C++
                   10426: terminology: The derived class inherits from the base class.
1.5       anton    10427: 
1.78      anton    10428: @end table
1.5       anton    10429: 
1.78      anton    10430: @c If you wonder about the message sending terminology, it comes from
                   10431: @c a time when each object had it's own task and objects communicated via
                   10432: @c message passing; eventually the Smalltalk developers realized that
                   10433: @c they can do most things through simple (indirect) calls. They kept the
                   10434: @c terminology.
1.5       anton    10435: 
1.78      anton    10436: @c --------------------------------------------------------------
                   10437: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
                   10438: @subsection The @file{objects.fs} model
                   10439: @cindex objects
                   10440: @cindex object-oriented programming
1.26      crook    10441: 
1.78      anton    10442: @cindex @file{objects.fs}
                   10443: @cindex @file{oof.fs}
1.26      crook    10444: 
1.78      anton    10445: This section describes the @file{objects.fs} package. This material also
                   10446: has been published in M. Anton Ertl,
                   10447: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
                   10448: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
                   10449: 37--43.
                   10450: @c McKewan's and Zsoter's packages
1.26      crook    10451: 
1.78      anton    10452: This section assumes that you have read @ref{Structures}.
1.5       anton    10453: 
1.78      anton    10454: The techniques on which this model is based have been used to implement
                   10455: the parser generator, Gray, and have also been used in Gforth for
                   10456: implementing the various flavours of word lists (hashed or not,
                   10457: case-sensitive or not, special-purpose word lists for locals etc.).
1.5       anton    10458: 
                   10459: 
1.26      crook    10460: @menu
1.78      anton    10461: * Properties of the Objects model::  
                   10462: * Basic Objects Usage::         
                   10463: * The Objects base class::      
                   10464: * Creating objects::            
                   10465: * Object-Oriented Programming Style::  
                   10466: * Class Binding::               
                   10467: * Method conveniences::         
                   10468: * Classes and Scoping::         
                   10469: * Dividing classes::            
                   10470: * Object Interfaces::           
                   10471: * Objects Implementation::      
                   10472: * Objects Glossary::            
1.26      crook    10473: @end menu
1.5       anton    10474: 
1.78      anton    10475: Marcel Hendrix provided helpful comments on this section.
1.5       anton    10476: 
1.78      anton    10477: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
                   10478: @subsubsection Properties of the @file{objects.fs} model
                   10479: @cindex @file{objects.fs} properties
1.5       anton    10480: 
1.78      anton    10481: @itemize @bullet
                   10482: @item
                   10483: It is straightforward to pass objects on the stack. Passing
                   10484: selectors on the stack is a little less convenient, but possible.
1.44      crook    10485: 
1.78      anton    10486: @item
                   10487: Objects are just data structures in memory, and are referenced by their
                   10488: address. You can create words for objects with normal defining words
                   10489: like @code{constant}. Likewise, there is no difference between instance
                   10490: variables that contain objects and those that contain other data.
1.5       anton    10491: 
1.78      anton    10492: @item
                   10493: Late binding is efficient and easy to use.
1.44      crook    10494: 
1.78      anton    10495: @item
                   10496: It avoids parsing, and thus avoids problems with state-smartness
                   10497: and reduced extensibility; for convenience there are a few parsing
                   10498: words, but they have non-parsing counterparts. There are also a few
                   10499: defining words that parse. This is hard to avoid, because all standard
                   10500: defining words parse (except @code{:noname}); however, such
                   10501: words are not as bad as many other parsing words, because they are not
                   10502: state-smart.
1.5       anton    10503: 
1.78      anton    10504: @item
                   10505: It does not try to incorporate everything. It does a few things and does
                   10506: them well (IMO). In particular, this model was not designed to support
                   10507: information hiding (although it has features that may help); you can use
                   10508: a separate package for achieving this.
1.5       anton    10509: 
1.78      anton    10510: @item
                   10511: It is layered; you don't have to learn and use all features to use this
                   10512: model. Only a few features are necessary (@pxref{Basic Objects Usage},
                   10513: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
                   10514: are optional and independent of each other.
1.5       anton    10515: 
1.78      anton    10516: @item
                   10517: An implementation in ANS Forth is available.
1.5       anton    10518: 
1.78      anton    10519: @end itemize
1.5       anton    10520: 
1.44      crook    10521: 
1.78      anton    10522: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
                   10523: @subsubsection Basic @file{objects.fs} Usage
                   10524: @cindex basic objects usage
                   10525: @cindex objects, basic usage
1.5       anton    10526: 
1.78      anton    10527: You can define a class for graphical objects like this:
1.44      crook    10528: 
1.78      anton    10529: @cindex @code{class} usage
                   10530: @cindex @code{end-class} usage
                   10531: @cindex @code{selector} usage
1.5       anton    10532: @example
1.78      anton    10533: object class \ "object" is the parent class
                   10534:   selector draw ( x y graphical -- )
                   10535: end-class graphical
                   10536: @end example
                   10537: 
                   10538: This code defines a class @code{graphical} with an
                   10539: operation @code{draw}.  We can perform the operation
                   10540: @code{draw} on any @code{graphical} object, e.g.:
                   10541: 
                   10542: @example
                   10543: 100 100 t-rex draw
1.26      crook    10544: @end example
1.5       anton    10545: 
1.78      anton    10546: @noindent
                   10547: where @code{t-rex} is a word (say, a constant) that produces a
                   10548: graphical object.
                   10549: 
                   10550: @comment TODO add a 2nd operation eg perimeter.. and use for
                   10551: @comment a concrete example
1.5       anton    10552: 
1.78      anton    10553: @cindex abstract class
                   10554: How do we create a graphical object? With the present definitions,
                   10555: we cannot create a useful graphical object. The class
                   10556: @code{graphical} describes graphical objects in general, but not
                   10557: any concrete graphical object type (C++ users would call it an
                   10558: @emph{abstract class}); e.g., there is no method for the selector
                   10559: @code{draw} in the class @code{graphical}.
1.5       anton    10560: 
1.78      anton    10561: For concrete graphical objects, we define child classes of the
                   10562: class @code{graphical}, e.g.:
1.5       anton    10563: 
1.78      anton    10564: @cindex @code{overrides} usage
                   10565: @cindex @code{field} usage in class definition
1.26      crook    10566: @example
1.78      anton    10567: graphical class \ "graphical" is the parent class
                   10568:   cell% field circle-radius
1.5       anton    10569: 
1.78      anton    10570: :noname ( x y circle -- )
                   10571:   circle-radius @@ draw-circle ;
                   10572: overrides draw
1.5       anton    10573: 
1.78      anton    10574: :noname ( n-radius circle -- )
                   10575:   circle-radius ! ;
                   10576: overrides construct
1.5       anton    10577: 
1.78      anton    10578: end-class circle
                   10579: @end example
1.44      crook    10580: 
1.78      anton    10581: Here we define a class @code{circle} as a child of @code{graphical},
                   10582: with field @code{circle-radius} (which behaves just like a field
                   10583: (@pxref{Structures}); it defines (using @code{overrides}) new methods
                   10584: for the selectors @code{draw} and @code{construct} (@code{construct} is
                   10585: defined in @code{object}, the parent class of @code{graphical}).
1.5       anton    10586: 
1.78      anton    10587: Now we can create a circle on the heap (i.e.,
                   10588: @code{allocate}d memory) with:
1.44      crook    10589: 
1.78      anton    10590: @cindex @code{heap-new} usage
1.5       anton    10591: @example
1.78      anton    10592: 50 circle heap-new constant my-circle
1.5       anton    10593: @end example
                   10594: 
1.78      anton    10595: @noindent
                   10596: @code{heap-new} invokes @code{construct}, thus
                   10597: initializing the field @code{circle-radius} with 50. We can draw
                   10598: this new circle at (100,100) with:
1.5       anton    10599: 
                   10600: @example
1.78      anton    10601: 100 100 my-circle draw
1.5       anton    10602: @end example
                   10603: 
1.78      anton    10604: @cindex selector invocation, restrictions
                   10605: @cindex class definition, restrictions
                   10606: Note: You can only invoke a selector if the object on the TOS
                   10607: (the receiving object) belongs to the class where the selector was
                   10608: defined or one of its descendents; e.g., you can invoke
                   10609: @code{draw} only for objects belonging to @code{graphical}
                   10610: or its descendents (e.g., @code{circle}).  Immediately before
                   10611: @code{end-class}, the search order has to be the same as
                   10612: immediately after @code{class}.
                   10613: 
                   10614: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
                   10615: @subsubsection The @file{object.fs} base class
                   10616: @cindex @code{object} class
                   10617: 
                   10618: When you define a class, you have to specify a parent class.  So how do
                   10619: you start defining classes? There is one class available from the start:
                   10620: @code{object}. It is ancestor for all classes and so is the
                   10621: only class that has no parent. It has two selectors: @code{construct}
                   10622: and @code{print}.
                   10623: 
                   10624: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
                   10625: @subsubsection Creating objects
                   10626: @cindex creating objects
                   10627: @cindex object creation
                   10628: @cindex object allocation options
                   10629: 
                   10630: @cindex @code{heap-new} discussion
                   10631: @cindex @code{dict-new} discussion
                   10632: @cindex @code{construct} discussion
                   10633: You can create and initialize an object of a class on the heap with
                   10634: @code{heap-new} ( ... class -- object ) and in the dictionary
                   10635: (allocation with @code{allot}) with @code{dict-new} (
                   10636: ... class -- object ). Both words invoke @code{construct}, which
                   10637: consumes the stack items indicated by "..." above.
                   10638: 
                   10639: @cindex @code{init-object} discussion
                   10640: @cindex @code{class-inst-size} discussion
                   10641: If you want to allocate memory for an object yourself, you can get its
                   10642: alignment and size with @code{class-inst-size 2@@} ( class --
                   10643: align size ). Once you have memory for an object, you can initialize
                   10644: it with @code{init-object} ( ... class object -- );
                   10645: @code{construct} does only a part of the necessary work.
                   10646: 
                   10647: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
                   10648: @subsubsection Object-Oriented Programming Style
                   10649: @cindex object-oriented programming style
                   10650: @cindex programming style, object-oriented
1.5       anton    10651: 
1.78      anton    10652: This section is not exhaustive.
1.5       anton    10653: 
1.78      anton    10654: @cindex stack effects of selectors
                   10655: @cindex selectors and stack effects
                   10656: In general, it is a good idea to ensure that all methods for the
                   10657: same selector have the same stack effect: when you invoke a selector,
                   10658: you often have no idea which method will be invoked, so, unless all
                   10659: methods have the same stack effect, you will not know the stack effect
                   10660: of the selector invocation.
1.5       anton    10661: 
1.78      anton    10662: One exception to this rule is methods for the selector
                   10663: @code{construct}. We know which method is invoked, because we
                   10664: specify the class to be constructed at the same place. Actually, I
                   10665: defined @code{construct} as a selector only to give the users a
                   10666: convenient way to specify initialization. The way it is used, a
                   10667: mechanism different from selector invocation would be more natural
                   10668: (but probably would take more code and more space to explain).
1.5       anton    10669: 
1.78      anton    10670: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
                   10671: @subsubsection Class Binding
                   10672: @cindex class binding
                   10673: @cindex early binding
1.5       anton    10674: 
1.78      anton    10675: @cindex late binding
                   10676: Normal selector invocations determine the method at run-time depending
                   10677: on the class of the receiving object. This run-time selection is called
                   10678: @i{late binding}.
1.5       anton    10679: 
1.78      anton    10680: Sometimes it's preferable to invoke a different method. For example,
                   10681: you might want to use the simple method for @code{print}ing
                   10682: @code{object}s instead of the possibly long-winded @code{print} method
                   10683: of the receiver class. You can achieve this by replacing the invocation
                   10684: of @code{print} with:
1.5       anton    10685: 
1.78      anton    10686: @cindex @code{[bind]} usage
1.5       anton    10687: @example
1.78      anton    10688: [bind] object print
1.5       anton    10689: @end example
                   10690: 
1.78      anton    10691: @noindent
                   10692: in compiled code or:
                   10693: 
                   10694: @cindex @code{bind} usage
1.5       anton    10695: @example
1.78      anton    10696: bind object print
1.5       anton    10697: @end example
                   10698: 
1.78      anton    10699: @cindex class binding, alternative to
                   10700: @noindent
                   10701: in interpreted code. Alternatively, you can define the method with a
                   10702: name (e.g., @code{print-object}), and then invoke it through the
                   10703: name. Class binding is just a (often more convenient) way to achieve
                   10704: the same effect; it avoids name clutter and allows you to invoke
                   10705: methods directly without naming them first.
1.5       anton    10706: 
1.78      anton    10707: @cindex superclass binding
                   10708: @cindex parent class binding
                   10709: A frequent use of class binding is this: When we define a method
                   10710: for a selector, we often want the method to do what the selector does
                   10711: in the parent class, and a little more. There is a special word for
                   10712: this purpose: @code{[parent]}; @code{[parent]
                   10713: @emph{selector}} is equivalent to @code{[bind] @emph{parent
                   10714: selector}}, where @code{@emph{parent}} is the parent
                   10715: class of the current class. E.g., a method definition might look like:
1.44      crook    10716: 
1.78      anton    10717: @cindex @code{[parent]} usage
                   10718: @example
                   10719: :noname
                   10720:   dup [parent] foo \ do parent's foo on the receiving object
                   10721:   ... \ do some more
                   10722: ; overrides foo
                   10723: @end example
1.6       pazsan   10724: 
1.78      anton    10725: @cindex class binding as optimization
                   10726: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
                   10727: March 1997), Andrew McKewan presents class binding as an optimization
                   10728: technique. I recommend not using it for this purpose unless you are in
                   10729: an emergency. Late binding is pretty fast with this model anyway, so the
                   10730: benefit of using class binding is small; the cost of using class binding
                   10731: where it is not appropriate is reduced maintainability.
1.44      crook    10732: 
1.78      anton    10733: While we are at programming style questions: You should bind
                   10734: selectors only to ancestor classes of the receiving object. E.g., say,
                   10735: you know that the receiving object is of class @code{foo} or its
                   10736: descendents; then you should bind only to @code{foo} and its
                   10737: ancestors.
1.12      anton    10738: 
1.78      anton    10739: @node Method conveniences, Classes and Scoping, Class Binding, Objects
                   10740: @subsubsection Method conveniences
                   10741: @cindex method conveniences
1.44      crook    10742: 
1.78      anton    10743: In a method you usually access the receiving object pretty often.  If
                   10744: you define the method as a plain colon definition (e.g., with
                   10745: @code{:noname}), you may have to do a lot of stack
                   10746: gymnastics. To avoid this, you can define the method with @code{m:
                   10747: ... ;m}. E.g., you could define the method for
                   10748: @code{draw}ing a @code{circle} with
1.6       pazsan   10749: 
1.78      anton    10750: @cindex @code{this} usage
                   10751: @cindex @code{m:} usage
                   10752: @cindex @code{;m} usage
                   10753: @example
                   10754: m: ( x y circle -- )
                   10755:   ( x y ) this circle-radius @@ draw-circle ;m
                   10756: @end example
1.6       pazsan   10757: 
1.78      anton    10758: @cindex @code{exit} in @code{m: ... ;m}
                   10759: @cindex @code{exitm} discussion
                   10760: @cindex @code{catch} in @code{m: ... ;m}
                   10761: When this method is executed, the receiver object is removed from the
                   10762: stack; you can access it with @code{this} (admittedly, in this
                   10763: example the use of @code{m: ... ;m} offers no advantage). Note
                   10764: that I specify the stack effect for the whole method (i.e. including
                   10765: the receiver object), not just for the code between @code{m:}
                   10766: and @code{;m}. You cannot use @code{exit} in
                   10767: @code{m:...;m}; instead, use
                   10768: @code{exitm}.@footnote{Moreover, for any word that calls
                   10769: @code{catch} and was defined before loading
                   10770: @code{objects.fs}, you have to redefine it like I redefined
                   10771: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12      anton    10772: 
1.78      anton    10773: @cindex @code{inst-var} usage
                   10774: You will frequently use sequences of the form @code{this
                   10775: @emph{field}} (in the example above: @code{this
                   10776: circle-radius}). If you use the field only in this way, you can
                   10777: define it with @code{inst-var} and eliminate the
                   10778: @code{this} before the field name. E.g., the @code{circle}
                   10779: class above could also be defined with:
1.6       pazsan   10780: 
1.78      anton    10781: @example
                   10782: graphical class
                   10783:   cell% inst-var radius
1.6       pazsan   10784: 
1.78      anton    10785: m: ( x y circle -- )
                   10786:   radius @@ draw-circle ;m
                   10787: overrides draw
1.6       pazsan   10788: 
1.78      anton    10789: m: ( n-radius circle -- )
                   10790:   radius ! ;m
                   10791: overrides construct
1.6       pazsan   10792: 
1.78      anton    10793: end-class circle
                   10794: @end example
1.6       pazsan   10795: 
1.78      anton    10796: @code{radius} can only be used in @code{circle} and its
                   10797: descendent classes and inside @code{m:...;m}.
1.6       pazsan   10798: 
1.78      anton    10799: @cindex @code{inst-value} usage
                   10800: You can also define fields with @code{inst-value}, which is
                   10801: to @code{inst-var} what @code{value} is to
                   10802: @code{variable}.  You can change the value of such a field with
                   10803: @code{[to-inst]}.  E.g., we could also define the class
                   10804: @code{circle} like this:
1.44      crook    10805: 
1.78      anton    10806: @example
                   10807: graphical class
                   10808:   inst-value radius
1.6       pazsan   10809: 
1.78      anton    10810: m: ( x y circle -- )
                   10811:   radius draw-circle ;m
                   10812: overrides draw
1.44      crook    10813: 
1.78      anton    10814: m: ( n-radius circle -- )
                   10815:   [to-inst] radius ;m
                   10816: overrides construct
1.6       pazsan   10817: 
1.78      anton    10818: end-class circle
                   10819: @end example
1.6       pazsan   10820: 
1.78      anton    10821: @c !! :m is easy to confuse with m:.  Another name would be better.
1.6       pazsan   10822: 
1.78      anton    10823: @c Finally, you can define named methods with @code{:m}.  One use of this
                   10824: @c feature is the definition of words that occur only in one class and are
                   10825: @c not intended to be overridden, but which still need method context
                   10826: @c (e.g., for accessing @code{inst-var}s).  Another use is for methods that
                   10827: @c would be bound frequently, if defined anonymously.
1.6       pazsan   10828: 
                   10829: 
1.78      anton    10830: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
                   10831: @subsubsection Classes and Scoping
                   10832: @cindex classes and scoping
                   10833: @cindex scoping and classes
1.6       pazsan   10834: 
1.78      anton    10835: Inheritance is frequent, unlike structure extension. This exacerbates
                   10836: the problem with the field name convention (@pxref{Structure Naming
                   10837: Convention}): One always has to remember in which class the field was
                   10838: originally defined; changing a part of the class structure would require
                   10839: changes for renaming in otherwise unaffected code.
1.6       pazsan   10840: 
1.78      anton    10841: @cindex @code{inst-var} visibility
                   10842: @cindex @code{inst-value} visibility
                   10843: To solve this problem, I added a scoping mechanism (which was not in my
                   10844: original charter): A field defined with @code{inst-var} (or
                   10845: @code{inst-value}) is visible only in the class where it is defined and in
                   10846: the descendent classes of this class.  Using such fields only makes
                   10847: sense in @code{m:}-defined methods in these classes anyway.
1.6       pazsan   10848: 
1.78      anton    10849: This scoping mechanism allows us to use the unadorned field name,
                   10850: because name clashes with unrelated words become much less likely.
1.6       pazsan   10851: 
1.78      anton    10852: @cindex @code{protected} discussion
                   10853: @cindex @code{private} discussion
                   10854: Once we have this mechanism, we can also use it for controlling the
                   10855: visibility of other words: All words defined after
                   10856: @code{protected} are visible only in the current class and its
                   10857: descendents. @code{public} restores the compilation
                   10858: (i.e. @code{current}) word list that was in effect before. If you
                   10859: have several @code{protected}s without an intervening
                   10860: @code{public} or @code{set-current}, @code{public}
                   10861: will restore the compilation word list in effect before the first of
                   10862: these @code{protected}s.
1.6       pazsan   10863: 
1.78      anton    10864: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
                   10865: @subsubsection Dividing classes
                   10866: @cindex Dividing classes
                   10867: @cindex @code{methods}...@code{end-methods}
1.6       pazsan   10868: 
1.78      anton    10869: You may want to do the definition of methods separate from the
                   10870: definition of the class, its selectors, fields, and instance variables,
                   10871: i.e., separate the implementation from the definition.  You can do this
                   10872: in the following way:
1.6       pazsan   10873: 
1.78      anton    10874: @example
                   10875: graphical class
                   10876:   inst-value radius
                   10877: end-class circle
1.6       pazsan   10878: 
1.78      anton    10879: ... \ do some other stuff
1.6       pazsan   10880: 
1.78      anton    10881: circle methods \ now we are ready
1.44      crook    10882: 
1.78      anton    10883: m: ( x y circle -- )
                   10884:   radius draw-circle ;m
                   10885: overrides draw
1.6       pazsan   10886: 
1.78      anton    10887: m: ( n-radius circle -- )
                   10888:   [to-inst] radius ;m
                   10889: overrides construct
1.44      crook    10890: 
1.78      anton    10891: end-methods
                   10892: @end example
1.7       pazsan   10893: 
1.78      anton    10894: You can use several @code{methods}...@code{end-methods} sections.  The
                   10895: only things you can do to the class in these sections are: defining
                   10896: methods, and overriding the class's selectors.  You must not define new
                   10897: selectors or fields.
1.7       pazsan   10898: 
1.78      anton    10899: Note that you often have to override a selector before using it.  In
                   10900: particular, you usually have to override @code{construct} with a new
                   10901: method before you can invoke @code{heap-new} and friends.  E.g., you
                   10902: must not create a circle before the @code{overrides construct} sequence
                   10903: in the example above.
1.7       pazsan   10904: 
1.78      anton    10905: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
                   10906: @subsubsection Object Interfaces
                   10907: @cindex object interfaces
                   10908: @cindex interfaces for objects
1.7       pazsan   10909: 
1.78      anton    10910: In this model you can only call selectors defined in the class of the
                   10911: receiving objects or in one of its ancestors. If you call a selector
                   10912: with a receiving object that is not in one of these classes, the
                   10913: result is undefined; if you are lucky, the program crashes
                   10914: immediately.
1.7       pazsan   10915: 
1.78      anton    10916: @cindex selectors common to hardly-related classes
                   10917: Now consider the case when you want to have a selector (or several)
                   10918: available in two classes: You would have to add the selector to a
                   10919: common ancestor class, in the worst case to @code{object}. You
                   10920: may not want to do this, e.g., because someone else is responsible for
                   10921: this ancestor class.
1.7       pazsan   10922: 
1.78      anton    10923: The solution for this problem is interfaces. An interface is a
                   10924: collection of selectors. If a class implements an interface, the
                   10925: selectors become available to the class and its descendents. A class
                   10926: can implement an unlimited number of interfaces. For the problem
                   10927: discussed above, we would define an interface for the selector(s), and
                   10928: both classes would implement the interface.
1.7       pazsan   10929: 
1.78      anton    10930: As an example, consider an interface @code{storage} for
                   10931: writing objects to disk and getting them back, and a class
                   10932: @code{foo} that implements it. The code would look like this:
1.7       pazsan   10933: 
1.78      anton    10934: @cindex @code{interface} usage
                   10935: @cindex @code{end-interface} usage
                   10936: @cindex @code{implementation} usage
                   10937: @example
                   10938: interface
                   10939:   selector write ( file object -- )
                   10940:   selector read1 ( file object -- )
                   10941: end-interface storage
1.13      pazsan   10942: 
1.78      anton    10943: bar class
                   10944:   storage implementation
1.13      pazsan   10945: 
1.78      anton    10946: ... overrides write
                   10947: ... overrides read1
                   10948: ...
                   10949: end-class foo
                   10950: @end example
1.13      pazsan   10951: 
1.78      anton    10952: @noindent
                   10953: (I would add a word @code{read} @i{( file -- object )} that uses
                   10954: @code{read1} internally, but that's beyond the point illustrated
                   10955: here.)
1.13      pazsan   10956: 
1.78      anton    10957: Note that you cannot use @code{protected} in an interface; and
                   10958: of course you cannot define fields.
1.13      pazsan   10959: 
1.78      anton    10960: In the Neon model, all selectors are available for all classes;
                   10961: therefore it does not need interfaces. The price you pay in this model
                   10962: is slower late binding, and therefore, added complexity to avoid late
                   10963: binding.
1.13      pazsan   10964: 
1.78      anton    10965: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
                   10966: @subsubsection @file{objects.fs} Implementation
                   10967: @cindex @file{objects.fs} implementation
1.13      pazsan   10968: 
1.78      anton    10969: @cindex @code{object-map} discussion
                   10970: An object is a piece of memory, like one of the data structures
                   10971: described with @code{struct...end-struct}. It has a field
                   10972: @code{object-map} that points to the method map for the object's
                   10973: class.
1.13      pazsan   10974: 
1.78      anton    10975: @cindex method map
                   10976: @cindex virtual function table
                   10977: The @emph{method map}@footnote{This is Self terminology; in C++
                   10978: terminology: virtual function table.} is an array that contains the
                   10979: execution tokens (@i{xt}s) of the methods for the object's class. Each
                   10980: selector contains an offset into a method map.
1.13      pazsan   10981: 
1.78      anton    10982: @cindex @code{selector} implementation, class
                   10983: @code{selector} is a defining word that uses
                   10984: @code{CREATE} and @code{DOES>}. The body of the
                   10985: selector contains the offset; the @code{DOES>} action for a
                   10986: class selector is, basically:
1.8       pazsan   10987: 
                   10988: @example
1.78      anton    10989: ( object addr ) @@ over object-map @@ + @@ execute
1.13      pazsan   10990: @end example
                   10991: 
1.78      anton    10992: Since @code{object-map} is the first field of the object, it
                   10993: does not generate any code. As you can see, calling a selector has a
                   10994: small, constant cost.
1.26      crook    10995: 
1.78      anton    10996: @cindex @code{current-interface} discussion
                   10997: @cindex class implementation and representation
                   10998: A class is basically a @code{struct} combined with a method
                   10999: map. During the class definition the alignment and size of the class
                   11000: are passed on the stack, just as with @code{struct}s, so
                   11001: @code{field} can also be used for defining class
                   11002: fields. However, passing more items on the stack would be
                   11003: inconvenient, so @code{class} builds a data structure in memory,
                   11004: which is accessed through the variable
                   11005: @code{current-interface}. After its definition is complete, the
                   11006: class is represented on the stack by a pointer (e.g., as parameter for
                   11007: a child class definition).
1.26      crook    11008: 
1.78      anton    11009: A new class starts off with the alignment and size of its parent,
                   11010: and a copy of the parent's method map. Defining new fields extends the
                   11011: size and alignment; likewise, defining new selectors extends the
                   11012: method map. @code{overrides} just stores a new @i{xt} in the method
                   11013: map at the offset given by the selector.
1.13      pazsan   11014: 
1.78      anton    11015: @cindex class binding, implementation
                   11016: Class binding just gets the @i{xt} at the offset given by the selector
                   11017: from the class's method map and @code{compile,}s (in the case of
                   11018: @code{[bind]}) it.
1.13      pazsan   11019: 
1.78      anton    11020: @cindex @code{this} implementation
                   11021: @cindex @code{catch} and @code{this}
                   11022: @cindex @code{this} and @code{catch}
                   11023: I implemented @code{this} as a @code{value}. At the
                   11024: start of an @code{m:...;m} method the old @code{this} is
                   11025: stored to the return stack and restored at the end; and the object on
                   11026: the TOS is stored @code{TO this}. This technique has one
                   11027: disadvantage: If the user does not leave the method via
                   11028: @code{;m}, but via @code{throw} or @code{exit},
                   11029: @code{this} is not restored (and @code{exit} may
                   11030: crash). To deal with the @code{throw} problem, I have redefined
                   11031: @code{catch} to save and restore @code{this}; the same
                   11032: should be done with any word that can catch an exception. As for
                   11033: @code{exit}, I simply forbid it (as a replacement, there is
                   11034: @code{exitm}).
1.13      pazsan   11035: 
1.78      anton    11036: @cindex @code{inst-var} implementation
                   11037: @code{inst-var} is just the same as @code{field}, with
                   11038: a different @code{DOES>} action:
1.13      pazsan   11039: @example
1.78      anton    11040: @@ this +
1.8       pazsan   11041: @end example
1.78      anton    11042: Similar for @code{inst-value}.
1.8       pazsan   11043: 
1.78      anton    11044: @cindex class scoping implementation
                   11045: Each class also has a word list that contains the words defined with
                   11046: @code{inst-var} and @code{inst-value}, and its protected
                   11047: words. It also has a pointer to its parent. @code{class} pushes
                   11048: the word lists of the class and all its ancestors onto the search order stack,
                   11049: and @code{end-class} drops them.
1.20      pazsan   11050: 
1.78      anton    11051: @cindex interface implementation
                   11052: An interface is like a class without fields, parent and protected
                   11053: words; i.e., it just has a method map. If a class implements an
                   11054: interface, its method map contains a pointer to the method map of the
                   11055: interface. The positive offsets in the map are reserved for class
                   11056: methods, therefore interface map pointers have negative
                   11057: offsets. Interfaces have offsets that are unique throughout the
                   11058: system, unlike class selectors, whose offsets are only unique for the
                   11059: classes where the selector is available (invokable).
1.20      pazsan   11060: 
1.78      anton    11061: This structure means that interface selectors have to perform one
                   11062: indirection more than class selectors to find their method. Their body
                   11063: contains the interface map pointer offset in the class method map, and
                   11064: the method offset in the interface method map. The
                   11065: @code{does>} action for an interface selector is, basically:
1.20      pazsan   11066: 
                   11067: @example
1.78      anton    11068: ( object selector-body )
                   11069: 2dup selector-interface @@ ( object selector-body object interface-offset )
                   11070: swap object-map @@ + @@ ( object selector-body map )
                   11071: swap selector-offset @@ + @@ execute
1.20      pazsan   11072: @end example
                   11073: 
1.78      anton    11074: where @code{object-map} and @code{selector-offset} are
                   11075: first fields and generate no code.
1.20      pazsan   11076: 
1.78      anton    11077: As a concrete example, consider the following code:
1.20      pazsan   11078: 
                   11079: @example
1.78      anton    11080: interface
                   11081:   selector if1sel1
                   11082:   selector if1sel2
                   11083: end-interface if1
1.20      pazsan   11084: 
1.78      anton    11085: object class
                   11086:   if1 implementation
                   11087:   selector cl1sel1
                   11088:   cell% inst-var cl1iv1
1.20      pazsan   11089: 
1.78      anton    11090: ' m1 overrides construct
                   11091: ' m2 overrides if1sel1
                   11092: ' m3 overrides if1sel2
                   11093: ' m4 overrides cl1sel2
                   11094: end-class cl1
1.20      pazsan   11095: 
1.78      anton    11096: create obj1 object dict-new drop
                   11097: create obj2 cl1    dict-new drop
                   11098: @end example
1.20      pazsan   11099: 
1.78      anton    11100: The data structure created by this code (including the data structure
                   11101: for @code{object}) is shown in the
                   11102: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
                   11103: @comment TODO add this diagram..
1.20      pazsan   11104: 
1.78      anton    11105: @node Objects Glossary,  , Objects Implementation, Objects
                   11106: @subsubsection @file{objects.fs} Glossary
                   11107: @cindex @file{objects.fs} Glossary
1.20      pazsan   11108: 
                   11109: 
1.78      anton    11110: doc---objects-bind
                   11111: doc---objects-<bind>
                   11112: doc---objects-bind'
                   11113: doc---objects-[bind]
                   11114: doc---objects-class
                   11115: doc---objects-class->map
                   11116: doc---objects-class-inst-size
                   11117: doc---objects-class-override!
1.79      anton    11118: doc---objects-class-previous
                   11119: doc---objects-class>order
1.78      anton    11120: doc---objects-construct
                   11121: doc---objects-current'
                   11122: doc---objects-[current]
                   11123: doc---objects-current-interface
                   11124: doc---objects-dict-new
                   11125: doc---objects-end-class
                   11126: doc---objects-end-class-noname
                   11127: doc---objects-end-interface
                   11128: doc---objects-end-interface-noname
                   11129: doc---objects-end-methods
                   11130: doc---objects-exitm
                   11131: doc---objects-heap-new
                   11132: doc---objects-implementation
                   11133: doc---objects-init-object
                   11134: doc---objects-inst-value
                   11135: doc---objects-inst-var
                   11136: doc---objects-interface
                   11137: doc---objects-m:
                   11138: doc---objects-:m
                   11139: doc---objects-;m
                   11140: doc---objects-method
                   11141: doc---objects-methods
                   11142: doc---objects-object
                   11143: doc---objects-overrides
                   11144: doc---objects-[parent]
                   11145: doc---objects-print
                   11146: doc---objects-protected
                   11147: doc---objects-public
                   11148: doc---objects-selector
                   11149: doc---objects-this
                   11150: doc---objects-<to-inst>
                   11151: doc---objects-[to-inst]
                   11152: doc---objects-to-this
                   11153: doc---objects-xt-new
1.20      pazsan   11154: 
                   11155: 
1.78      anton    11156: @c -------------------------------------------------------------
                   11157: @node OOF, Mini-OOF, Objects, Object-oriented Forth
                   11158: @subsection The @file{oof.fs} model
                   11159: @cindex oof
                   11160: @cindex object-oriented programming
1.20      pazsan   11161: 
1.78      anton    11162: @cindex @file{objects.fs}
                   11163: @cindex @file{oof.fs}
1.20      pazsan   11164: 
1.78      anton    11165: This section describes the @file{oof.fs} package.
1.20      pazsan   11166: 
1.78      anton    11167: The package described in this section has been used in bigFORTH since 1991, and
                   11168: used for two large applications: a chromatographic system used to
                   11169: create new medicaments, and a graphic user interface library (MINOS).
1.20      pazsan   11170: 
1.78      anton    11171: You can find a description (in German) of @file{oof.fs} in @cite{Object
                   11172: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
                   11173: 10(2), 1994.
1.20      pazsan   11174: 
1.78      anton    11175: @menu
                   11176: * Properties of the OOF model::  
                   11177: * Basic OOF Usage::             
                   11178: * The OOF base class::          
                   11179: * Class Declaration::           
                   11180: * Class Implementation::        
                   11181: @end menu
1.20      pazsan   11182: 
1.78      anton    11183: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
                   11184: @subsubsection Properties of the @file{oof.fs} model
                   11185: @cindex @file{oof.fs} properties
1.20      pazsan   11186: 
1.78      anton    11187: @itemize @bullet
                   11188: @item
                   11189: This model combines object oriented programming with information
                   11190: hiding. It helps you writing large application, where scoping is
                   11191: necessary, because it provides class-oriented scoping.
1.20      pazsan   11192: 
1.78      anton    11193: @item
                   11194: Named objects, object pointers, and object arrays can be created,
                   11195: selector invocation uses the ``object selector'' syntax. Selector invocation
                   11196: to objects and/or selectors on the stack is a bit less convenient, but
                   11197: possible.
1.44      crook    11198: 
1.78      anton    11199: @item
                   11200: Selector invocation and instance variable usage of the active object is
                   11201: straightforward, since both make use of the active object.
1.44      crook    11202: 
1.78      anton    11203: @item
                   11204: Late binding is efficient and easy to use.
1.20      pazsan   11205: 
1.78      anton    11206: @item
                   11207: State-smart objects parse selectors. However, extensibility is provided
                   11208: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20      pazsan   11209: 
1.78      anton    11210: @item
                   11211: An implementation in ANS Forth is available.
1.20      pazsan   11212: 
1.78      anton    11213: @end itemize
1.23      crook    11214: 
                   11215: 
1.78      anton    11216: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
                   11217: @subsubsection Basic @file{oof.fs} Usage
                   11218: @cindex @file{oof.fs} usage
1.23      crook    11219: 
1.78      anton    11220: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23      crook    11221: 
1.78      anton    11222: You can define a class for graphical objects like this:
1.23      crook    11223: 
1.78      anton    11224: @cindex @code{class} usage
                   11225: @cindex @code{class;} usage
                   11226: @cindex @code{method} usage
                   11227: @example
                   11228: object class graphical \ "object" is the parent class
1.139     pazsan   11229:   method draw ( x y -- )
1.78      anton    11230: class;
                   11231: @end example
1.23      crook    11232: 
1.78      anton    11233: This code defines a class @code{graphical} with an
                   11234: operation @code{draw}.  We can perform the operation
                   11235: @code{draw} on any @code{graphical} object, e.g.:
1.23      crook    11236: 
1.78      anton    11237: @example
                   11238: 100 100 t-rex draw
                   11239: @end example
1.23      crook    11240: 
1.78      anton    11241: @noindent
                   11242: where @code{t-rex} is an object or object pointer, created with e.g.
                   11243: @code{graphical : t-rex}.
1.23      crook    11244: 
1.78      anton    11245: @cindex abstract class
                   11246: How do we create a graphical object? With the present definitions,
                   11247: we cannot create a useful graphical object. The class
                   11248: @code{graphical} describes graphical objects in general, but not
                   11249: any concrete graphical object type (C++ users would call it an
                   11250: @emph{abstract class}); e.g., there is no method for the selector
                   11251: @code{draw} in the class @code{graphical}.
1.23      crook    11252: 
1.78      anton    11253: For concrete graphical objects, we define child classes of the
                   11254: class @code{graphical}, e.g.:
1.23      crook    11255: 
1.78      anton    11256: @example
                   11257: graphical class circle \ "graphical" is the parent class
                   11258:   cell var circle-radius
                   11259: how:
                   11260:   : draw ( x y -- )
                   11261:     circle-radius @@ draw-circle ;
1.23      crook    11262: 
1.139     pazsan   11263:   : init ( n-radius -- )
1.78      anton    11264:     circle-radius ! ;
                   11265: class;
                   11266: @end example
1.1       anton    11267: 
1.78      anton    11268: Here we define a class @code{circle} as a child of @code{graphical},
                   11269: with a field @code{circle-radius}; it defines new methods for the
                   11270: selectors @code{draw} and @code{init} (@code{init} is defined in
                   11271: @code{object}, the parent class of @code{graphical}).
1.1       anton    11272: 
1.78      anton    11273: Now we can create a circle in the dictionary with:
1.1       anton    11274: 
1.78      anton    11275: @example
                   11276: 50 circle : my-circle
                   11277: @end example
1.21      crook    11278: 
1.78      anton    11279: @noindent
                   11280: @code{:} invokes @code{init}, thus initializing the field
                   11281: @code{circle-radius} with 50. We can draw this new circle at (100,100)
                   11282: with:
1.1       anton    11283: 
1.78      anton    11284: @example
                   11285: 100 100 my-circle draw
                   11286: @end example
1.1       anton    11287: 
1.78      anton    11288: @cindex selector invocation, restrictions
                   11289: @cindex class definition, restrictions
                   11290: Note: You can only invoke a selector if the receiving object belongs to
                   11291: the class where the selector was defined or one of its descendents;
                   11292: e.g., you can invoke @code{draw} only for objects belonging to
                   11293: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
                   11294: mechanism will check if you try to invoke a selector that is not
                   11295: defined in this class hierarchy, so you'll get an error at compilation
                   11296: time.
1.1       anton    11297: 
                   11298: 
1.78      anton    11299: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
                   11300: @subsubsection The @file{oof.fs} base class
                   11301: @cindex @file{oof.fs} base class
1.1       anton    11302: 
1.78      anton    11303: When you define a class, you have to specify a parent class.  So how do
                   11304: you start defining classes? There is one class available from the start:
                   11305: @code{object}. You have to use it as ancestor for all classes. It is the
                   11306: only class that has no parent. Classes are also objects, except that
                   11307: they don't have instance variables; class manipulation such as
                   11308: inheritance or changing definitions of a class is handled through
                   11309: selectors of the class @code{object}.
1.1       anton    11310: 
1.78      anton    11311: @code{object} provides a number of selectors:
1.1       anton    11312: 
1.78      anton    11313: @itemize @bullet
                   11314: @item
                   11315: @code{class} for subclassing, @code{definitions} to add definitions
                   11316: later on, and @code{class?} to get type informations (is the class a
                   11317: subclass of the class passed on the stack?).
1.1       anton    11318: 
1.78      anton    11319: doc---object-class
                   11320: doc---object-definitions
                   11321: doc---object-class?
1.1       anton    11322: 
                   11323: 
1.26      crook    11324: @item
1.78      anton    11325: @code{init} and @code{dispose} as constructor and destructor of the
                   11326: object. @code{init} is invocated after the object's memory is allocated,
                   11327: while @code{dispose} also handles deallocation. Thus if you redefine
                   11328: @code{dispose}, you have to call the parent's dispose with @code{super
                   11329: dispose}, too.
                   11330: 
                   11331: doc---object-init
                   11332: doc---object-dispose
                   11333: 
1.1       anton    11334: 
1.26      crook    11335: @item
1.78      anton    11336: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
                   11337: @code{[]} to create named and unnamed objects and object arrays or
                   11338: object pointers.
                   11339: 
                   11340: doc---object-new
                   11341: doc---object-new[]
                   11342: doc---object-:
                   11343: doc---object-ptr
                   11344: doc---object-asptr
                   11345: doc---object-[]
                   11346: 
1.1       anton    11347: 
1.26      crook    11348: @item
1.78      anton    11349: @code{::} and @code{super} for explicit scoping. You should use explicit
                   11350: scoping only for super classes or classes with the same set of instance
                   11351: variables. Explicitly-scoped selectors use early binding.
1.21      crook    11352: 
1.78      anton    11353: doc---object-::
                   11354: doc---object-super
1.21      crook    11355: 
                   11356: 
1.26      crook    11357: @item
1.78      anton    11358: @code{self} to get the address of the object
1.21      crook    11359: 
1.78      anton    11360: doc---object-self
1.21      crook    11361: 
                   11362: 
1.78      anton    11363: @item
                   11364: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
                   11365: pointers and instance defers.
1.21      crook    11366: 
1.78      anton    11367: doc---object-bind
                   11368: doc---object-bound
                   11369: doc---object-link
                   11370: doc---object-is
1.21      crook    11371: 
                   11372: 
1.78      anton    11373: @item
                   11374: @code{'} to obtain selector tokens, @code{send} to invocate selectors
                   11375: form the stack, and @code{postpone} to generate selector invocation code.
1.21      crook    11376: 
1.78      anton    11377: doc---object-'
                   11378: doc---object-postpone
1.21      crook    11379: 
                   11380: 
1.78      anton    11381: @item
                   11382: @code{with} and @code{endwith} to select the active object from the
                   11383: stack, and enable its scope. Using @code{with} and @code{endwith}
                   11384: also allows you to create code using selector @code{postpone} without being
                   11385: trapped by the state-smart objects.
1.21      crook    11386: 
1.78      anton    11387: doc---object-with
                   11388: doc---object-endwith
1.21      crook    11389: 
                   11390: 
1.78      anton    11391: @end itemize
1.21      crook    11392: 
1.78      anton    11393: @node Class Declaration, Class Implementation, The OOF base class, OOF
                   11394: @subsubsection Class Declaration
                   11395: @cindex class declaration
1.21      crook    11396: 
1.78      anton    11397: @itemize @bullet
                   11398: @item
                   11399: Instance variables
1.21      crook    11400: 
1.78      anton    11401: doc---oof-var
1.21      crook    11402: 
                   11403: 
1.78      anton    11404: @item
                   11405: Object pointers
1.21      crook    11406: 
1.78      anton    11407: doc---oof-ptr
                   11408: doc---oof-asptr
1.21      crook    11409: 
                   11410: 
1.78      anton    11411: @item
                   11412: Instance defers
1.21      crook    11413: 
1.78      anton    11414: doc---oof-defer
1.21      crook    11415: 
                   11416: 
1.78      anton    11417: @item
                   11418: Method selectors
1.21      crook    11419: 
1.78      anton    11420: doc---oof-early
                   11421: doc---oof-method
1.21      crook    11422: 
                   11423: 
1.78      anton    11424: @item
                   11425: Class-wide variables
1.21      crook    11426: 
1.78      anton    11427: doc---oof-static
1.21      crook    11428: 
                   11429: 
1.78      anton    11430: @item
                   11431: End declaration
1.1       anton    11432: 
1.78      anton    11433: doc---oof-how:
                   11434: doc---oof-class;
1.21      crook    11435: 
                   11436: 
1.78      anton    11437: @end itemize
1.21      crook    11438: 
1.78      anton    11439: @c -------------------------------------------------------------
                   11440: @node Class Implementation,  , Class Declaration, OOF
                   11441: @subsubsection Class Implementation
                   11442: @cindex class implementation
1.21      crook    11443: 
1.78      anton    11444: @c -------------------------------------------------------------
                   11445: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
                   11446: @subsection The @file{mini-oof.fs} model
                   11447: @cindex mini-oof
1.21      crook    11448: 
1.78      anton    11449: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79      anton    11450: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78      anton    11451: and reduces to the bare minimum of features. This is based on a posting
                   11452: of Bernd Paysan in comp.lang.forth.
1.21      crook    11453: 
1.78      anton    11454: @menu
                   11455: * Basic Mini-OOF Usage::        
                   11456: * Mini-OOF Example::            
                   11457: * Mini-OOF Implementation::     
                   11458: @end menu
1.21      crook    11459: 
1.78      anton    11460: @c -------------------------------------------------------------
                   11461: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
                   11462: @subsubsection Basic @file{mini-oof.fs} Usage
                   11463: @cindex mini-oof usage
1.21      crook    11464: 
1.78      anton    11465: There is a base class (@code{class}, which allocates one cell for the
                   11466: object pointer) plus seven other words: to define a method, a variable,
                   11467: a class; to end a class, to resolve binding, to allocate an object and
                   11468: to compile a class method.
                   11469: @comment TODO better description of the last one
1.26      crook    11470: 
1.21      crook    11471: 
1.78      anton    11472: doc-object
                   11473: doc-method
                   11474: doc-var
                   11475: doc-class
                   11476: doc-end-class
                   11477: doc-defines
                   11478: doc-new
                   11479: doc-::
1.21      crook    11480: 
                   11481: 
                   11482: 
1.78      anton    11483: @c -------------------------------------------------------------
                   11484: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
                   11485: @subsubsection Mini-OOF Example
                   11486: @cindex mini-oof example
1.1       anton    11487: 
1.78      anton    11488: A short example shows how to use this package. This example, in slightly
                   11489: extended form, is supplied as @file{moof-exm.fs}
                   11490: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20      pazsan   11491: 
1.26      crook    11492: @example
1.78      anton    11493: object class
                   11494:   method init
                   11495:   method draw
                   11496: end-class graphical
1.26      crook    11497: @end example
1.20      pazsan   11498: 
1.78      anton    11499: This code defines a class @code{graphical} with an
                   11500: operation @code{draw}.  We can perform the operation
                   11501: @code{draw} on any @code{graphical} object, e.g.:
1.20      pazsan   11502: 
1.26      crook    11503: @example
1.78      anton    11504: 100 100 t-rex draw
1.26      crook    11505: @end example
1.12      anton    11506: 
1.78      anton    11507: where @code{t-rex} is an object or object pointer, created with e.g.
                   11508: @code{graphical new Constant t-rex}.
1.12      anton    11509: 
1.78      anton    11510: For concrete graphical objects, we define child classes of the
                   11511: class @code{graphical}, e.g.:
1.12      anton    11512: 
1.26      crook    11513: @example
                   11514: graphical class
1.78      anton    11515:   cell var circle-radius
                   11516: end-class circle \ "graphical" is the parent class
1.12      anton    11517: 
1.78      anton    11518: :noname ( x y -- )
                   11519:   circle-radius @@ draw-circle ; circle defines draw
                   11520: :noname ( r -- )
                   11521:   circle-radius ! ; circle defines init
                   11522: @end example
1.12      anton    11523: 
1.78      anton    11524: There is no implicit init method, so we have to define one. The creation
                   11525: code of the object now has to call init explicitely.
1.21      crook    11526: 
1.78      anton    11527: @example
                   11528: circle new Constant my-circle
                   11529: 50 my-circle init
1.12      anton    11530: @end example
                   11531: 
1.78      anton    11532: It is also possible to add a function to create named objects with
                   11533: automatic call of @code{init}, given that all objects have @code{init}
                   11534: on the same place:
1.38      anton    11535: 
1.78      anton    11536: @example
                   11537: : new: ( .. o "name" -- )
                   11538:     new dup Constant init ;
                   11539: 80 circle new: large-circle
                   11540: @end example
1.12      anton    11541: 
1.78      anton    11542: We can draw this new circle at (100,100) with:
1.12      anton    11543: 
1.78      anton    11544: @example
                   11545: 100 100 my-circle draw
                   11546: @end example
1.12      anton    11547: 
1.78      anton    11548: @node Mini-OOF Implementation,  , Mini-OOF Example, Mini-OOF
                   11549: @subsubsection @file{mini-oof.fs} Implementation
1.12      anton    11550: 
1.78      anton    11551: Object-oriented systems with late binding typically use a
                   11552: ``vtable''-approach: the first variable in each object is a pointer to a
                   11553: table, which contains the methods as function pointers. The vtable
                   11554: may also contain other information.
1.12      anton    11555: 
1.79      anton    11556: So first, let's declare selectors:
1.37      anton    11557: 
                   11558: @example
1.79      anton    11559: : method ( m v "name" -- m' v ) Create  over , swap cell+ swap
1.78      anton    11560:   DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
                   11561: @end example
1.37      anton    11562: 
1.79      anton    11563: During selector declaration, the number of selectors and instance
                   11564: variables is on the stack (in address units). @code{method} creates one
                   11565: selector and increments the selector number. To execute a selector, it
1.78      anton    11566: takes the object, fetches the vtable pointer, adds the offset, and
1.79      anton    11567: executes the method @i{xt} stored there. Each selector takes the object
                   11568: it is invoked with as top of stack parameter; it passes the parameters
                   11569: (including the object) unchanged to the appropriate method which should
1.78      anton    11570: consume that object.
1.37      anton    11571: 
1.78      anton    11572: Now, we also have to declare instance variables
1.37      anton    11573: 
1.78      anton    11574: @example
1.79      anton    11575: : var ( m v size "name" -- m v' ) Create  over , +
1.78      anton    11576:   DOES> ( o -- addr ) @@ + ;
1.37      anton    11577: @end example
                   11578: 
1.78      anton    11579: As before, a word is created with the current offset. Instance
                   11580: variables can have different sizes (cells, floats, doubles, chars), so
                   11581: all we do is take the size and add it to the offset. If your machine
                   11582: has alignment restrictions, put the proper @code{aligned} or
                   11583: @code{faligned} before the variable, to adjust the variable
                   11584: offset. That's why it is on the top of stack.
1.37      anton    11585: 
1.78      anton    11586: We need a starting point (the base object) and some syntactic sugar:
1.37      anton    11587: 
1.78      anton    11588: @example
                   11589: Create object  1 cells , 2 cells ,
1.79      anton    11590: : class ( class -- class selectors vars ) dup 2@@ ;
1.78      anton    11591: @end example
1.12      anton    11592: 
1.78      anton    11593: For inheritance, the vtable of the parent object has to be
                   11594: copied when a new, derived class is declared. This gives all the
                   11595: methods of the parent class, which can be overridden, though.
1.12      anton    11596: 
1.78      anton    11597: @example
1.79      anton    11598: : end-class  ( class selectors vars "name" -- )
1.78      anton    11599:   Create  here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
                   11600:   cell+ dup cell+ r> rot @@ 2 cells /string move ;
                   11601: @end example
1.12      anton    11602: 
1.78      anton    11603: The first line creates the vtable, initialized with
                   11604: @code{noop}s. The second line is the inheritance mechanism, it
                   11605: copies the xts from the parent vtable.
1.12      anton    11606: 
1.78      anton    11607: We still have no way to define new methods, let's do that now:
1.12      anton    11608: 
1.26      crook    11609: @example
1.79      anton    11610: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78      anton    11611: @end example
1.12      anton    11612: 
1.78      anton    11613: To allocate a new object, we need a word, too:
1.12      anton    11614: 
1.78      anton    11615: @example
                   11616: : new ( class -- o )  here over @@ allot swap over ! ;
1.12      anton    11617: @end example
                   11618: 
1.78      anton    11619: Sometimes derived classes want to access the method of the
                   11620: parent object. There are two ways to achieve this with Mini-OOF:
                   11621: first, you could use named words, and second, you could look up the
                   11622: vtable of the parent object.
1.12      anton    11623: 
1.78      anton    11624: @example
                   11625: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
                   11626: @end example
1.12      anton    11627: 
                   11628: 
1.78      anton    11629: Nothing can be more confusing than a good example, so here is
                   11630: one. First let's declare a text object (called
                   11631: @code{button}), that stores text and position:
1.12      anton    11632: 
1.78      anton    11633: @example
                   11634: object class
                   11635:   cell var text
                   11636:   cell var len
                   11637:   cell var x
                   11638:   cell var y
                   11639:   method init
                   11640:   method draw
                   11641: end-class button
                   11642: @end example
1.12      anton    11643: 
1.78      anton    11644: @noindent
                   11645: Now, implement the two methods, @code{draw} and @code{init}:
1.21      crook    11646: 
1.26      crook    11647: @example
1.78      anton    11648: :noname ( o -- )
                   11649:  >r r@@ x @@ r@@ y @@ at-xy  r@@ text @@ r> len @@ type ;
                   11650:  button defines draw
                   11651: :noname ( addr u o -- )
                   11652:  >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
                   11653:  button defines init
1.26      crook    11654: @end example
1.12      anton    11655: 
1.78      anton    11656: @noindent
                   11657: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79      anton    11658: new data and no new selectors:
1.78      anton    11659: 
                   11660: @example
                   11661: button class
                   11662: end-class bold-button
1.12      anton    11663: 
1.78      anton    11664: : bold   27 emit ." [1m" ;
                   11665: : normal 27 emit ." [0m" ;
                   11666: @end example
1.1       anton    11667: 
1.78      anton    11668: @noindent
                   11669: The class @code{bold-button} has a different draw method to
                   11670: @code{button}, but the new method is defined in terms of the draw method
                   11671: for @code{button}:
1.20      pazsan   11672: 
1.78      anton    11673: @example
                   11674: :noname bold [ button :: draw ] normal ; bold-button defines draw
                   11675: @end example
1.21      crook    11676: 
1.78      anton    11677: @noindent
1.79      anton    11678: Finally, create two objects and apply selectors:
1.21      crook    11679: 
1.26      crook    11680: @example
1.78      anton    11681: button new Constant foo
                   11682: s" thin foo" foo init
                   11683: page
                   11684: foo draw
                   11685: bold-button new Constant bar
                   11686: s" fat bar" bar init
                   11687: 1 bar y !
                   11688: bar draw
1.26      crook    11689: @end example
1.21      crook    11690: 
                   11691: 
1.78      anton    11692: @node Comparison with other object models,  , Mini-OOF, Object-oriented Forth
                   11693: @subsection Comparison with other object models
                   11694: @cindex comparison of object models
                   11695: @cindex object models, comparison
                   11696: 
                   11697: Many object-oriented Forth extensions have been proposed (@cite{A survey
                   11698: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
                   11699: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
                   11700: relation of the object models described here to two well-known and two
                   11701: closely-related (by the use of method maps) models.  Andras Zsoter
                   11702: helped us with this section.
                   11703: 
                   11704: @cindex Neon model
                   11705: The most popular model currently seems to be the Neon model (see
                   11706: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
                   11707: 1997) by Andrew McKewan) but this model has a number of limitations
                   11708: @footnote{A longer version of this critique can be
                   11709: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
                   11710: Dimensions, May 1997) by Anton Ertl.}:
                   11711: 
                   11712: @itemize @bullet
                   11713: @item
                   11714: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
                   11715: to pass objects on the stack.
1.21      crook    11716: 
1.78      anton    11717: @item
                   11718: It requires that the selector parses the input stream (at
1.79      anton    11719: compile time); this leads to reduced extensibility and to bugs that are
1.78      anton    11720: hard to find.
1.21      crook    11721: 
1.78      anton    11722: @item
1.79      anton    11723: It allows using every selector on every object; this eliminates the
                   11724: need for interfaces, but makes it harder to create efficient
                   11725: implementations.
1.78      anton    11726: @end itemize
1.21      crook    11727: 
1.78      anton    11728: @cindex Pountain's object-oriented model
                   11729: Another well-known publication is @cite{Object-Oriented Forth} (Academic
                   11730: Press, London, 1987) by Dick Pountain. However, it is not really about
                   11731: object-oriented programming, because it hardly deals with late
                   11732: binding. Instead, it focuses on features like information hiding and
                   11733: overloading that are characteristic of modular languages like Ada (83).
1.26      crook    11734: 
1.78      anton    11735: @cindex Zsoter's object-oriented model
1.79      anton    11736: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
                   11737: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
                   11738: describes a model that makes heavy use of an active object (like
                   11739: @code{this} in @file{objects.fs}): The active object is not only used
                   11740: for accessing all fields, but also specifies the receiving object of
                   11741: every selector invocation; you have to change the active object
                   11742: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
                   11743: changes more or less implicitly at @code{m: ... ;m}. Such a change at
                   11744: the method entry point is unnecessary with Zsoter's model, because the
                   11745: receiving object is the active object already. On the other hand, the
                   11746: explicit change is absolutely necessary in that model, because otherwise
                   11747: no one could ever change the active object. An ANS Forth implementation
                   11748: of this model is available through
                   11749: @uref{http://www.forth.org/oopf.html}.
1.21      crook    11750: 
1.78      anton    11751: @cindex @file{oof.fs}, differences to other models
                   11752: The @file{oof.fs} model combines information hiding and overloading
                   11753: resolution (by keeping names in various word lists) with object-oriented
                   11754: programming. It sets the active object implicitly on method entry, but
                   11755: also allows explicit changing (with @code{>o...o>} or with
                   11756: @code{with...endwith}). It uses parsing and state-smart objects and
                   11757: classes for resolving overloading and for early binding: the object or
                   11758: class parses the selector and determines the method from this. If the
                   11759: selector is not parsed by an object or class, it performs a call to the
                   11760: selector for the active object (late binding), like Zsoter's model.
                   11761: Fields are always accessed through the active object. The big
                   11762: disadvantage of this model is the parsing and the state-smartness, which
                   11763: reduces extensibility and increases the opportunities for subtle bugs;
                   11764: essentially, you are only safe if you never tick or @code{postpone} an
                   11765: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21      crook    11766: 
1.78      anton    11767: @cindex @file{mini-oof.fs}, differences to other models
                   11768: The @file{mini-oof.fs} model is quite similar to a very stripped-down
                   11769: version of the @file{objects.fs} model, but syntactically it is a
                   11770: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21      crook    11771: 
                   11772: 
1.78      anton    11773: @c -------------------------------------------------------------
1.150     anton    11774: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78      anton    11775: @section Programming Tools
                   11776: @cindex programming tools
1.21      crook    11777: 
1.78</